Query against a non-empty array with a specific value

for example

> db.test.insert( { 'a':5 } )
> db.test.insert( { 'a': [5] } )

> db.test.find({ 'a':5})
{ "_id" : ObjectId("53e2b4366c9ef5cceb327e01"), "a" : 5 }
{ "_id" : ObjectId("53e2b43b6c9ef5cceb327e02"), "a" : [ 5 ] }

      

But I only want to be able to match the first document.

+3


source to share


1 answer


The easiest way is to check for the existence of an array element using and "dot notation": $exists

db.test.find({ "a": 5, "a.0": { "$exists": false } })

      



Says that "a" is 5, but the first array element in "a" cannot exist.

+5


source







All Articles