1

样本文件

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

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

我如何访问namesubnamecomplete哪里_id匹配?

4

1 回答 1

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

于 2016-09-08T09:03:43.400 回答