MongoDB - 使用聚合对内部数组进行排序

MongoDB - Sort inner array with Aggregate

这是我的数据:

{
  { "_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 的对象,其内部数组 commentstime 的相反顺序排序。我目前有:

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 数组有一些元素但 returns [] 为整个对象时,如果数组为空,这工作正常。我可以得到一些关于如何 return 即使数组为空的内容的帮助吗?

$unwind 阶段使用 preserveNullAndEmptyArrays

preserveNullAndEmptyArrays

If true, if the path is null, missing, or an empty array, $unwind outputs the document.

{
  $unwind: {
    path: "$comments",
    preserveNullAndEmptyArrays: true
  }
}

Sample Mongo Playground