我在同一個集合“模式”下有以下資料,這是我的狀態示例:
{
"_id": "c19592b6-8110-4684-9c96-f133e08d973e",
"display": "WAITING",
"name": "waiting",
"color": "#ccf0d5",
"type": "status"
},
{
"_id": "69e39c0c-b722-433a-aa6e-471c24211a4d",
"display": "IN PROGRESS",
"name": "in_progress",
"color": "#4ddb7f",
"type": "status"
},
{
"_id": "59336051-776e-4f02-b988-46b3260f097c",
"display": "APPROVED",
"name": "approved",
"color": "#738ace",
"type": "status"
}
這是我的狀態的一個例子:
{
"_id": "e351ed21-0db3-44aa-ae0c-d7b0b92b4dce",
"index": 1,
"display": "In Progress",
"name": "in_progress",
"type": "state",
"members": ["c19592b6-8110-4684-9c96-f133e08d973e", "69e39c0c-b722-433a-aa6e-471c24211a4d"]
},
{
"_id": "2b57768b-919e-4cba-a861-a682eeac0cd2",
"index": 2,
"display": "In Review",
"name": "in_review",
"type": "state",
"members": ["59336051-776e-4f02-b988-46b3260f097c"]
}
這是我最后想要得到的:
{
"_id": "e351ed21-0db3-44aa-ae0c-d7b0b92b4dce",
"index": 1,
"display": "In Progress",
"name": "in_progress",
"type": "state",
"members": [{
"_id": "c19592b6-8110-4684-9c96-f133e08d973e",
"display": "WAITING",
"name": "waiting",
"color": "#ccf0d5",
"type": "status"
},{
"_id": "69e39c0c-b722-433a-aa6e-471c24211a4d",
"display": "IN PROGRESS",
"name": "in_progress",
"color": "#4ddb7f",
"type": "status"
}]
},
我看過其他類似的問題:
$MongoDB $lookup foreach 同一集合上陣列中的元素
$lookup 具有相同集合的兩個欄位
但每一個都是略有不同的情況,老實說,我不能老實說 $lookup。謝謝您的幫助。
uj5u.com熱心網友回復:
db.c2.aggregate([
{
$match: {
_id: "e351ed21-0db3-44aa-ae0c-d7b0b92b4dce"
}
},
{
$unwind: "$members"
},
{
$lookup: {
from: "c1",
localField: "members",
foreignField: "_id",
as: "members"
}
},
{
$group: {
_id: "$_id",
index: { $first: "$index" },
display: { $first: "$display" },
name: { $first: "$name" },
type: { $first: "$type" },
members: { $push: "$members" }
}
}
])
mongoplayground
db.schema.aggregate([
{
$match: { type: "state" }
},
{
$unwind: "$members"
},
{
$lookup: {
from: "schema",
localField: "members",
foreignField: "_id",
as: "members"
}
},
{
$group: {
_id: "$_id",
index: { $first: "$index" },
name: { $first: "$name" },
display: { $first: "$display" },
type: { $first: "$type" },
members: { $push: { $first: "$members" } }
}
}
])
mongoplayground
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/450649.html
