Saturday 21 February 2015

mongoDB : $last: aggregation


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

Syntax
{ $last: <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:{$last:"$c"}}} ])
{ "_id" : 0, "c" : 17 }
{ "_id" : 1, "c" : 5 }


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:{$last:"$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:{$last:"$c"}}} ])
{ "_id" : 0, "c" : 17 }
{ "_id" : 1, "c" : 5 }


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment