首页 文章

如何在find({})中处理数组交集?

提问于
浏览
0

有一个数组,例如:

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

和A一样,就像这样

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

通过

find({....})

我想得到结果

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

结果children的数组是 arr 和collection Achildren 的交集

我该如何设置查询运算符?

2 回答

  • 1

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

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

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

    但你可以按照我的建议,然后在你的应用程序中迭代所有结果,并只输出你的数组的子项交集 .

  • 1

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

    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" ] }
    

相关问题