這是我的資料:
{
{ "_id" : ObjectId("623a92139e19f99295167786"),
"headline" : "headline1",
"comments" : [
{"userID" : ObjectId("623a7b199e19f99295167776"),
"time" : ISODate("2022-03-24T10:20:23Z")},
{"userID" : ObjectId("623a7b199e19f99295167776"),
"time" : ISODate("2022-03-25T10:20:23Z")},
]
},
{ "_id" : ObjectId("623be3ce9e19f99295167787"),
"headline" : "headline2",
"comments" : [ ]
}
}
內部陣列comments可能包含也可能不包含某些元素。我想找到一個與_id字串變數匹配的物件my_id,其內部陣列comments以time. 我目前有:
col.aggregate([
{$match: {_id: monk.id(my_id)}},
{$unwind: "$comments"},
{$sort: {"comments.time":-1}},
{$group: {_id: "$_id", headline: {$first:"$headline"},
comments:{$push:"$comments"}}}
]).then((result) => {
console.log(JSON.stringify(result));
});
comments當陣列有一些元素但[]如果陣列為空則回傳整個物件時,這很好用。即使陣列為空,我也可以就如何回傳內容獲得一些幫助嗎?
uj5u.com熱心網友回復:
用于舞臺preserveNullAndEmptyArrays。$unwind
保留NullAndEmptyArrays
如果為真,如果路徑為空、缺失或為空陣列,則 $unwind 輸出檔案。
{
$unwind: {
path: "$comments",
preserveNullAndEmptyArrays: true
}
}
示例 Mongo Playground
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/453931.html
