首页 > 解决方案 > 子文档中同一集合中的 mongodb 聚合和 $lookup

问题描述

我有以下结构:

{ 
    "_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)
}

我想使用聚合函数检索以下用户的信息。

我的要求是这样的:

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" : [

    ]
}

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

有谁知道问题是什么以及我如何让它工作?

标签: mongodbmongodb-queryaggregation-frameworknosql-aggregation

解决方案


推荐阅读