[英]Mongo Query to search one or more values are present in an array field of a document
I have a collection like below 我有如下收藏
{
_id: ObjectId(),
account_number: someID,
account_context: {acnt_id:"1234",acnt_name:"Akhil",address:"Kadapa"},
tags:["tag","TaG","User","tag2","usr"]
},
{
_id: OBjectId(),
account_number: someID,
account_context: {acnt_id:"1234",acnt_name:"Akhil",address:"Kadapa"},
tags:["gat","GaT","Hello","tag2","Usr"]
}
I would like to query based on tags. 我想根据标签查询。 If I search for "tag" and "gat" , I should get both the documents If I search for "Tag" , I should get first document If I search for "tag" and "Hello", I should get both the documents.
如果我搜索“ tag”和“ gat”,则应同时获取两个文档。如果我搜索“ Tag”,则应获取第一个文档。如果我搜索“ tag”和“ Hello”,则应同时获取两个文档。
Which means if the search field match for any one of the array element in the document I should get that document. 这意味着如果搜索字段与文档中的任何一个数组元素匹配,我都应该获取该文档。
How can I get that? 我该怎么办?
you can use $elemMatch
with $in
for this problem like it: 您可以将
$elemMatch
与$in
$elemMatch
使用$in
以解决以下问题:
var searchedArray = ["tag","Hello"]
collection.find({
tags: {$elemMatch: {$in:searchedArray}}
}, (err, result)=>{
})
$elemMatch
check all elements of an array with her expression. $elemMatch
使用她的表达式检查数组的所有元素。 my expression is $in
that check filed with all values is there in searchedArray
if equal accept it. 我的表达式是
$in
,如果相等,则在searchedArray
存在带有所有值的支票文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.