简体   繁体   English

MongoDB:在数组中查找元素

[英]MongoDB: Find an element in an array

I have a simple array in my MongoDB collection: 我的MongoDB集合中有一个简单的数组:

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

I now want to check if "Audi" is in that document. 我现在要检查该文档中是否包含“ Audi”。 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. 通过MongoDB Shell在MongoDB 2.6.7版中进行了测试。 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" ] }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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