MongoDB查找两个查询结果之间的交集
我在MongoDB中有以下收藏:MongoDB查找两个查询结果之间的交集,mongodb,Mongodb,我在MongoDB中有以下收藏: { _id: 1, from: "from1", to: "to1" }, { _id: 2, from: "from1", to: "to2" }, { _id: 3, from: "from2", to: "to1" }, { _id: 4, from: "from1", to:
{
_id: 1,
from: "from1",
to: "to1"
},
{ _id: 2,
from: "from1",
to: "to2"
},
{ _id: 3,
from: "from2",
to: "to1"
},
{
_id: 4,
from: "from1",
to: "to3"
},
{ _id: 5,
from: "from2",
to: "to2"
},
{ _id: 6,
from: "from3",
to: "to1"
},
如果我必须列出:
f1 = ["from1", "from3"]
f2 = ["from2"]
我想从集合中的元素中找到所有“to”值,其中“from”在每个“from”值列表中,然后从这个结果中找到“to”值的交集
例如。
如果我执行以下查询:
db.collection.find({"from": {"$in": f1}}, {"to": 1, "_id": 0})
db.collection.find({"from": {"$in": f2}}, {"to": 1, "_id": 0})
我得到以下两个结果:
result1 = [{"to": "to1"}, {"to": "to2"}, {"to": "to3"}]
result2 = [{"to": "to1"}, {"to": "to2"}]
现在,我想要的是这两个结果的交集,最好是在一个列表中:
["to1", "to2"]
是否有一个查询允许我获得此结果?顺便说一句,我使用的是mongodb v3.2。我会在聚合中使用
$facet
。它将允许我们运行两个单独的$match
查询,然后合并结果,这将便于比较和找到您要查找的交叉点。下面是您需要的聚合:
db.collection.aggregate([
{
"$facet": {
"query1": [
{
$match: {
"from": {
"$in": ["from1", "from3"] // <- Match Query One
}
}
},
{
$group: {
_id: null,
tos: {
$push: "$to"
}
}
}
],
"query2": [
{
$match: {
"from": {
"$in": ["from2"] // <- Match Query Two
}
}
},
{
$group: {
_id: null,
tos: {
$push: "$to"
}
}
}
]
}
},
{
"$unwind": "$query1"
},
{
"$unwind": "$query2"
},
{
"$project": {
toIntersection: {
"$setIntersection": [
"$query1.tos",
"$query2.tos"
]
}
}
}
])
假设您使用node,您可以将其分配给如下变量:
const intersction = result[0].toIntersection; //<-- gives you ["to1", "to2"]
const intersection=result[0]。toIntersection//是的,这个解决方案正是我想要的!但是,我的MongoDB 3.2版无法使用它$facet
。无论如何我都会接受这个答案。谢谢
const intersction = result[0].toIntersection; //<-- gives you ["to1", "to2"]