Reputation: 2080
I have a MongoDB collection. In it, each document has an item ID, a time field, and a large number of other fields. The item IDs are repeated. I want to extract all the data from the last document in this collection for each distinct item ID. One approach that works is the following:
db.items.aggregate({
$sort: {time: -1}}, {
$group: {
_id: {item: '$item.id'},
time: {$first: '$time'},
anotherField: {$first: '$anotherField'},
yetAnotherField: {$first: '$yetAnotherField'},
...
}
})
...however, I would need to add an expression for each field in the document that I want to pull, which is quite clunky. Is there a query that accomplishes this as computationally efficiently (or better) as the above but more gracefully?
Upvotes: 0
Views: 162