3

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!

1

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This appears to work, with the addition of an exists and size check on arr. Thanks!
0

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]})

3 Comments

Correct, the $all operator seems to return if any value is null (including arr itself). Unfortunately, it is unknown how many values an array will have, so I will be unable to construct a literal array for comparison.
It seems like an odd requirement. Perhaps there's another approach to solving. Can you share more details regarding your use case and examples?
Simply put, I need to be able to filter documents who have homogeneous data in an array. For example, say driver1 and driver2 have the following entries in db.drivers: {_id: "driver1" , record: ["win", "win", "win"]}, {_id: "driver2", record: ["win"]}. Given this data, I would want to query db.drivers for all drivers with a perfect record, which would return both in this case.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.