Home > Net >  MongoDB - Sort inner array with Aggregate
MongoDB - Sort inner array with Aggregate

Time:04-01

Here is my data:

{
  { "_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" : [ ]
  }
}

The inner array comments may or may not contain some elements. I want to find an object with the _id that matches the string variable my_id, with its inner array comments sorted in the reverse order of time. I currently have:

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));
});

This works fine when the comments array has some elements but returns [] for the entire object if the array is empty. May I get some help on how to return the content even when the array is empty?

CodePudding user response:

Use preserveNullAndEmptyArrays for $unwind stage.

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

  • Related