Home > Enterprise >  Is it possible to write a Mongo query that validates a condition in each element of an array?
Is it possible to write a Mongo query that validates a condition in each element of an array?

Time:08-10

Consider the following documents:

{
   _id: 1,
   a: [{b:true},{b:true}]
},
{
   _id: 2,
   a: [{b:false},{b:true}]
},
{
   _id: 3,
   a: [{b:true}]
}

I'd like to write a query that will return all of the top level documents that have an array ("a") that contain only elements matching {b : true}. In this example, I'm expecting the first and third document to be returned, but not the second.

When writing the query like this, all 3 documents are returned.. {a : {b : true}}

Is there an operator that I'm missing? I've reviewed quite a few of them ($all) and I'm not sure which would match best for this use case

Thanks so much

CodePudding user response:

Simply use $allElementsTrue on the array a.b.

db.collection.find({
  $expr: {
    "$allElementsTrue": "$a.b"
  }
})

Here is the Mongo Playground for your reference.

  • Related