简体   繁体   English

如果Mongoose数组中包含元素,则查找Mongodb文档

[英]Find a Mongodb document if it contains an element in the array in mongoose

If I have a field in a mongodb document which has an array, for example: 如果我在mongodb文档中有一个具有数组的字段,例如:

"tags" : [  "tag", "etc1",  "etc2",  "etc3" ]

Is there a way that I can select that document if it contains the element 'etc1'? 如果该文档包含元素“ etc1”,是否可以选择该文档?
If I try using the query: 如果我尝试使用查询:

db.coll.find({"tags" : { $elemMatch: { value0: 'etc1'} }})

but I need to know the position of the element in the array, which I don't know. 但是我需要知道元素在数组中的位置,我不知道。
I have also tried: 我也尝试过:

db.coll.find({"tags" : { $elemMatch: 'etc1' }})

but it needs to be an object. 但它必须是一个对象。 Is there any way of doing this? 有什么办法吗?

NB I am using mongoose but I wasn't sure how to construct the query 注意:我正在使用猫鼬,但不确定如何构造查询

Use the $in operator as described in this question or this other question and as described in the mongodb docs and can be accessed in mongoose . 使用$in运算符,如本问题其他问题中所述,以及mongodb文档中所述 ,可以在mongoose中进行访问

With it, you'll have a query that looks something like this... remembering that you must pass an array when using $in : 有了它,您将得到一个看起来像这样的查询... 请记住,在使用$ in时必须传递一个数组

db.coll.find({"tags" : { $in : ['etc1'] } } );

除了使用$ in运算符,您还可以使用$ all运算符,例如:

db.col1.find({"tags":{$all :["etc1"]}})

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

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