Jorge Aranda
Jorge Aranda

Reputation: 2080

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

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

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312035

You can use $$ROOT to reference the entire doc in your $group.

So to get the most recent (i.e. last) doc for each group you can do:

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

Upvotes: 2

Related Questions