表1
{
"_id" : "123",
"name" : "A",
},
{
"_id" : "234"
"name" : "B",
}
table2
{
"_id" : "432",
"language" : "Hindi"
},
{
"_id" : "345345",
"language" : "Hindi"
}
table3
{
"_id" : "3498",
"film" : {
"kannada" : [
"200"
],
}
}
第1步
我必须从表1 中获取_id,然后再检查表2 ,然后从表2 中获取language
第2步
我们必须检查是否将此language
映射到 table3 集合?。
预期输出:
["100"]
答案 0 :(得分:0)
您可以使用以下汇总:
db.UserDetails.aggregate(
{
$lookup: {
from: "UserProducts",
localField: "UID",
foreignField: "UID",
as: "userProduct"
}
},
{ $unwind: "$userProduct" },
{
"$project": { "_id" : 0, "userProduct.UPID" : 1 }
},
{
$group: {
_id: null,
userProductUPIDs: { $addToSet: "$userProduct.UPID" }
}
},
{
$lookup: {
from: "Groups",
pipeline: [
{ $unwind: "$members.regularStudent" },
{ $project: { _id: 0, value: "$members.regularStudent" } }
],
as: "UPID"
}
},
{
$addFields: {
UPID: {
$map: {
input: "$UPID",
as: "x",
in: "$$x.value"
}
}
}
},
{
$project: {
result: {
$setDifference: [ "$userProductUPIDs", "$UPID" ]
}
}
}
)
基本上,目标是获得具有两个数组的单个文档来执行$setDifference。您已经拥有合适的部分(只需要添加$group),并且您需要$lookup with custom pipeline才能将Groups
中的所有数据收集到一个集合中。输出:
{ "_id" : null, "result" : [ "100" ] }
编辑:要使用自定义管道运行$lookup
,您需要MongoDB 3.6或更高版本。或者,您必须运行两次聚合,然后在应用程序逻辑中比较两个结果:
var queryResult = db.UserDetails.aggregate(
{
$lookup: {
from: "UserProducts",
localField: "UID",
foreignField: "UID",
as: "userProduct"
}
},
{ $unwind: "$userProduct" },
{
"$project": { "_id" : 0, "userProduct.UPID" : 1 }
},
{
$group: {
_id: null,
userProductUPIDs: { $addToSet: "$userProduct.UPID" }
}
}
) // returns [ "100", "200" ]
let userProductUPIDs = queryResult.toArray()[0].userProductUPIDs;
db.Groups.aggregate([
{
$unwind: "$members.regularStudent"
},
{
$group: {
_id: null,
UPIDs: { $addToSet: "$members.regularStudent" }
}
},
{
$project: {
members: {
$setDifference: [ userProductUPIDs , "$UPIDs" ]
},
_id : 0
}
}
])