Mongo用未知的父键查找值 [英] Mongo find value with unknown parent key
问题描述
我在 Mongo 表中寻找一个值,该值的父键可能没有描述性或已知名称.这是我们的一个文档的示例.
I am looking for a value in a Mongo table where its parent key might not have a descriptive or known name. Here is an example of what one of our documents looks like.
{
"assetsId": {
"0": "546cf2f8585ffa451bb68369"
},
"slotTypes": {
"0": { "usage": "json" },
"1": { "usage": "image" }
}
}
我想看看这是否在 slotTypes 中包含 "usage": "json",但我不能保证此用法的父键为 "0".
I am looking to see if this contains "usage": "json" in slotTypes, but I can't guarantee that the parent key for this usage will be "0".
我尝试使用以下查询但没有任何运气:
I tried using the following query without any luck:
db.documents.find(
{
slotTypes:
{
$elemMatch:
{
"usage": "json"
}
}
}
)
如果这是一个非常基本的问题,请提前抱歉,但我不习惯在 nosql 数据库中工作.
Sorry in advance if this is a really basic question, but I'm not used to working in a nosql database.
推荐答案
我不确定你是否能够用你当前的模式优雅地解决这个问题;slotTypes
应该是一个子文档数组,这将允许您的 $elemMatch
查询工作.现在,它是一个带有数字键的对象.
I'm not sure you're going to be able to solve elegantly this with your current schema; slotTypes
should be an array of sub-documents, which would allow your $elemMatch
query to work. Right now, it's an object with numeric-ish keys.
也就是说,您的文档架构应该类似于:
That is, your document schema should be something like:
{
"assetsId": {
"0": "546cf2f8585ffa451bb68369"
},
"slotTypes": [
{ "usage": "json" },
{ "usage": "image" }
]
}
如果无法更改数据布局,那么您基本上需要扫描每个文档以找到与 $where
匹配的内容.这很慢,无法编入索引,而且很笨拙.
If changing the data layout isn't an option, then you're going to need to basically scan through every document to find matches with $where
. This is slow, unindexable, and awkward.
db.objects.find({$where: function() {
for(var key in this.slotTypes) {
if (this.slotTypes[key].usage == "json") return true;
}
return false;
}})
您应该阅读 $where 上的文档 以确保您了解它,以及对所有神圣事物的热爱,净化您对该功能的输入;这是在您的数据库上下文中执行的实时代码.
You should read the documentation on $where to make sure you understand the caveats of it, and for the love of all that is holy, sanitize your inputs to the function; this is live code that is executing in the context of your database.
这篇关于Mongo用未知的父键查找值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!