Maulik Soneji
Maulik Soneji

Reputation: 177

MongoDB: Checking if nested array contains sub-array

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

Upvotes: 0

Views: 2265

Answers (1)

s7vr
s7vr

Reputation: 75964

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

Upvotes: 2

Related Questions