如何通過參考 id 和其他屬性查找物件。
收藏A
{
_id: ObjectId("6013859ba0c3120034d08bfa"),
name: "A1",
refs:[
{id: ObjectId("6013859ba0c3120034d08bfb"), text: "ABC"},
{id: ObjectId("6013859ba0c3120034d08bfc"), text: "DEF"}
]
}
收藏B
{
_id: ObjectId("6013859ba0c3120034d08bfb"),
name: "B1"
}
{
_id: ObjectId("6013859ba0c3120034d08bfc"),
name: "B2"
}
預期結果
{
_id: ObjectId("6013859ba0c3120034d08bfa"),
name: 'A1',
refs:[
{id: ObjectId("6013859ba0c3120034d08bfb"), name: "B1", text: "ABC"},
{id: ObjectId("6013859ba0c3120034d08bfc"), name: "B2", text: "DEF"}
]
}
uj5u.com熱心網友回復:
$unwind- 解構refs陣列欄位。$lookup- 將collectionA(refs.id) 與collectionB(_id) 連接起來。$project- 裝飾檔案,refsB通過$first.$group- 分組_id并為檔案生成(必填)欄位。
db.collectionA.aggregate([
{
$unwind: "$refs"
},
{
"$lookup": {
"from": "collectionB",
"localField": "refs.id",
"foreignField": "_id",
"as": "refsB"
}
},
{
$project: {
_id: 1,
name: 1,
refs: {
id: "$refs.id",
text: "$refs.text",
name: {
$first: "$refsB.name"
}
}
}
},
{
$group: {
_id: "$_id",
name: {
$first: "$name"
},
refs: {
$push: "$refs"
}
}
}
])
示例 Mongo Playground
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/362980.html
