Group mongodb 集合并将结果输出为单个对象

Group mongodb collection and output the result as a single object

有没有办法对看起来像

的集合进行分组
[
  {_id: "5bd258a7877e74059b6b65b2", year: 2017, title: "One"},
  {_id: "5bd258a7877e74059b6b65b3", year: 2017, title: "Two"},
  {_id: "5bd258a7877e74059b6b65b4", year: 2018, title: "Three"},
  {_id: "5bd258a7877e74059b6b65b5", year: 2018, title: "Four"}
]

并将结果输出为

{
  2017: [
    0: {_id: "5bd258a7877e74059b6b65b2", title: "One", …}
    1: {_id: "5bd258a7877e74059b6b65b3", title: "Two", …}
  ],
  2018: [
    0: {_id: "5bd258a7877e74059b6b65b4", title: "Three", …}
    1: {_id: "5bd258a7877e74059b6b65b5", title: "Four", …}
  ]
}

使用 mongodb 聚合?类似于 lodash groupBy 的工作方式

您可以使用以下 mongoDB 聚合来做到这一点:

db.collection.aggregate([{
    $group: {
      _id: "$year",
      docs: {
        $addToSet: "$$CURRENT"
      }
    }
  },
  {
    "$group": {
      "_id": null,
      "data": {
        "$push": {
          "k": {
            $toString: "$_id"
          },
          "v": "$docs"
        }
      }
    }
  },
  {
    "$replaceRoot": {
      "newRoot": {
        "$arrayToObject": "$data"
      }
    }
  }
])

你可以看到 result here

我们的想法是以我们可以利用的方式对数据进行分组 $arrayToObject. First group gives you the grouped by year where the second is just prep for $arrayToObject which requires key, value object. Last thing is the $replaceRoot

这需要 MongoDB 3.6 及更高版本,因为该版本中引入了 $arrayToObject。在此之前,您必须使用 $push