如何使用mongo-query

时间:2019-01-10 12:08:20

标签: mongodb mongodb-query aggregation-framework aggregate

UserDetails

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

UserProducts

{
    "_id" : "5c23536f807caa1bec00e79c",
    "UPID" : "100",
    "UID" : "1"
},
{
    "_id" : "5c23536f807caa1bec00e79c",
    "UPID" : "200",
    "UID" : "2"
}

{
    "_id" : "5bb20d7556db6915846da55f",
    "members" : {
        "regularStudent" : [
            "200" // UPID
        ],
    }
}

第1步

我必须从 UserDetails 中获取UID,并与 UserProducts 进行核对,然后从 UserProducts

中获取UPID

第2步

我们必须检查映射到 Groups 集合的UPID吗? members.regularStudent我们被映射为UPID

第3步

假设未映射 UPID ,这意味着我要从 UserProducts

中打印 UPID

我已经尝试过但无法完成,请帮助我。

  

预期输出:

["100"]

注意:预期输出为["100"],因为 UserProducts 具有UPID 100 & 200,但 Groups 集合仅映射了200

>

我的代码

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" ]

db.Groups.aggregate([
    {
        $unwind: "$members.regularStudent"
    },
    {
        $group: {
            _id: null,
            UPIDs: { $addToSet: "$members.regularStudent" }
        }
    }
]) // returns ["200"]

现在我想检查两个数组的 $ setDifference ,所以我添加了下面的代码,但返回了类似$userProductUPIDs is not defined的错误

  db.Groups.aggregate([
    {
        $unwind: "$members.regularStudent"
    },
    {
        $group: {
            _id: null,
            UPIDs: { $addToSet: "$members.regularStudent" }
        }
    },
    {
        $project: {
            members: {
                $setDifference: [ $userProductUPIDs , "$members" ]
            },
            _id : 0
        }
    }
    ]) 

1 个答案:

答案 0 :(得分:1)

由于这是我以前的回答之一的后续措施,因此我将尝试修复您的代码。底线是您需要两个查询,因为您无法升级数据库,因此代码应如下所示:

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" }
    }
});

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
        }
    }
]) // should return 100
相关问题