英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论