问题描述
UserDetails
UserDetails
{
"_id" : "5c23536f807caa1bec00e79b",
"UID" : "1",
"name" : "A",
},
{
"_id" : "5c23536f807caa1bec00e78b",
"UID" : "2",
"name" : "B",
},
{
"_id" : "5c23536f807caa1bec00e90",
"UID" : "3",
"name" : "C"
}
UserProducts
UserProducts
{
"_id" : "5c23536f807caa1bec00e79c",
"UPID" : "100",
"UID" : "1",
"status" : "A"
},
{
"_id" : "5c23536f807caa1bec00e79c",
"UPID" : "200",
"UID" : "2",
"status" : "A"
},
{
"_id" : "5c23536f807caa1bec00e52c",
"UPID" : "300",
"UID" : "3",
"status" : "A"
}
组
{
"_id" : "5bb20d7556db6915846da55f",
"members" : {
"regularStudent" : [
"200" // UPID
],
}
},
{
"_id" : "5bb20d7556db69158468878",
"members" : {
"regularStudent" : {
"0" : "100" // UPID
}
}
}
第1步
我必须从 UserDetails 中获取UID,并与 UserProducts 进行核对,然后从 UserProducts
I have to take UID from UserDetails check with UserProducts then take UPID
from UserProducts
第2步
我们必须检查是否映射到 Groups 集合的UPID
吗?members.regularStudent
我们被映射为UPID
we have to check this UPID
mapped to Groups collection or not ?.members.regularStudent
we are mapped UPID
第3步
假设未映射 UPID ,这意味着我要从 UserProducts
Suppose UPID not mapped means i want to print the UPID from from UserProducts
我已经尝试过但无法完成,请帮我解决这个问题.
I have tried but couldn't complete this, kindly help me out on this.
["300"]
注意:预期输出为["300"]
,因为 UserProducts 具有UPID 100 & 200
但 Groups 集合仅映射了100
& 200
.
Note: Expected Output is ["300"]
, because UserProducts having UPID 100 & 200
but Groups collection mapped only 100
& 200
.
我的代码
var queryResult = db.UserDetails.aggregate(
{
$lookup: {
from: "UserProducts",
localField: "UID",
foreignField: "UID",
as: "userProduct"
}
},
{ $unwind: "$userProduct" },
{ "$match": { "userProduct.status": "A" } },
{
"$project": { "_id" : 0, "userProduct.UPID" : 1 }
},
{
$group: {
_id: null,
userProductUPIDs: { $addToSet: "$userProduct.UPID" }
}
});
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
}
}
])
{
"members" : [
"300",
"100"
]
}
推荐答案
您需要修复第二个聚合并将所有UPIDs
作为数组获取.为此,您可以使用 $ cond 并基于 $ type 返回数组或使用 $ objectToArray 运行转换,请尝试:
You need to fix that second aggregation and get all UPIDs
as an array. To achieve that you can use $cond and based on $type either return an array or use $objectToArray to run the conversion, try:
db.Groups.aggregate([
{
$project: {
students: {
$cond: [
{ $eq: [ { $type: "$members.regularStudent" }, "array" ] },
"$members.regularStudent",
{ $map: { input: { "$objectToArray": "$members.regularStudent" }, as: "x", in: "$$x.v" } }
]
}
}
},
{
$unwind: "$students"
},
{
$group: {
_id: null,
UPIDs: { $addToSet: "$students" }
}
},
{
$project: {
members: {
$setDifference: [ userProductUPIDs , "$UPIDs" ]
},
_id : 0
}
}
])
这篇关于如何在数组&中设置$ setDifference使用Mongo DB的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!