如何对 mongodb / mongoose 中的嵌套字段进行排序

How to sort nested field in mongodb / mongoose

我正在尝试按日期对评论进行排序,但我做错了。

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

这是我试过的方法(结果必须是,按最后日期对评论进行排序

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

使用 $sort 您可以对数据进行排序,但在使用之前您必须拆分数组。试试这个 mongo 查询:

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