我有兩個集合users和posts.
用戶有這樣的檔案:
{
_id: ObjectId('611142303c409b5dc826e563'),
name: 'foo'
}
帖子有這樣的檔案:
{
_id: ObjectId('611142303c409b5dc826e111'),
comments:[
{
owner: ObjectId('611142303c409b5dc826e563'),
description: "my description"
},
{
owner: ObjectId('611142303c409b5dc826e333'),
description: "my description2"
}
]
}
當我收到請求服務器端時,我需要回傳所有者的整個檔案,而不僅僅是它的 id。
例如對于我必須回傳的獲取請求:
{
_id: ObjectId('611142303c409b5dc826e111'),
comments:[
{
owner:{
_id: ObjectId('611142303c409b5dc826e563'),
name: 'foo'
},
description: "my description"
},
{
owner: {
_id: ObjectId('611142303c409b5dc826e555'),
name: 'foo2'
},
description: "my description2"
}
]
}
為此,我做了以下管道:
[
$lookup:{
from: 'owners',
localField: 'comments.owner',
foreignField: '_id',
as: 'owners_comments'
}
]
通過這種方式,我得到了一組在一個特定檔案中有評論的所有者。
我的問題是如何為每條評論獲取正確的所有者個人資料?我知道我可以更輕松地完成服務器端,但我更喜歡在 DB 端進行。
我想映射每個評論和內部過濾器owners_comments,但在 mongo 聚合中我幾乎沒有問題。
你有什么建議嗎?
uj5u.com熱心網友回復:
你必須到$unwindcomments陣列,然后執行$lookup然后你想$group恢復原來的結構,像這樣:
db.posts.aggregate([
{
$unwind: "$comments"
},
{
$lookup: {
from: "owners",
localField: "comments.owner",
foreignField: "_id",
as: "owners"
}
},
{
$group: {
_id: "$_id",
comments: {
$push: {
owner: "$comments.owner",
description: "$comments.description",
owner_profile: {
"$arrayElemAt": [
"$owners",
0
]
},
}
}
}
}
])
蒙戈游樂場
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/345384.html
