简体   繁体   中英

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

I am using MongoDB 3.6 for my project. I have 2 collections "users" and "follow". I want to extract out details of user's followers and following (like an Instagram app).

users collection

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

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

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

}

follow 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"

}

Now i want following list of id 2 So id 2 is following id 1 and id 3 So, Output should be like this

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

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

}

For that, I am using $lookup aggregation. But this is not giving the desired output which I want. Here is my code -

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

For more understanding please refer the image

To get following list of id 2 you can use following query:

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 
        } 
    }
])

So the point here is that you have a relation between id and follow id and after $lookup phase follow id becomes the new id since it's parent-child relation.

EDIT: 3.4 solution below

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" 
        } 
    }
])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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