在 MongoDB 聚合查询中为每个文档提取大量字段

Extracting a large number of fields for each document in a MongoDB aggregation query

我有一个MongoDBcollection。在其中,每个文档都有一个项目 ID、一个时间字段和大量其他字段。项目 ID 重复。我想从这个 collection 的最后一个文档中为每个不同的项目 ID 提取所有数据。一种有效的方法如下:

db.items.aggregate({
    $sort: {time: -1}}, {
    $group: {
        _id: {item: '$item.id'},
        time: {$first: '$time'},
        anotherField: {$first: '$anotherField'},
        yetAnotherField: {$first: '$yetAnotherField'},
        ...
    }
})

...但是,我需要为要提取的文档中的每个字段添加一个表达式,这非常笨拙。有没有像上面那样在计算上高效(或更好)但更优雅地完成此操作的查询?

您可以使用 $$ROOT 在您的 $group 中引用整个文档。

因此,要获取每个组的最新(即最后)文档,您可以执行以下操作:

db.items.aggregate({
    $sort: {time: -1}}, {
    $group: {
        _id: {item: '$item.id'},
        lastDoc: {$first: '$$ROOT'}
    }
})