在mongoDB中加入两个collection并在节点js中提取数据

Join two collection in mongoDB and extract out data in node js

我正在为我的项目使用 MongoDB 3.6。 我有 2 collections "users" 和 "follow"。我想提取用户关注者和关注者的详细信息(如 Instagram 应用程序)。

用户collection

{
    "id" : "1",
    "name" : "abc",
    "age" : "26"

},
{
    "id" : "2",
    "name" : "xyz",
    "age" : "22"

},
{
    "id" : "3",
    "name" : "qwe",
    "age" : "23"

}

关注collection

{
    "id" : "2",
    "follow id" : "1"

},
{
    "id" : "3",
    "follow id" : "1"

},
{
    "id" : "1",
    "follow id" : "2"

},
{
    "id" : "2",
    "follow id" : "3"

},
{
    "id" : "1",
    "follow id" : "3"

}

现在我想关注 id 2 的列表所以 id 2 是在 id 1 和 id 3 之后 所以,输出应该是这样的

{
    "id" : "1",
    "name" : "abc",
    "age" : "26"

},
{
    "id" : "3",
    "name" : "qwe",
    "age" : "23"

}

为此,我正在使用 $lookup 聚合。但这并没有给出我想要的输出。 这是我的代码 -

Follow.aggregate([
    { 
        $lookup:{
            from:"users",
            localField:"id",
            foreignField:"id",
            as:"fromItems"
        }
    },
    {
        $replaceRoot:{newRoot: {$mergeObjects: [ { $arrayElemAt: ["$fromItems", 0 ] }, "$$ROOT" ] } }
    },
    { $project : 
        { 
            fromItems : 0 
        } 
    }
], callback)

更多理解请参考image

要获取以下 ID 2 列表,您可以使用以下查询:

Follow.aggregate([
    {
        $match: { "id": "2" }
    },
    { 
        $lookup:{
            from:"users",
            localField:"follow id",
            foreignField:"id",
            as:"fromItems"
        }
    },
    {
        $replaceRoot:{newRoot: {$mergeObjects: [ { $arrayElemAt: ["$fromItems", 0 ] }, "$$ROOT" ] } }
    },
    { $project : 
        { 
            id : "$follow id",
            name: 1,
            age: 1 
        } 
    }
])

所以这里的重点是 idfollow id 之间存在关系,并且在 $lookup 阶段之后 follow id 成为新的 id 因为它是parent-child关系。

编辑: 3.4 下面的解决方案

Follow.aggregate([
    {
        $match: { "id": "2" }
    },
    { 
        $lookup:{
            from:"users",
            localField:"follow id",
            foreignField:"id",
            as:"fromItems"
        }
    },
    {
        $project: {
            id: "$follow id",
            from: { $arrayElemAt: ["$fromItems", 0 ] }
        }
    },
    { $project : 
        { 
            id : 1,
            name: "$from.name",
            age: "$from.age" 
        } 
    }
])