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