繁体   English   中英

在mongoDB中加入两个集合,并在节点js中提取数据

[英]Join two collection in mongoDB and extract out data in node js

我正在为项目使用MongoDB 3.6。 我有2个收藏集“用户”和“关注”。 我想提取用户关注者和关注者的详细信息(例如Instagram应用)。

用户集合

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

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

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

}

关注收藏

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

欲了解更多信息,请参考图片

要获取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因为它是父子关系。

编辑:下面的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" 
        } 
    }
])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM