答案:
要计算两个集合之间的交集,需要使用MongoDB的聚合框架。下面是实现这个问题的一些步骤:
使用$lookup操作符将两个集合连接起来。
db.collection1.aggregate([
{
$lookup:
{
from: "collection2",
localField: "_id",
foreignField: "_id",
as: "result"
}
}
])
使用$unwind操作符将连接的结果展开成单个文档。
db.collection1.aggregate([
{
$lookup:
{
from: "collection2",
localField: "_id",
foreignField: "_id",
as: "result"
}
},
{
$unwind: "$result"
}
])
使用$match操作符将只包含匹配文档的结果过滤出来。
db.collection1.aggregate([
{
$lookup:
{
from: "collection2",
localField: "_id",
foreignField: "_id",
as: "result"
}
},
{
$unwind: "$result"
},
{
$match: { "result": { $exists: true } }
}
])
使用$project操作符仅返回需要的字段。
db.collection1.aggregate([
{
$lookup:
{
from: "collection2",
localField: "_id",
foreignField: "_id",
as: "result"
}
},
{
$unwind: "$result"
},
{
$match: { "result": { $exists: true } }
},
{
$project: { "_id": 1, "field1": 1, "field2": 1 }
}
])
上述聚合管道将集合1和集合2中的文档连接起来,然后使用$unwind和$match操作符过滤出交集。最后,使用$project操作符返回所需字段。