0

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.