搜索数组中的元素并在mongodb中返回匹配的元素 [英] Searching for elements in array and return matching elements in mongodb
本文介绍了搜索数组中的元素并在mongodb中返回匹配的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下文件
db.c.save({a:[{u:3},{u:6},{u:123}]});
我想从数组中获取匹配的元素.因此,我使用以下查询来做到这一点.
I want to fetch matching elements from the array. So I use the following query to do it.
db.c.find({'a.u':{$in:[3,123]}},{'a.$':1});
这给了我{ "a" : [ { "u" : 3 } ] }
,但我想它应该返回{ "a" : [ { "u" : 3 }, { "u" : 123 } ] }
This gives me { "a" : [ { "u" : 3 } ] }
but I guess it should return { "a" : [ { "u" : 3 }, { "u" : 123 } ] }
有什么建议吗?
推荐答案
不幸的是, $ positional operator 仅返回第一个匹配项,因此您不能使用它来完成您要尝试做的事情.
Unfortunately, the $ positional operator only returns the first match so you can't use it to do what you are trying to do.
但是,您可以使用聚合或
However, you can use either aggregation or map-reduce. The following code does what you want using the aggregation framework :
db.c.aggregate([
{ $unwind : "$a"},
{ $match : { "a.u" : {$in :[3,123]} } },
{ $group : {_id : "$_id",a : { $push : "$a" } } }
])
这篇关于搜索数组中的元素并在mongodb中返回匹配的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文