David Parkinson
David Parkinson

Reputation: 25

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

Upvotes: 1

Views: 5925

Answers (2)

Gaurav Sharma
Gaurav Sharma

Reputation: 633

I faced a similar use case where any element in the array is not matching with the searched value. So, I am extending the answer to this question.

If you specify a single query predicate in the $elemMatch expression, and are not using the $not or $ne operators inside of $elemMatch , $elemMatch can be omitted. reference

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

This query returns the documents where any name in the results array is not "Cool".

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

This query returns the documents where all of the name in the results array are not "Cool".

Upvotes: 1

Tom Slabbaert
Tom Slabbaert

Reputation: 22276

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

Upvotes: 4

Related Questions