Find documents where all objects in array have specific value

Viewed 55

I have the following documents in MongoDB:

{
    name: "document1",
    data: [{
        name: "xxxxx",
        status: "delivered"
    },{
        name: "xxxxx",
        status: "In Process"
    },{
        name: "xxxxx",
        status: "Not Started"
    }]
},{
    name: "document2",
    data: [{
        name: "xxxxx",
        status: "delivered"
    },{
        name: "xxxxx",
        status: "delivered"
    },{
        name: "xxxxx",
        status: "delivered"
    }]
}

I want to find all documents where all objects inside the "data" array have the status "delivered", I used to use $ne: 'Not Started', but now that more status options have been introduced, this doesn't work. Perhaps I could do a $ne: $and and include all negative options, but any new status will give issues.

2 Answers

You can use $not with $elemMatch

db.collection.find({
  "data": {
    "$not": {
      "$elemMatch": {
        "status": {
          $ne: "delivered"
        }
      }
    }
  },
  "data.status": "delivered"
})

Here is fiddle https://mongoplayground.net/p/digdoFC6yF0

You can use $not.

{
  $and: [
     { 'data.status': { $not: /Not Started/},
     {'data.status': "delivered"}
  ]
}

Note that $not must receive a regex and not just plain string.

Related