首页 > 解决方案 > mongodb:选择嵌入式数组中的最新条目

问题描述

给定具有价格历史记录的项目的以下数据:

{
  item: "Item A",
  priceHistory: [
    {
      date: ISODate("2021-04-01T08:32:45.561Z"),
      value: 100
    },
    {
      date: ISODate("2021-04-02T08:32:45.561Z"),
      value: 200
    },
    {
      date: ISODate("2021-04-04T08:32:45.561Z"),
      value: 400
    },
    {
      date: ISODate("2021-04-03T08:32:45.561Z"),
      value: 300
    },
  ]
},{
  item: "Item B",
  priceHistory: [
    {
      date: ISODate("2021-04-01T08:32:45.561Z"),
      value: 1
    }
  ]
}, ...

请注意,该priceHistory字段排序。

我想找到每件商品的最新价格:

{
  item: "Item A",
  price: 400
},{
  item: "Item B",
  price: 1
}, ...

现在我正在努力选择最新的条目priceHistory

我已经尝试过的

但我很难将它们整合在一起。


顺便说一句,也许问题出在数据模型本身上?将价格历史记录到自己的收藏中,并且只将最新价格存储在商品本身上是否有意义?

标签: mongodbmongodb-query

解决方案


演示 - https://mongoplayground.net/p/-LQPcTn_-Aj

db.collection.aggregate([
  { $unwind: "$priceHistory" }, // unwind to individual documents
  { $sort: { "priceHistory.date": -1 } }, // sort by priceHistory.date to get max date at the top (descending)
  {
    $group: {
      _id: "$_id", // group by id back and get priceHistory sorted in descending order by date
      price: { $first: "$priceHistory.value" }, // get the first price which is for max date record
      item: { $first: "$item"}
    }
  }
])

推荐阅读