Search code examples
mongodbmongoose-schema

How to sort nested field in mongodb / mongoose


Im trying to sort the comments by its date but i cant do it correct.

   {
        "_id": "5defc10b8e753623b4ad0adf",
        "title": "bla bla",
        "owner:"idToPopulate",
        "comments": [
            {
                "_id": "5dfc2185e62103121cfc0f18",
                "reply": "1",
                "replyDate": "2019-12-10T16:00:11.228Z"
            },
            {
                "_id": "5dfc218be62103121cfc0f19",
                "reply": "2",
                "replyDate": "2019-13-10T16:00:11.228Z"
            }
        ]
    }

This is the way i tried ( the result has to be, sort the comments by it last date)

.sort({"comments.replyDate":1})

Solution

  • Using $sort you can sort your data, but before using that you have to split your array. Try with this mongo query:

     db.collection.aggregate([
      {
        $unwind: {
          path: "$comments"
        }
      },
      {
        $sort: {
          "comments.replyDate": -1
        }
      },
      {
        $group: {
          _id: "$_id",
          comments: {
            $push: {
              _id: "$comments._id",
              item: "$comments.reply",
              date: "$comments.replyDate"
            }
          }
        }
      }
    ])