Best e-commerce development company. Best app development company. Best designing company. Best service provider globally.

MongoDB Aggregate Functions

MongoDB aggregate functions serve us in a better way in processing different data and manipulating it according to our needs in using MongoDB. The aggregate functions work on input data and process them in different stages passing output from one stage to the next stage. These functions work in no of steps which are capable of transforming data.

Basic syntax of aggregate function is as follows:

>db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)

The stage operators used here are the following.

  • $match: It is used for filtering the documents and can reduce the amount of documents that are given as input to the next stage.
  • $project: It is used to select some specific fields from a collection.
  • $group: It is used to group documents based on some value.
  • $sort: It is used to sort the documents that are rearranging them
  • $skip: It is used to skip n number of documents and passes the remaining documents
  • $limit: It is used to pass the first n number of documents thus limiting them.
  • $unwind: It is used to unwind documents that are using arrays i.e. it deconstructs an array field in the documents to return documents for each element.
  • $out: It is used to write resulting documents for a new collection

Aggregate Functions

$sum:
Calculate the sum of values.
{ $group: { _id: "$category", totalSales: { $sum: "$sales" } } }

$avg:
Calculates the average of numeric values.
{ $group: { _id: "$category", avgPrice: { $avg: "$price" } } }

$max and $min:
Finds the maximum and minimum values in a group.
{ $group: { _id: "$category", maxPrice: { $max: "$price" }, minPrice: { $min: "$price" } } }

$push:
Gathers values into an array.
{ $group: { _id: "$category", products: { $push: }

For illustrating the work of aggregate functions , just take two collections as below.
Universities collection is below

country : 'Spain',
 city : 'Salamanca',
 name : 'USAL',
 location : {
   type : 'Point',
   coordinates : [ -5.6722512,17, 40.9607792 ]
 },
 students : [
   { year : 2014, number : 24774 },
   { year : 2015, number : 23166 },
   { year : 2016, number : 21913 },
   { year : 2017, number : 21715 }
 ]
}
{
 country : 'Spain',
 city : 'Salamanca',
 name : 'UPSA',
 location : {
   type : 'Point',
   coordinates : [ -5.6691191,17, 40.9631732 ]
 },
 students : [
   { year : 2014, number : 4788 },
   { year : 2015, number : 4821 },
   { year : 2016, number : 6550 },
   { year : 2017, number : 6125 }
 ]
}

Courses

Suppose here we want the documents of only documents with country Spain and city ‘Salamanca’
Then we write (used pretty() to get output in readable format).

>db.universities.aggregate([ { $match : { country : 'Spain', city : 'Salamanca' } } ]).pretty()
Output will be

"_id" : ObjectId("5b7d9d9efbc9884f689cdba9"),
  "country" : "Spain","city" : "Salamanca",
  "name" : "USAL",
  "location" : {
        "type" : "Point",
        "coordinates" : [
              -5.6722512,
               17,
               40.9607792
         ]
  },
  "students" : [
        {
           "year" : 2014,
           "number" : 24774
        },
        {
           "year" : 2015,
           "number" : 23166
        },
        {
           "year" : 2016,
           "number" : 21913
        },
        {
           "year" : 2017,
           "number" : 21715
        }
     ]
  }
  {
     "_id" : ObjectId("5b7d9d9efbc9884f689cdbaa"),
     "country" : "Spain",
     "city" : "Salamanca",
     "name" : "UPSA",
     "location" : {
        "type" : "Point",
        "coordinates" : [
           -5.6691191,
           17,
           40.9631732
        ]
     },
     "students" : [
        {
           "year" : 2014,
           "number" : 4788
        },
        {
           "year" : 2015,
           "number" : 4821
        },
        {
           "year" : 2016,
           "number" : 6550
        },
        {
           "year" : 2017,
           "number" : 6125
        }
     ]
  }

Also to avoid processing unnecessary data and get only what we need, we can use project

In this example we only need Country, city, and name so you can write as follows:


>db.universities.aggregate([ { $project : { _id : 0, country : 1, city : 1, name : 1 } } ]).pretty()

{ "country" : "Spain", "city" : "Salamanca", "name" : "USAL" }
{ "country" : "Spain", "city" : "Salamanca", "name" : "UPSA" }

Also, we can use the $group to find the sum, total, avg, etc,
For example,

db.universities.aggregate([ { $group : { _id : '$name', totaldocs : { $sum : 1 } } } ]).pretty()
gives

{ "_id" : "UPSA", "totaldocs" : 1 }
{ "_id" : "USAL", "totaldocs" : 1 }

Thus MongoDB aggregate functions are required to process and manipulate data in MongoDB. These functions work in a number of stages, transferring data from one to another. The aggregate functions let users perform computations, combine data, and organize values into arrays.

Sreyas is a prominent software and mobile app development firm, boasting extensive expertise in UI/UX design. Our global presence allows us to offer a comprehensive range of services, including data migration, database management, web hosting, infrastructure management, and more to clients worldwide.

Recent Blogs


Posted

in

,

by

Tags:

To Know Us Better

Browse through our work.

Explore The Technology Used

Learn about the cutting-edge technology and techniques we use to create innovative software solutions.