簡體   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