Mongodb聚合和展开行为 - 重复

时间:2017-04-10 10:37:07

标签: mongodb aggregation-framework

我目前正在使用以下查询来展开并“加入”多个集合:

    User.aggregate([{
                "$match": {
                    "verified": true,
                    "active_account": true
                }
            },
            {
                "$lookup": {
                    "from": "screens",
                    "localField": "_id",
                    "foreignField": "user_obj",
                    "as": "screenings"
                }
            },
            {
                "$unwind": "$screens"
            },
            {
                "$lookup": {
                    "from": "drinks",
                    "localField": "_id",
                    "foreignField": "user_id",
                    "as": "drinks"
                }
            },
            {
                "$unwind": "$drinks"
            },
            {
                "$group": {
                    "_id": "$_id",
                    "smsmobile": {
                        "$first": "$smsmobile"
                    },
                    "screens": {
                        "$push": "$screens"
                    },
                    "drinks": {
                        "$push": "$drinks"
                    }
                }
            }
        ]...

我目前遇到的问题是,对于饮料和屏幕,它们每个都有重复的记录 - 但是在实际数据库中它们是单个项目。例如,数据库中的屏幕只有两个记录,但在上面的过程中输出了四个。

似乎聚合展开过程正在生成这些重复项。我对此表示欢迎。

屏幕的示例输出如下。注意_id,它自己的集合没有重复的罪。

[ { _id: 58e901837a085502ec6b4b6b,
    updatedAt: 2017-04-08T15:28:03.153Z,
    createdAt: 2017-04-08T15:28:03.153Z,
    user_obj: 58e901267a085502ec6b4b69,
    screen: 1,
    difficult_sit: 1,
    group: 2,
    __v: 0 },
  { _id: 58e901837a085502ec6b4b6b,
    updatedAt: 2017-04-08T15:28:03.153Z,
    createdAt: 2017-04-08T15:28:03.153Z,
    user_obj: 58e901267a085502ec6b4b69,
    screen: 1,
    difficult_sit: 1,
    group: 2,
    __v: 0 },
  { _id: 58eb4001ee18b403f05a9043,
    updatedAt: 2017-04-10T08:19:13.857Z,
    createdAt: 2017-04-10T08:19:13.857Z,
    user_obj: 58e901267a085502ec6b4b69,
    screen: 1,
    difficult_sit: null,
    group: 2,
    __v: 0 },
  { _id: 58eb4001ee18b403f05a9043,
    updatedAt: 2017-04-10T08:19:13.857Z,
    createdAt: 2017-04-10T08:19:13.857Z,
    user_obj: 58e901267a085502ec6b4b69,
    screen: 1,
    difficult_sit: null,
    group: 2,
    __v: 0 } ]

0 个答案:

没有答案