Saturday 21 February 2015

mongoDB : $first (aggregation)


$first returns the value that results from applying an expression to the first document in a group of documents that share the same group by key.

Syntax
{ $first: <expression> }


> db.fun.find()
{ "_id" : 0, "a" : 0, "b" : 0, "c" : 21 }
{ "_id" : 1, "a" : 0, "b" : 0, "c" : 54 }
{ "_id" : 2, "a" : 0, "b" : 1, "c" : 52 }
{ "_id" : 3, "a" : 0, "b" : 1, "c" : 17 }
{ "_id" : 4, "a" : 1, "b" : 0, "c" : 22 }
{ "_id" : 5, "a" : 1, "b" : 0, "c" : 5 }
{ "_id" : 6, "a" : 1, "b" : 1, "c" : 87 }
{ "_id" : 7, "a" : 1, "b" : 1, "c" : 97 }
>
>
> db.fun.aggregate([{$sort:{c:-1}},{$group:{_id:"$a", c:{$first:"$c"}}} ])
{ "_id" : 0, "c" : 54 }
{ "_id" : 1, "c" : 97 }


Explanation
1. “{$sort:{c:-1}}” sorts all documents by c in descending order.

> db.fun.aggregate([{$sort:{c:-1}}])
{ "_id" : 7, "a" : 1, "b" : 1, "c" : 97 }
{ "_id" : 6, "a" : 1, "b" : 1, "c" : 87 }
{ "_id" : 1, "a" : 0, "b" : 0, "c" : 54 }
{ "_id" : 2, "a" : 0, "b" : 1, "c" : 52 }
{ "_id" : 4, "a" : 1, "b" : 0, "c" : 22 }
{ "_id" : 0, "a" : 0, "b" : 0, "c" : 21 }
{ "_id" : 3, "a" : 0, "b" : 1, "c" : 17 }
{ "_id" : 5, "a" : 1, "b" : 0, "c" : 5 }


2. “{$group:{_id:"$a", c:{$first:"$c"}}}” group all documents by a and get all the first documents in that group.
> db.fun.aggregate([{$sort:{c:-1}},{$group:{_id:"$a", c:{$first:"$c"}}} ])
{ "_id" : 0, "c" : 54 }
{ "_id" : 1, "c" : 97 }





Prevoius                                                 Next                                                 Home

No comments:

Post a Comment