所以我一直試圖獲得 $lookup 結果的特定欄位,我從這個開始:
$lookup: {
from : "answers",
localField: "_id",
foreignField: "questionID",
as: "usersAnswered"
}
它回傳如下內容:
{
_id: "616974f1b4f67d0220fe2cf1",
questionText: "text abc ?",
userID: "614c7a75403a5636b4029f28",
usersAnswered: [{
_id: "6169635cb4f67d0220fe2aa4",
answerText: "xyz",
questionID: "616974f1b4f67d0220fe2cf1",
userID: "614c7a75403a5636b4029f21"
},{
_id: "6169635cb4f67d0220fe2ab8",
answerText: "lmo",
questionID: "616974f1b4f67d0220fe2cf1",
userID: "614c7a75403a5636b4029cc2"
}]
}
在這個例子中,我試圖實作的只是userID從usersAnswered陣列中獲取,而不是如果我真的不需要整個物件。它應該看起來像:
usersAnswered: [{
userID: "614c7a75403a5636b4029f21"
},{
userID: "614c7a75403a5636b4029cc2"
}]
}
我實際上已經嘗試過完成它,但我無法完成它所以必須得到一些幫助,我可以做類似的事情嗎
$lookup: {
from : "answers",
localField: "_id",
foreignField: "questionID.userID",
as: "usersAnswered"
}
或者也許關鍵是在 $unwind 之后 $group 因為我對聚合框架真的很陌生,所以我無法看透它,請放輕松,因為我真的很陌生。
uj5u.com熱心網友回復:
如果你已經運行了 MongoDB 5.0,那么試試這個:
{
$lookup:
{
from: "answers",
localField: "_id",
foreignField: "questionID",
pipeline: [ {$project: {userID: 1} } ],
as: "usersAnswered"
}
}
否則在之后添加此階段$lookup:
{ $set:
{
usersAnswered: {
$map: { input: "$usersAnswered", in: { userID: "$$this.userID" } }
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/406696.html
標籤:
