Kiwi breeder
Kiwi breeder

Reputation: 627

Aggregate match documents using nested documents

I have a document structure as so:

{
   "name": "Bob",
   "configurations": [
      {
         "version": 0,
         "isValid": true,
         "isPublished": false
      },
      {
         "version": 1,
         "isValid": false,
         "isPublished": true
      }
   ]
}

I wish to find all such document where there exists a configuration where both isValid is true and isPublished is true. For such a query, the example I gave above should not be returned since the none of the configurations have both of the flags set as true.

I first tried something like:

coll.aggregate([
   {
      $match: {
         "configurations.isValid": true,
         "configurations.isPublished": true
      }
   }
])

This isn't what I want because this simply checks if there exists a configuration with isValid set to true and if there also exists another configuration with isPublished set to true. I tried fixing this via:

coll.aggregate([
   {
      $match: {
         "permissions": {
            "isValid": true,
            "isPublished": true
         }
      }
   }
])

but this returns zero results. Any ideas?

EDIT:

Figured it out:

coll.aggregate([
   {$match: { configurations: { $elemMatch: { $and: [ {isValid: true}, {isPublished: true}  ] } } }}  
])

Upvotes: 0

Views: 32

Answers (1)

Gibbs
Gibbs

Reputation: 22974

Playground

$elemMatch will help you to find arrays with condition matches.

db.collection.find({
  configurations: {
    "$elemMatch": {
      "isValid": true,
      "isPublished": true
    }
  }
})

For aggregation, Example, Simply use the above in $match

Upvotes: 1

Related Questions