[英]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
匹配的地方訪問complete
的name
和subname
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.