1

有一个数组,例如:

var arr = ["1","1.1","1.3","2","2.1","2.2","2.3"]

和一个 Collection A ,就像这样

[
  {_id:"1",儿童:["1.1","1.4"]},
  {_id:"2",儿童:["2.1","2.2"]},
  {_id:"3",children:["3.1","3.2"]}
]

经过

寻找({....})
我想得到结果

[
  {_id:"1",儿童:["1.1"]},
  {_id:"2",儿童:["2.1","2.2"]},
]

结果子数组是 arr和集合A的交集children

如何设置查询运算符?

4

2 回答 2

3

这也不是您正在寻找的确切答案,但您可以使用$in运算符非常接近:

db.i.find({
  children : { $in : arr}
})

请记住,这不会产生上述结果(它将输出数组中的所有值而不是{_id:"1",children:["1.1"]},)。

但是您可以按照我的建议,然后在您的应用程序中遍历所有结果并仅输出子节点与您的数组的交集。

于 2013-10-29T04:26:20.830 回答
2

您无法通过简单的查询(查找)获得所需的结果,但您可以使用聚合框架来实现。就是这样:

var arr = ["1","1.1","1.3","2","2.1","2.2","2.3"]

db.A.aggregate([ { "$unwind" : "$children" }, 
                 { "$match"  : { "children" : { "$in" : arr } } },
                 { "$group"  : { "_id" : "$_id", "children" : { "$push" : "$children" } } }
               ]
);

样本数据的结果:

{ "_id" : "2", "children" : [  "2.1",  "2.2" ] }
{ "_id" : "1", "children" : [  "1.1" ] }
于 2013-10-29T04:51:11.587 回答