$last operator in MongoDB

You are here : Home / MongoDB Tutorial


Contents of page >


$last operator in MongoDB >
$last operator returns the last document from documents in the collection in MongoDB.
1) First let's create insert documents in collection in MongoDB


1.1) First, Let's create new collection and insert document >
db.employee.insert({_id : 1,  firstName:"ank", salary : 1000 })
db.employee.insert({_id : 2,  firstName:"ank", salary : 2000 })
db.employee.insert({_id : 3,  firstName:"sag", salary : 3000 })
db.employee.insert({_id : 4,  firstName:"sag", salary : 4000 })
db.employee.insert({_id : 5,  firstName:"neh", salary : 5000 })
Above will create collection (or table) (if collection already exists it will insert documents in it).


1.2) FIND > Query all documents of collection using find() method>
db.employee.find()
Output>
{ "_id" : 1, "firstName" : "ank", "salary" : 1000 }
{ "_id" : 2, "firstName" : "ank", "salary" : 2000 }
{ "_id" : 3, "firstName" : "sag", "salary" : 3000 }
{ "_id" : 4, "firstName" : "sag", "salary" : 4000 }
{ "_id" : 5, "firstName" : "neh", "salary" : 5000 }


2) Find last salary of employee with same firstName in collection in MongoDB >


Step 2.1 - We will group employee by firstName and find last salary of each group.
Step 2.2 - We will use aggregate() method, $last operator and $group operator.
> db.employee.aggregate([{$group : {_id : "$firstName", salary_last : {$last : "$salary"}}}])
Output >
{ "_id" : "ank", "salary_last" : 2000 }
{ "_id" : "sag", "salary_last" : 4000 }
{ "_id" : "neh", "salary_last" : 5000 }


3) Find last salary of all employee in collection in MongoDB >


Step 3.1 - We will group employee by null (nothing) and find maximum salary of group (there will be only 1 group - i.e. whole documents of collection)
Step 3.2- We will use aggregate() method, $group operator, $last operator
> db.employee.aggregate([{$group : {_id : null, salary_last : {$last : "$salary"}}}])
Output >
{ "_id" : null, "salary_last" : 5000 }

4) Summary -
So in this MongoDB tutorial we learned about $last operator in MongoDB. $last operator returns the last document from documents in the collection in MongoDB.


Find last salary of employee with same firstName in collection in MongoDB >
> db.employee.aggregate([{$group : {_id : "$firstName", salary_last : {$last : "$salary"}}}])


Find last salary of all employee in collection in MongoDB >
> db.employee.aggregate([{$group : {_id : null, salary_last : {$last : "$salary"}}}])


Having any doubt? or you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter. You may join our fbGroup or linkedInGroup as well.


RELATED LINKS>

eEdit
Must read for you :