用户详细信息

{
    "_id" : "5c23536f807caa1bec00e79b",
    "UID" : "1",
    "name" : "A",
},
{
    "_id" : "5c23536f807caa1bec00e78b",
    "UID" : "2",
    "name" : "B",
},
{
"_id" : "5c23536f807caa1bec00e90",
"UID" : "3",
"name" : "C"
}

用户产品
{
    "_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获取UPID
步骤2
我们必须检查这个UPID是否映射到组集合?.
members.regularStudent我们被映射到UPID
步骤3
假设upid未映射意味着我想从userproducts打印upid
我试过了,但没能完成,请帮我解决这个问题。
预期产量:
["300"]

注意:预期输出是["300"],因为用户产品具有upid100 & 200,但组集合只映射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运行转换,请尝试:

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

关于mongodb - 如何使用Mongodb设置数组和对象的差异,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54178838/

10-09 20:20