查询每个项目的最新更新记录的MongoDB查询

huangapple go评论79阅读模式
英文:

MongoDB query latest updated record for each item

问题

我有一个历史更新跟踪集合。这个集合看起来像这样:

{
  itemId: a,
  itemContent: a1,
  lastUpdateTime: 2022-01-01,
},
{
  itemId: a,
  itemContent: a2,
  lastUpdateTime: 2022-01-02,
},
{
  itemId: b,
  itemContent: b1,
  lastUpdateTime: 2021-01-01,
},
{
  itemId: b,
  itemContent: b2,
  lastUpdateTime: 2021-09-01,
},
{
  itemId: b,
  itemContent: b3,
  lastUpdateTime: 2022-01-01,
}

是否可能获取每个itemId的最新更新?例如:

{
  itemId: a,
  itemContent: a2,
  lastUpdateTime: 2022-01-02,
},
{
  itemId: b,
  itemContent: b3,
  lastUpdateTime: 2022-01-01,
}
英文:

I am have a historic update tracking collection. This collection is look like:

{
  itemId: a,
  itemContent: a1,
  lastUpdateTime: 2022-01-01,
},
{
  itemId: a,
  itemContent: a2,
  lastUpdateTime: 2022-01-02,
},
{
  itemId: b,
  itemContent: b1,
  lastUpdateTime: 2021-01-01,
},
{
  itemId: b,
  itemContent: b2,
  lastUpdateTime: 2021-09-01,
},
{
  itemId: b,
  itemContent: b3,
  lastUpdateTime: 2022-01-01,
}

Is that possible that I can get latest update for each individual itemId? Ie:
returns

{
  itemId: a,
  itemContent: a2,
  lastUpdateTime: 2022-01-02,
},
{
  itemId: b,
  itemContent: b3,
  lastUpdateTime: 2022-01-01,
}

答案1

得分: 0

排序并获取每个ItemId的第一个项目。

英文:
db.collection.aggregate([
  {
    "$sort": {
      lastUpdateTime: -1
    }
  },
  {
    "$group": {
      "_id": "$itemId",
      "itemcontent": {
        "$first": "$itemContent"
      }
    }
  }
])

Sort and get first item for each ItemId.

huangapple
  • 本文由 发表于 2022年5月25日 12:14:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/72371900.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定