Home > front end >  MongoDB query latest updated record for each item
MongoDB query latest updated record for each item

Time:05-26

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,
}

CodePudding user response:

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

Sort and get first item for each ItemId.

  • Related