简体   繁体   中英

MongoDB: Find an element in an array

I have a simple array in my MongoDB collection:

"_id": "5669b4930874f8d01f7676da", "cars": ["BMW", "Audi", "VW"]

I now want to check if "Audi" is in that document. I've read through all questions on arrays here at SO but they focus all on array with objects inside, which isn't the case here.

db.collectionName.find({ cars: {$eq: "Audi"} })

doesn't work (it returns no document).

EDIT: It was my own stupidity, see my comment below on the best solution. So the above query was always working. Well, as they say the problem always sits in front of the keyboard ;-)

Neither does:

db.collectionName.find({ $elemMatch: { cars: "Audi" }})

It actually leads to the following error message:

error: {
"$err" : "Can't canonicalize query: BadValue unknown top level operator: $elemMatch",
"code" : 17287

or:

db.collectionName.find({ cars: { $in: "Audi" }})

This leads to the following error:

error: {
"$err" : "Can't canonicalize query: BadValue $in needs an array",
"code" : 17287

Tested with MongoDB version 2.6.7 via MongoDB shell. Thanks for your help!

you can simplify:

db.collectionName.find({ cars: "Audi" })

Should work perfectly.

db.collectionName.find({ cars: { $in: ["Audi"] }})

Could work too, but first is simpler.

this query seemed to work for me:

 db.cars.find({cars: {$elemMatch:{$eq:"BMW"}} })

result

{ "_id" : ObjectId("5669ca2ff0fbefa0650e5fb6"), "cars" : [ "Audi","BMW", "Honda" ] }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM