使用mongose聚合从mongo

时间:2016-09-07 13:15:12

标签: node.js mongodb mongoose aggregation-framework mongodb-aggregation

示例文档

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

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

如何从name匹配的subname访问complete_id

1 个答案:

答案 0 :(得分:0)

您可以使用$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