Search code examples
mongodbmongooseaggregation-framework

Find if a value is not present in array of objects mongodb


I would like to check if a field is not present in an array of objects. Let's say I have an array inside documents called attributes:

[
  {
    attributes: [
      {
        name: "Cool",
        value: true
      }
    ]
  }
]

And I wish to find items which are unspecified. I will use an $or operator to find empty values

$attributes: {
    $elemMatch: {
        $or: [
           { name: 'cool', value: '' },
           { name: 'cool', value: { $exists: false } },

           { name: {ne: 'cool' } ?????
        ]
    }
}

But I want to find items where {name: 'Cool'} just isn't in the array and I can't figure out the syntax.

Any help would be great, many thanks


Solution

  • Simple $ne usage will suffice outside an $elemMatch expression, Mongo "flattens" arrays for most queries so if a single element in the array matches the query it suffices the conditions.

    In your case if you use $ne and cool is one of the elements then the condition will be "matched" and the document excluded, like so:

    db.collection.find({
      "attributes.name": {
        $ne: "Cool"
      }
    })
    

    Mongo Playground