MongoDB:检查嵌套数组是否包含子数组 [英] MongoDB: Checking if nested array contains sub-array

查看:751
本文介绍了MongoDB:检查嵌套数组是否包含子数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用例,其中数据库的建模如下:

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:

我将获得ID和值的列表. 例如:给定的列表如下:

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']
}]

简而言之,ID应该匹配,并且注释应该是该ID的注释数组的子数组,而且,数组中指定的所有条件都应该匹配,因此在所有条件.

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.

我能够进入此查询,但是它与comments数组中的所有元素都匹配,我希望ID应该完全匹配,并且注释应该是子数组.

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']
    }]
 }})

推荐答案

您可以尝试使用$all$elemMatch来匹配查询条件.

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']
                }
            }
        }, ]
    }
})

这篇关于MongoDB:检查嵌套数组是否包含子数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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