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
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
andcool
is one of the elements then the condition will be "matched" and the document excluded, like so:Mongo Playground
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.
This query returns the documents where any name in the results array is not "Cool".
This query returns the documents where all of the name in the results array are not "Cool".