当父键未知时,按值查询MongoDB [英] Query MongoDB by value when parent key is unknown

查看:47
本文介绍了当父键未知时,按值查询MongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为references的MongoDB集合,该集合具有一个文档,在该文档中,我需要返回所有具有名为format且值为1的键的对象.该文档的示例如下所示:

I have a MongoDB collection called references that has a document where I need to return all the objects that have a key called format with the value of 1. An example of the document looks like this:

{
    "_id" : ObjectId("878f92ad6d9e8089aa3456a9"),
    "categories" : {
            "1" : {
                    "format" : 1,
                    ...
            }
    }
}

我已经尝试过:

db.references.find({
    "_id" :  ObjectId("878f92ad6d9e8089aa3456a9"), 
    "categories.$.format" : 1
}).pretty();

还有这个:

db.references.find({
    "_id" :  ObjectId("878f92ad6d9e8089aa3456a9"), 
    "categories.*.format" : 1
}).pretty();

而这两个都不返回任何内容.

and both of those are returning nothing.

推荐答案

我认为架构设计不是很好.具有如下所示的架构设计:

I think schema design is not quite well. Having a schema design like the following:

{
    "_id" : ObjectId("57fbe76f78c1638eaebfb21f"),
    "categories" : [
        {
            "cat_name" : 1,
            "format" : 1
        },
        {
            "cat_name" : 2,
            "format" : 6
        }
    ]
}

更有意义,通过这种方式,您可以简单地使用点符号来访问嵌入式类别文档的format字段.您请求的查询可以是:db.stackQuestion.find({ "categories.format": 1 })

Makes much more sense, this way you can access the format field of the embedded category documents simply using dot notation. The query you requested can be: db.stackQuestion.find({ "categories.format": 1 })

这篇关于当父键未知时,按值查询MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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