MongoDB: Checking if nested array contains sub-array

可紊 提交于 2019-12-20 06:32:11

问题


I have a use case where the database is modelled like this:

name: XYZ
gradeCards: [{
  id: 1234, // id of the report card
  comments: ['GOOD','NICE','WOW']
}, {
  id: 2345,
  comments: ['GOOD','NICE TRY']
}]

Now, I have a query that I would like to query the schema as follows:

I would be given a list of ids and values. For example: the given list is as follows:

[{
  id: 1234,
  comments: ['GOOD','NICE']
},{
  id: 2345,
  comments: ['GOOD']
}]

In short the ID should be matching and the comments should be a sub-array of the comments array for that id and also, all the conditions specified in the array should be matched, so it should be an AND condition on all the conditions provided.

I was able to get to this query, but it matches all of the elements in the comments array, I want that id should be exactly matched and comments should be a subarray.

For matching all elements in comments array:

db.getCollection('user').find({arr:{
    $all: [{
        id:1234,
        comments:['GOOD','NICE','WOW']
    },{
        id:2345,
        comments:['GOOD','NICE TRY']
    }]
 }})

回答1:


You can try $all with $elemMatch to match on the query conditions.

db.collection.find({
    gradeCards: {
        $all: [{
            "$elemMatch": {
                id: 1234,
                comments: {
                    $in: ['GOOD', 'NICE']
                }
            }
        }, {
            "$elemMatch": {
                id: 2345,
                comments: {
                    $in: ['GOOD']
                }
            }
        }, ]
    }
})


来源:https://stackoverflow.com/questions/42748763/mongodb-checking-if-nested-array-contains-sub-array

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