Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get first document (not field) in MongoDB aggregate query?

In Aggregation Framework Examples,there is a first & 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" } } }

Can I get the full zipcodes document with $first?

Edited:

To clarify,I use coffeescript in my express app do the following thing,seems stupid:

@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}}

The fields (id,name,... tags) are all the document schema's field. I just want to know,is there any way to do this in single $first.

like image 708
wuhaixing Avatar asked May 07 '13 01:05

wuhaixing


People also ask

How do I get the first element of a collection in MongoDB?

If the operand resolves to a non-empty array, $first returns the first element in the array: If the operand resolves to an empty array [] , $first does not return a value. If the operand is null or missing, $first returns null.

Where is first document in MongoDB?

MongoDB provides two methods for finding documents from a collection: findOne() - returns a the first document that matched with the specified criteria. find() - returns a cursor to the selected documents that matched with the specified criteria.

Which is faster in find and aggregate in MongoDB?

find. The aggregation query takes ~80ms while the find query takes 0 or 1ms.


Video Answer


1 Answers

This is now possible in 2.6, because you can access the document being processed with $$ROOT. Something like this should work:

@aggregate([
    {
        $group: {
            _id: "$category" ,
            cnt: { $sum : 1 },
            first: { $first : "$$ROOT" }
        }
    },{
        $sort :{ "createdAt" : -1 }
    }
])
like image 149
Seth Avatar answered Oct 15 '22 06:10

Seth