MongoDB: 检查嵌套数组是否包含子数组

MongoDB: Checking if nested array contains sub-array

我有一个这样的数据库建模用例:

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

现在,我有一个查询,我想按如下方式查询架构:

我会得到一个 ID 和值列表。 例如:给出的列表如下:

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

简而言之,ID 应该是匹配的,comments 应该是该 id 的 comments 数组的子数组,而且数组中指定的所有条件都应该匹配,所以它应该是一个 AND 条件提供的所有条件。

我能够得到这个查询,但它匹配评论数组中的所有元素,我希望 id 应该完全匹配并且评论应该是一个子数组。

用于匹配评论数组中的所有元素:

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

您可以尝试$all$elemMatch来匹配查询条件。

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