簡體   English   中英

使用mongose聚合從mongo中的集合填充

[英]Using mongose aggregation to populate from collection in mongo

樣本文件

{
     _id:"123",
     "completed" : [ 
         {
             "Id" : ObjectId("57caae00b2c40dd21ba089be")
             "subName" : "oiyt",
             "Name" : "Endo",

         }, 
         {
             "Id" : ObjectId("57caae00b2c40dd21ba089be"),
             "subName" : "oiyt",
             "Name" : "Endo",
         }
    ] 
}

如何在_id匹配的地方訪問completenamesubname name

您可以使用$filter$unwind (或兩者)。

此示例顯示如何使用$filter僅使用數組中的一個匹配元素來獲取文檔,然后$unwind以更輕松地訪問匹配的元素。

但是還有更多的選擇來獲得理想的結果。

db.collection.aggregate([
    {
        $project: {
            filtered_completed: {
                $filter:{
                    input: "$completed",
                    as: "complete",
                    cond: {
                        $eq: [input_id, "$$complete.Id"]
                    }
                }
            }
        }
    },
    {
        $unwind: "$filtered_completed"
        // because we already filtered the 'completed' array, we will get only one document.
        // but you can use it as the first aggreagation pipeline stage and match the _id
    },
    {
        $project: {
            "filtered_completed.Name": 1,
            "filtered_completed.subName": 1
        }
    }
])

閱讀更多關於$ filter$ unwind的信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM