mongodb query nested structure

↘锁芯ラ 提交于 2019-12-11 03:43:23

问题


How can I query this nested json structure in order to find documents that contain "A"?

"categories":[{"id":12,"values":[["A","B","C"]]},{"id":17,"values":[["D","E","F"]]}]

So far, I only managed to get to the id value with

db.coll.find( {categories: { $elemMatch: { id: 12 }}} )

回答1:


You need to nest the $elemMatch operators to match the nested levels of your arrays to match the element:

db.coll.find({
    "categories": { 
        "$elemMatch": { 
            "values": { 
                "$elemMatch": {
                    "$elemMatch": { "$in": ["A"] }
                }
            }
        }
    }
})



回答2:


Although Neil's answer will work, you can do it with only two $elemMatch operators, instead of three to make it simpler.

You can use dot notation to get to the values property and then you can use nested $elemMatch operators to check the nested array value:

db.coll.find({
    "categories.values" : { 
        $elemMatch : { 
            $elemMatch : { $in : ["A", "B"] }
        }
    }
});


来源:https://stackoverflow.com/questions/24520874/mongodb-query-nested-structure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!