如何处理find({})中的数组交集? [英] How can I handle array intersection in find({})?

查看:84
本文介绍了如何处理find({})中的数组交集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个数组,例如:

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

和一个收藏集A,就像这样

and a Collection A ,just like this


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

by

find({....})

我想得到结果


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

结果子数组是arr和集合Achildren

the result children's array is the intersection that arr and collection A's children

如何设置查询运算符?

推荐答案

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

You can't achieve the result you want via a simple query (find) but you can do it using the aggregation framework. Here's how:

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

这篇关于如何处理find({})中的数组交集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆