Aggregation In MongoDb

  1. It process the records and returns the result
  2. It group values from various documents in collection together
  3. Perform operations on the grouped data

We have aggregate method in mongodb and we pass different operation to pass in aggregate method. Ex. $sum ,$avg, $min, $max ,$first, $last.

db.employee.aggregate([{$group:{_id:”$department”,totalCount:{$sum:1}}}])

This query group the employee as per department from collection.

Distinct: to find out distinct field in collection use below method distinct and pass parameter as field which you want to pass.

db.employee.distinct(“department”)

  1. Count: Is use to get the count/ no of document present in collection.

db.employee.count()

To find out which field value repeated how many times or the value we can use below query in this we need to pass field name with value whose count want to get.

db.employee.find({department:”Sales”}).count()

Sorting: Sort function is used to sort the document and below is query which required to parameter field with value 1 and default sort is ascending.

db.employee.find().sort({salary:1}).pretty()

In this value +1 is for ascending order and -1 this value for descending order.

db.employee.find().sort({salary:-1}).pretty()

Natural order: in this we have to pass $natural with value 1. In this we get result last updated record last.

db.employee.find().sort({$natural:1}).pretty()

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *