示例文档
{
_id:"123",
"completed" : [
{
"Id" : ObjectId("57caae00b2c40dd21ba089be")
"subName" : "oiyt",
"Name" : "Endo",
},
{
"Id" : ObjectId("57caae00b2c40dd21ba089be"),
"subName" : "oiyt",
"Name" : "Endo",
}
]
}
如何从name
匹配的subname
访问complete
和_id
?
答案 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
}
}
])