MongoDB查询帮助-查询子对象中任何键的值 [英] MongoDB Query Help - query on values of any key in a sub-object

查看:330
本文介绍了MongoDB查询帮助-查询子对象中任何键的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对此集合执行查询,以确定哪些文档中的任何键具有与特定值匹配的键.这可能吗?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆