如何检索 MongoDB 上每个其他不同字段的字段最大的文档?

How to retrieve documents where a field is maximum for every other distinct field on MongoDB?

我在 MongoDB 上有以下集合(为清楚起见,我省略了字段 _id):

[
  {
    "stock": "Stock1",
    "value": 12,
    "month": 1,
    "year": 2019
  },
  {
    "stock": "Stock1",
    "value": 13,
    "month": 2,
    "year": 2019
  },
  {
    "stock": "Stock1",
    "value": 14,
    "month": 1,
    "year": 2020
  },
  {
    "stock": "Stock1",
    "value": 15,
    "month": 2,
    "year": 2020
  },
  {
    "stock": "Stock2",
    "value": 6,
    "month": 1,
    "year": 2019
  },
  {
    "stock": "Stock2",
    "value": 5,
    "month": 2,
    "year": 2019
  }
]

并且我希望检索每个 stock 的文档,其中包含最新(最多)year 可用的文档,这样我最终得到以下内容:

[
  {
    "stock": "Stock1",
    "value": 14,
    "month": 1,
    "year": 2020
  },
  {
    "stock": "Stock1",
    "value": 15,
    "month": 2,
    "year": 2020
  },
  {
    "stock": "Stock2",
    "value": 6,
    "month": 1,
    "year": 2019
  },
  {
    "stock": "Stock2",
    "value": 5,
    "month": 2,
    "year": 2019
  }
]

我很想以编程方式遍历每个 stock,并在第一步中使用 find({"stock": "Stockx"}).sort({"year": -1}).limit(1) 查询最后一个 year,在第二步中查询 find({"stock": "Stockx", "year": maxyearforStockx"})。使用 findaggregate 命令是否有更优雅的方法?

如有任何帮助,我们将不胜感激!

  1. $sort - 按 year 降序排序。
  2. $group - 按 stockyear.
  3. 分组
  4. $group - 按 stock 分组并取 stockYearItems 的第一项(从 2)。
  5. $unwind - 将 items.stockYearItems 数组解构为多个文档。
  6. $replaceRoot - 用新文档替换输入文档以显示 stock 个文档。
db.collection.aggregate({
  "$sort": {
    "year": -1
  }
},
{
  $group: {
    _id: {
      "stock": "$stock",
      "year": "$year"
    },
    stockYearItems: {
      $push: "$$ROOT"
    }
  }
},
{
  $group: {
    _id: "$_id.stock",
    items: {
      $first: "$$ROOT"
    }
  }
},
{
  $unwind: "$items.stockYearItems"
},
{
  "$replaceRoot": {
    "newRoot": "$items.stockYearItems"
  }
})

Sample Mongo Playground