没有字段名称的mongodb查询 [英] mongodb query without field name
问题描述
我想查询所有具有包含特定值的字段的对象.例如,我有两个文档:
I would like query all objects that have a field containing a specific value. For example, I have two documents:
{"123": "apple", "217": "pear", "179": "orange"}
{"831": "pear", "189": "grapes"}
,并希望获取具有值为"apple"的字段的所有对象,但我不知道该字段的名称.是否可以在MongoDB中指定查询来实现此目的? (对象中的数字键是子代id,而对象中的值是长GUID)
and would like to get all objects that has a field whose value is "apple", but I do not know the name of the field. Is it possible to specify a query in MongoDB to achieve this? (The numerical keys in the objects are children ids, and the values in the objects are long GUIDs)
推荐答案
不幸的是,MongoDB不支持任何查询具有特定值的所有字段的方法.现有的Jira票证要求进行此增强: https://jira.mongodb.org/browse/SERVER -1248 .随意发表评论,投票或关注该票证.
Unfortunately, MongoDB does not support any method of querying all fields with a particular value. There is an existing Jira ticket requesting this enhancement: https://jira.mongodb.org/browse/SERVER-1248 . Feel free to comment, vote, or follow that ticket.
同时,处理此问题的通常方法是更改MongoDB模式.对于您的示例,您将更改现有架构:
In the meantime, the usual way that this is handled is to change the MongoDB schema. For your example, you would change your existing schema:
{"123": "apple", "217": "pear", "179": "orange"}
{"831": "pear", "189": "grapes"}
您可能会像这样构造它:
And you might structure it something like this:
{ tags: [
{ cid: "123", value: "apple" },
{ cid: "217", value: "pear" },
{ cid: "179", value: "orange" },
]
}
{ tags: [
{ cid: "831", value: "pear" },
{ cid: "189", value: "grapes" },
]
}
完成此操作后,您可以执行以下查询以查找所有所需文档:
Once you've done this, you can perform the follwing query to find all of the desired documents:
db.docs.find( {'tags.value': "apple" } )
请注意,该架构允许您索引'tags.cid'和'tags.value'字段,而原始架构则没有.
Note that this schema allows you to index the 'tags.cid' and 'tags.value' fields, which your original schema does not.
我希望这会有所帮助.
-威廉
这篇关于没有字段名称的mongodb查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!