MongoDB:查询结果匹配数组中的任何值 [英] MongoDB: query result match any value in array
问题描述
我有一些文件:
{
"storeID" : "715R",
"sensorID" : [
"0BBA",
"0BB9"
]
}
{
"storeID" : "312R",
"sensorID" : [
"0BBB"
]
}
我想获取sensorID
的结果,该结果sotreID
匹配storeIDarray
中的任何值,例如['715R','312R','789R']
I want to get result of sensorID
which sotreID
match any value in storeIDarray
like ['715R','312R','789R']
在这种情况下,我想得到结果:sensorID
数组:[ "0BBA", "0BB9","0BBB"]
in this case I want get result : a sensorID
array : [ "0BBA", "0BB9","0BBB"]
我该怎么办?谢谢.
推荐答案
您应该查看 $in
运算符.
将其与查找配合使用,然后,为了加快请求速度,可以使用 lean
方法:使用它,mongoDB将返回JS对象,而不是Mongoose模型/对象.
You should take a look at the $in
operator in MongoDB.
Use it with a find, then, to make your request faster, you can use the lean
method : with it, mongoDB will return JS objects and not Mongoose model/objects.
YourModel.find({storeID: {$in: storeIDarray }}).lean().exec(yourCallback);
然后,您可以在结果数组上使用reduce
方法:
Then, you can use the reduce
method on the resulting array :
yourResult.reduce((acc, el) => acc.concat(el.sensorID), []);
希望有帮助,
最好的问候
Hope it helps,
Best regards
这篇关于MongoDB:查询结果匹配数组中的任何值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!