MongoDB 查询帮助 - 查询子对象中任意键的值 [英] MongoDB Query Help - query on values of any key in a sub-object
问题描述
我想对该集合执行查询,以确定哪些文档在与某个值匹配的事物中具有任何键.这可能吗?
I want to perform a query on this collection to determine which documents have any keys in things that match a certain value. Is this possible?
我有一组文档,例如:
{
"things": {
"thing1": "red",
"thing2": "blue",
"thing3": "green"
}
}
为了简洁
推荐答案
我建议更改架构,以便您可以在 MongoDB 中实际进行合理的查询.
I'd suggest a schema change so that you can actually do reasonable queries in MongoDB.
来自:
{
"userId": "12347",
"settings": {
"SettingA": "blue",
"SettingB": "blue",
"SettingC": "green"
}
}
到:
{
"userId": "12347",
"settings": [
{ name: "SettingA", value: "blue" },
{ name: "SettingB", value: "blue" },
{ name: "SettingC", value: "green" }
]
}
然后,您可以对 "settings.value"
进行索引,并执行如下查询:
Then, you could index on "settings.value"
, and do a query like:
db.settings.ensureIndex({ "settings.value" : 1})
db.settings.find({ "settings.value" : "blue" })
更改确实很简单...,因为它将设置名称和设置值移动到完全可索引的字段,并将设置列表存储为数组.
The change really is simple ..., as it moves the setting name and setting value to fully indexable fields, and stores the list of settings as an array.
如果您无法更改架构,您可以尝试 @JohnnyHK 的 解决方案,但请注意,就性能而言,这基本上是最坏的情况,并且无法有效地使用索引.
If you can't change the schema, you could try @JohnnyHK's solution, but be warned that it's basically worst case in terms of performance and it won't work effectively with indexes.
这篇关于MongoDB 查询帮助 - 查询子对象中任意键的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!