Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query to match a non-empty array with a certain 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.

like image 222
smartnut007 Avatar asked Mar 15 '26 04:03

smartnut007


1 Answers

The simplest way is to test for the presence of an array element using $exists and "dot notation":

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

Says find "a" equal to 5, but the first array element in "a" cannot exist.

like image 185
Neil Lunn Avatar answered Mar 16 '26 22:03

Neil Lunn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!