Reputation: 397
Collection:
db.test.find()
{
{ "_id" : ObjectId(...), "arr" : [ "Today", "is", null ] }
{ "_id" : ObjectId(...), "arr" : [ null, null, null ] }
}
I'm trying to find all documents where all of arr
equals some value. In this example, I would want the document containing arr : [null, null, null]
when given null
.
Find documents where ALL elements of an array have a specific value
This solution is close to what I want; however, my array data do not have keys for an $elemMatch
to reference. Is there a way to accomplish this query without being unnecessarily costly or restructuring my data?
Thanks!
Upvotes: 3
Views: 4588
Reputation: 75914
You can use $elemMatch
query operator. It just needs a query.
db.test.find( { arr: { $not: { $elemMatch: { $ne: null } } } } )
"$elemMatch" + "$ne"
This part includes all the documents where arr
array don't have at least one null value.
These are all the documents which has at least one not null value.
$not
This part will keep the all the documents which are not in "$elemMatch" + "$ne"
.
These are all the documents that has its all of values as null
.
Please accommodate edge cases where field doesn't exist to make sure things work as expected.
Upvotes: 3
Reputation: 9497
You can use the the $all operator, but the semantics might not be exactly what you want.
db.test.find({ arr: { $all: [null] } })
That would return both of your test documents.
If you really want to query for an array with 3 null values, you can just query for the literal array:
db.test.find({arr:[null,null,null]})
Upvotes: 0