在子文档中的同一集合中的mongodb聚合和$ lookup

时间:2018-04-30 18:06:17

标签: mongodb mongodb-query aggregation-framework nosql-aggregation

我有以下结构:

{ 
    "_id" : ObjectId("5ae451b46302b274b5ebeefb"), 
    "name" : "Laurent", 
    "email" : "laurent@laurent.fr", 
    "password" : "sha1$e6f05101$1$21444307dfa8684f479f39530b03a2f5cad98ac9", 
    "follows" : [
        {
            "_id" : ObjectId("5ae7495e1cc09532e98b70fc"), 
            "userId" : "5ae4f2dc3d921228f5af56bc"
        }, 
        {
            "_id" : ObjectId("5ae749a31cc09532e98b70fd"), 
            "userId" : "5ae5f100e11ba63941fc0cb6"
        }
    ]
}
{ 
    "_id" : ObjectId("5ae4f2dc3d921228f5af56bc"), 
    "name" : "Test", 
    "email" : "test@test.com", 
    "password" : "sha1$5155f44b$1$05ff3feef313caf6c3d9e13e44629430368ea812", 
    "follows" : [
        {
            "_id" : ObjectId("5ae591cf3f56d33772540572"), 
            "userId" : "5ae451b46302b274b5ebeefb"
        }
    ]
}
{ 
    "_id" : ObjectId("5ae5f100e11ba63941fc0cb6"), 
    "name" : "user", 
    "email" : "user@user.com", 
    "password" : "sha1$30af5299$1$7f2fe08a44221b2b03ff0365b51b0b1aa5184da1", 
    "follows" : [
        {
            "_id" : ObjectId("5ae6011a5ccd9b4bcab5f45e"), 
            "userId" : "5ae4f2dc3d921228f5af56bc"
        }, 
        {
            "_id" : ObjectId("5ae60af234591a4fdfedaf02"), 
            "userId" : "5ae451b46302b274b5ebeefb"
        }
    ], 
    "__v" : NumberInt(0)
}

我想检索带有聚合函数的follow.userId中所用用户的信息。

我的要求是:

db.users.aggregate(
            {$match: {_id: ObjectId('5ae451b46302b274b5ebeefb')}},
            {$unwind: "$follows"},
            {
                $lookup: {
                    from: "users",
                    localField: "follows.userId",
                    foreignField: "_id",
                    as: "subscriptions"
                }
            }
            )

我在输出中得到一个空的订阅字段:

{ 
    "_id" : ObjectId("5ae451b46302b274b5ebeefb"), 
    "name" : "Laurent", 
    "email" : "laurent.chriqui@coding-academy.fr", 
    "password" : "sha1$e6f05101$1$21444307dfa8684f479f39530b03a2f5cad98ac9", 
    "follows" : {
        "_id" : ObjectId("5ae7495e1cc09532e98b70fc"), 
        "userId" : "5ae4f2dc3d921228f5af56bc"
    }, 
    "subscriptions" : [

    ]
}
{ 
    "_id" : ObjectId("5ae451b46302b274b5ebeefb"), 
    "name" : "Laurent", 
    "email" : "laurent@laurent.fr", 
    "password" : "sha1$e6f05101$1$21444307dfa8684f479f39530b03a2f5cad98ac9", 
    "__v" : NumberInt(0), 
    "follows" : {
        "_id" : ObjectId("5ae749a31cc09532e98b70fd"), 
        "userId" : "5ae5f100e11ba63941fc0cb6"
    }, 
    "subscriptions" : [

    ]
}

我不明白为什么订阅字段是一个空数组而且没有填充用户信息。

有没有人知道问题是什么以及如何让它发挥作用?

0 个答案:

没有答案