skip to Main Content

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

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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".

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search