MongoDB 按日期时间和姓名排序

MongoDB sort by dateTime and name

我有一个类似的 collection:

{"name": 'C', "dateTime": "Oct 19 14:52"}
{"name": 'B', "dateTime": "Oct 19 14:52"}
{"name": 'A', "dateTime": "Oct 19 16:52"}
{"name": 'C', "dateTime": "Oct 19 15:52"}
{"name": 'B', "dateTime": "Oct 19 16:52"}

我排序后使用

$sort: {
    "dateTime": 1,
    "name": 1
}

我得到了这个结果:

{"name": 'B', "dateTime": "Oct 19 14:52"}
{"name": 'C', "dateTime": "Oct 19 14:52"}
{"name": 'C', "dateTime": "Oct 19 15:52"}
{"name": 'A', "dateTime": "Oct 19 16:52"}
{"name": 'B', "dateTime": "Oct 19 16:52"}

但是,我想要的结果是按时间排序后,我想这样分组:

{"name": 'B', "dateTime": "Oct 19 14:52"}
{"name": 'B', "dateTime": "Oct 19 16:52"}
{"name": 'C', "dateTime": "Oct 19 14:52"}
{"name": 'C', "dateTime": "Oct 19 15:52"}
{"name": 'A', "dateTime": "Oct 19 16:52"}

请问怎样才能达到上面的效果,谢谢

您首先需要 $group 您的文件名在前。使用数组来保存文档,$sort 根据您的排序。 $unwind 他们取回原始文档。

db.collection.aggregate([
  {
    $group: {
      _id: "$name",
      docs: {
        $push: "$$ROOT"
      }
    }
  },
  {
    $sort: {
      "docs.dateTime": 1,
      "docs.name": 1
    }
  },
  {
    "$unwind": "$docs"
  },
  {
    "$replaceRoot": {
      "newRoot": "$docs"
    }
  }
])

这里是Mongo playground供您参考。