Maciej Wawrzyńczuk
Maciej Wawrzyńczuk

Reputation: 876

Mongo aggregation - last record with additional data

Lets consider the example:

https://docs.mongodb.com/manual/reference/operator/aggregation/last/ I'l like to include additional fields like price or quantity of last sale. I mean how to include field which is not part of key nor aggregate expression. Is it possible?

Upvotes: 0

Views: 156

Answers (1)

mickl
mickl

Reputation: 49945

Basically it is possible to get entire document as an output of $group stage. There's a special variable $$ROOT which is helpful in such situations. So for instance if you want to get last processed document you can use following code:

db.sales.aggregate([
    { "$sort": { "date": 1 } },
    { 
        $group: {
            _id: "$item",
            lastDocument: { $last: "$$ROOT" }
        } 
    }
])

Upvotes: 1

Related Questions