MongoDB 查询每个项目的最新更新记录
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 的最新更新? IE:
returns
{
itemId: a,
itemContent: a2,
lastUpdateTime: 2022-01-02,
},
{
itemId: b,
itemContent: b3,
lastUpdateTime: 2022-01-01,
}
db.collection.aggregate([
{
"$sort": {
lastUpdateTime: -1
}
},
{
"$group": {
"_id": "$itemId",
"itemcontent": {
"$first": "$itemContent"
}
}
}
])
排序并获取每个 ItemId 的第一项。
我有一个历史更新跟踪集合。这个集合看起来像:
{
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 的最新更新? IE: returns
{
itemId: a,
itemContent: a2,
lastUpdateTime: 2022-01-02,
},
{
itemId: b,
itemContent: b3,
lastUpdateTime: 2022-01-01,
}
db.collection.aggregate([
{
"$sort": {
lastUpdateTime: -1
}
},
{
"$group": {
"_id": "$itemId",
"itemcontent": {
"$first": "$itemContent"
}
}
}
])
排序并获取每个 ItemId 的第一项。