Can I get the first document (not a field) in an aggregated MongoDB query?

In Examples of aggregation structure , there is the first and last example:

db.zipcodes.aggregate( { $group: { _id: { state: "$state", city: "$city" }, pop: { $sum: "$pop" } } }, { $sort: { pop: 1 } }, { $group: { _id : "$_id.state", biggestCity: { $last: "$_id.city" }, biggestPop: { $last: "$pop" }, smallestCity: { $first: "$_id.city" }, smallestPop: { $first: "$pop" } } } 

Is it possible to get the full zipcodes document using $first ?

Edited by:

To clarify, I use coffeescript in my express application, doing the following seems silly:

 @aggregate( { $group : _id : "$category" cnt : { $sum : 1 } id: {$first: "$_id"} name: {$first: "$name"} description: {$first: "$description"} region: {$first: "$region"} startedAt: {$first: "$startedAt"} titleImage: {$first: "$titleImage"} tags: {$first: "$tags"} }, {$sort :{"createdAt" : -1}} 

Fields (id, name, ... tags) are all fields of the document scheme. I just want to know if there is a way to do this in a single $first .

+7
source share
1 answer

This is now possible in version 2.6, since you can access a document processed with $$ ROOT. Something like this should work:

 @aggregate( { $group : _id : "$category" cnt : { $sum : 1 } first: {$first : "$$ROOT"} {$sort :{"createdAt" : -1}} ) 
+10
source

All Articles