{"id":56755,"date":"2018-04-11T11:00:30","date_gmt":"2018-04-11T08:00:30","guid":{"rendered":"http:\/\/examples.javacodegeeks.com\/?p=56755"},"modified":"2018-04-18T15:22:23","modified_gmt":"2018-04-18T12:22:23","slug":"mongodb-aggregation-example","status":"publish","type":"post","link":"https:\/\/examples.javacodegeeks.com\/software-development\/mongodb\/mongodb-aggregation-example\/","title":{"rendered":"MongoDB Aggregation Example"},"content":{"rendered":"<p>Hello readers, <strong>aggregation<\/strong> in Mongo database is an operation that processes the multiple documents and returns a single computed result. In this tutorial, we will learn how to use the different <span style=\"text-decoration: underline;\">aggregation<\/span> operations in the Mongo database.<\/p>\n<h2>1. Introduction<\/h2>\n<p>If you have installed the MongoDB application (<em>version 3.6<\/em>) on Windows or Ubuntu operating system and you wish to learn the regular expressions then follow the below steps. It is very simple, but before moving further let&#8217;s take a look at the Mongo database and its characteristics.<\/p>\n<h3>1.1 What is MongoDB?<\/h3>\n<ul>\n<li>MongoDB is a high-performance <em>NoSQL database<\/em> where each database has collections which in turn has documents. Each document has a different number of fields, size, content, and is stored in a JSON-like format (i.e. Binary JSON (<a href=\"https:\/\/en.wikipedia.org\/wiki\/BSON\" target=\"_blank\" rel=\"noopener\">BSN<\/a>))<\/li>\n<li>The documents in MongoDB don\u2019t need to have a schema defined beforehand. Instead, the fields (i.e. <em>records<\/em>) can be created on the go<\/li>\n<li>Data model available within the MongoDB allows developers to represent the hierarchical relationships, store arrays, and other more complex structures easily<\/li>\n<li>This NoSQL solution often comes with embedding, auto-sharding, and onboard replication for better scalability and high availability<\/li>\n<\/ul>\n<h4>1.1.1 Why MongoDB?<\/h4>\n<ul>\n<li>As a NoSQL type database, MongoDB stores the data in the form of a document. Thus, MongoDB offers more flexibility<\/li>\n<li>This database supports search by field-name, range queries, and the regular expressions. It often provides queries to return the particular fields inside the documents<\/li>\n<li>MongoDB offers <em>indexes<\/em> to improve the <em>search performance<\/em> within the NoSQL database<\/li>\n<li>To offer horizontal scalability, MongoDB uses sharding by splitting the data across the many MongoDB occurrences<\/li>\n<li><strong>Replication<\/strong>: MongoDB can give high availability with the replica sets<\/li>\n<\/ul>\n<h2>2. MongoDB Aggregation Example<\/h2>\n<p>In this tutorial, we will learn what &#8220;<em>aggregation<\/em>&#8221; is and how to handle the different &#8220;<em>aggregation operations<\/em>&#8221; in the Mongo database.<\/p>\n<h3>2.1 Aggregation in the Mongo database<\/h3>\n<p>In the Mongo universe, the <code><a href=\"https:\/\/docs.mongodb.com\/manual\/reference\/method\/db.collection.aggregate\/\" target=\"_blank\" rel=\"noopener\">aggregate()<\/a><\/code> method groups the documents of a collection to provide a total sum, average, minimum, maximum etc. of the grouped documents. In other words, this method calculates the gross values for the documents in a collection. The <code>aggregate()<\/code> method has the following prototype form:<\/p>\n<p><span style=\"text-decoration: underline;\"><em>Mongo database &#8216;aggregate()&#8217; method Syntax<\/em><\/span><\/p>\n<pre class=\"brush:bash;wrap-lines:false;\">&gt; db.collection_name.aggregate(pipeline_operation, options)\r\n<\/pre>\n<p>Where:<\/p>\n<ul>\n<li>The <code>collection_name<\/code> is the name of the collection on which the aggregate function is applied<\/li>\n<li>A <code>pipeline_operation<\/code> is a required array argument which performs a sequence of aggregation options. Each option transforms the Mongo document and gives a final computed result<\/li>\n<li>The <code>options<\/code> are the optional input argument that is passed to the aggregation function<\/li>\n<\/ul>\n<p><figure id=\"attachment_56756\" aria-describedby=\"caption-attachment-56756\" style=\"width: 820px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-archi-guide-1.jpg\"><img decoding=\"async\" class=\"wp-image-56756\" src=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-archi-guide-1.jpg\" alt=\"Fig. 1: Aggregation\/Pipeline operation in Mongo database\" width=\"820\" height=\"126\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-archi-guide-1.jpg 849w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-archi-guide-1-300x46.jpg 300w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-archi-guide-1-768x118.jpg 768w\" sizes=\"(max-width: 820px) 100vw, 820px\" \/><\/a><figcaption id=\"caption-attachment-56756\" class=\"wp-caption-text\">Fig. 1: Aggregation\/Pipeline operation in Mongo database<\/figcaption><\/figure><\/p>\n<h4>2.1.1 Different Pipeline operators<\/h4>\n<p>Below table lists the different pipeline operators that are commonly used in the Mongo database.<\/p>\n<table>\n<thead>\n<tr>\n<th style=\"text-align: center;\"><strong>SQL<\/strong><\/th>\n<th style=\"text-align: center;\"><strong>MongoDB<\/strong><\/th>\n<th style=\"text-align: center;\"><strong>Description<\/strong><\/th>\n<th style=\"text-align: center;\"><strong>Example Query<\/strong><\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td style=\"text-align: center;\"><code>SELECT<\/code><\/td>\n<td style=\"text-align: center;\"><code>$project<\/code><\/td>\n<td>This function <em>passes the existing fields<\/em> from the Mongo document or the <em>newly evaluated fields<\/em> to the next option in the pipeline. In this, developers use &#8216;1&#8217; or &#8216;true&#8217; if they want to include the Field and &#8216;0&#8217; or &#8216;false&#8217; if they want to exclude a field.<\/td>\n<td><code>db.employee.aggregate([ {\"$project\": { \"_id\" : 0, \"emp_fname\" : 1, \"emp_dept\" : 1, \"emp_band\" : 1, \"emp_specs\" : 1 }} ])<\/code><\/td>\n<\/tr>\n<tr>\n<td style=\"text-align: center;\"><code>WHERE<\/code><\/td>\n<td style=\"text-align: center;\"><code>$match<\/code><\/td>\n<td>This function <em>filters<\/em> the documents of a collection that matches the specific criteria and pass only the matched documents to the next pipeline option.<\/td>\n<td><code>db.employee.aggregate([ {\"$match\": { \"emp_dept\": \"Finance\" }} ])<\/code><\/td>\n<\/tr>\n<tr>\n<td style=\"text-align: center;\"><code>LIMIT<\/code><\/td>\n<td style=\"text-align: center;\"><code>$limit<\/code><\/td>\n<td>This function <em>bound<\/em> the first &#8216;<code>n<\/code>&#8216; unmodified documents and passes them to the next option in the pipeline.<\/td>\n<td><code>db.employee.aggregate([ {\"$match\": { \"emp_dept\": \"Technology\" }}, {\"$limit\": 1} ])<\/code><\/td>\n<\/tr>\n<tr>\n<td style=\"text-align: center;\"><code>GROUPBY<\/code><\/td>\n<td style=\"text-align: center;\"><code>$group<\/code><\/td>\n<td>This function <em>groups<\/em> the documents of a Mongo collection by specific criteria and pass them to the next option of the aggregation pipeline.<\/td>\n<td><code>db.employee.aggregate([ {\"$group\": {\"_id\": {\"emp_dept\" : \"$emp_dept\"}, \"No_of_Times\": {\"$sum\": 1}}} ])<\/code><\/td>\n<\/tr>\n<tr>\n<td style=\"text-align: center;\"><code>ORDERBY<\/code><\/td>\n<td style=\"text-align: center;\"><code>$sort<\/code><\/td>\n<td>This function <em>re-orders<\/em> the documents of a Mongo collection either in the ascending or the descending order.<\/td>\n<td><code>db.employee.aggregate([ {\"$match\": { \"emp_dept\": \"HR\" }}, {\"$sort\" : {\"emp_fname\": 1}} ])<\/code><\/td>\n<\/tr>\n<tr>\n<td style=\"text-align: center;\"><code>JOIN<\/code><\/td>\n<td style=\"text-align: center;\"><code>$lookup<\/code><\/td>\n<td>This function performs a left-outer join with another collection in the same Mongo database.<\/td>\n<td><code>db.emp_city.aggregate([ {$lookup: {from: \"employee\", localField: \"emp_country_id\", foreignField: \"_id\", as: \"Country\" }} ])<\/code><\/td>\n<\/tr>\n<tr>\n<td style=\"text-align: center;\"><\/td>\n<td style=\"text-align: center;\"><code>$out<\/code><\/td>\n<td>This function writes the computed result to a specific collection in the Mongo database. This operator must be the last option in the aggregation pipeline.<\/td>\n<td><code>db.employee.aggregate([ {\"$match\": { \"emp_dept\": \"HR\" }}, {\"$sort\" : {\"emp_fname\": 1}}, {\"$out\" : \"sorted_emp\"} ])<\/code><\/td>\n<\/tr>\n<tr>\n<td style=\"text-align: center;\"><\/td>\n<td style=\"text-align: center;\"><code>$unwind<\/code><\/td>\n<td>This function deconstructs an array field from the inputted document to output a document for each element.<\/td>\n<td><code>db.employee.aggregate([ {\"$match\": { \"emp_fname\": \"April\" }}, {\"$unwind\": \"$emp_specs\"} ])<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h4>2.1.2 Different Expressions used by the Aggregation function<\/h4>\n<p>Below table lists the different expressions that are used by the aggregation function in the Mongo database.<div style=\"display:inline-block; margin: 15px 0;\"> <div id=\"adngin-JavaCodeGeeks_incontent_video-0\" style=\"display:inline-block;\"><\/div> <\/div><\/p>\n<table>\n<thead>\n<tr>\n<th style=\"text-align: center;\"><\/th>\n<th style=\"text-align: center;\"><strong>Expression<\/strong><\/th>\n<th style=\"text-align: center;\"><strong>Description<\/strong><\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td style=\"text-align: center;\">1<\/td>\n<td style=\"text-align: center;\"><code>$sum<\/code><\/td>\n<td>Amount the defined values of all the documents in a collection.<\/td>\n<\/tr>\n<tr>\n<td style=\"text-align: center;\">2<\/td>\n<td style=\"text-align: center;\"><code>$avg<\/code><\/td>\n<td>Calculate the average values of all the documents in a collection.<\/td>\n<\/tr>\n<tr>\n<td style=\"text-align: center;\">3<\/td>\n<td style=\"text-align: center;\"><code>$min<\/code><\/td>\n<td>Return the <em>minimum<\/em> value.<\/td>\n<\/tr>\n<tr>\n<td style=\"text-align: center;\">4<\/td>\n<td style=\"text-align: center;\"><code>$max<\/code><\/td>\n<td>Return the <em>maximum<\/em> value.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3>2.2 Practical usage<\/h3>\n<p>Let&#8217;s understand the implementation of this method with the help of the sample snippets.<\/p>\n<h4>2.2.1 Start MongoDB<\/h4>\n<p>Start a standalone <a href=\"https:\/\/docs.mongodb.com\/manual\/reference\/program\/mongod\/#bin.mongod\" target=\"_blank\" rel=\"noopener\">mongod<\/a> instance as shown below.<\/p>\n<p><figure id=\"attachment_56757\" aria-describedby=\"caption-attachment-56757\" style=\"width: 820px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-guide-1.jpg\"><img decoding=\"async\" class=\"wp-image-56757\" src=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-guide-1.jpg\" alt=\"Fig. 2: Start Mongo instance\" width=\"820\" height=\"592\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-guide-1.jpg 849w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-guide-1-300x217.jpg 300w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-guide-1-768x555.jpg 768w\" sizes=\"(max-width: 820px) 100vw, 820px\" \/><\/a><figcaption id=\"caption-attachment-56757\" class=\"wp-caption-text\">Fig. 2: Start Mongo instance<\/figcaption><\/figure><\/p>\n<h4>2.2.2 Connect to the Mongo Instance<\/h4>\n<p>Connect with the <a href=\"https:\/\/docs.mongodb.com\/manual\/reference\/program\/mongo\/#bin.mongo\" target=\"_blank\" rel=\"noopener\">mongo<\/a> shell to make a connection with the MongoDB instance on the port <code>27017<\/code> as shown below.<\/p>\n<p><figure id=\"attachment_56758\" aria-describedby=\"caption-attachment-56758\" style=\"width: 820px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-guide-2.jpg\"><img decoding=\"async\" class=\"wp-image-56758\" src=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-guide-2.jpg\" alt=\"Fig. 3: Connect to Mongo database\" width=\"820\" height=\"350\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-guide-2.jpg 849w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-guide-2-300x128.jpg 300w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-guide-2-768x327.jpg 768w\" sizes=\"(max-width: 820px) 100vw, 820px\" \/><\/a><figcaption id=\"caption-attachment-56758\" class=\"wp-caption-text\">Fig. 3: Connect to Mongo database<\/figcaption><\/figure><\/p>\n<h4>2.2.3 Create Mongo database and collection<\/h4>\n<p>To begin with the implementation, we will need to create a sample database and collection. The below script creates a database called <code>office<\/code> with a collection of <code>employee<\/code>. Open the Mongo terminal and execute the script.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>Database &amp; Collection creation script<\/em><\/span><\/p>\n<pre class=\"brush:bash;wrap-lines:false;\">&gt; use office\r\n\r\n&gt; db.employee.insertMany( [\r\n\t{ _id: 1, \"emp_fname\" : \"Jason\", \"emp_dept\" : \"Technology\", \"emp_band\" : \"C1\", \"emp_specs\": [ \"Java\", \"AngularJs\", \"MongoDb\" ] },\r\n\t{ _id: 2, \"emp_fname\" : \"Charlotte\", \"emp_dept\" : \"Finance\", \"emp_band\" : \"C0\", \"emp_specs\": [ \"Accounting\" ] },\r\n\t{ _id: 3, \"emp_fname\" : \"Daniel\", \"emp_dept\" : \"Technology\", \"emp_band\" : \"C2\", \"emp_specs\": [ \"Java\", \"AngularJs\" ] },\r\n\t{ _id: 4, \"emp_fname\" : \"April\", \"emp_dept\" : \"Technology\", \"emp_band\" : \"C1\", \"emp_specs\": [ \"AngularJs\", \"MongoDb\" ] },\r\n\t{ _id: 5, \"emp_fname\" : \"Ed\", \"emp_dept\" : \"Finance\", \"emp_band\" : \"C1\", \"emp_specs\": [ \"Accounting\", \"Payroll\" ] },\r\n\t{ _id: 6, \"emp_fname\" : \"Susan\", \"emp_dept\" : \"HR\", \"emp_band\" : \"C0\", \"emp_specs\": [ \"Personality Development\", \"Employee Concern\" ] },\r\n\t{ _id: 7, \"emp_fname\" : \"Marie\", \"emp_dept\" : \"HR\", \"emp_band\" : \"C2\", \"emp_specs\": [ \"Employee Safety\" ] },\r\n\t{ _id: 8, \"emp_fname\" : \"Jeff\", \"emp_dept\" : \"COO\", \"emp_band\" : \"C5\", \"emp_specs\": [ \"Delivery Leader\", \"Employee Safety\" ] },\r\n\t{ _id: 9, \"emp_fname\" : \"John\", \"emp_dept\" : \"CEO\", \"emp_band\" : \"C8\", \"emp_specs\": [ \"Global Delivery Leader\" ] }\r\n] )\r\n<\/pre>\n<p>The script gives the below output.<\/p>\n<p><figure id=\"attachment_56764\" aria-describedby=\"caption-attachment-56764\" style=\"width: 820px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-guide-3_rgb.jpg\"><img decoding=\"async\" class=\"wp-image-56764\" src=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-guide-3_rgb.jpg\" alt=\"Fig. 4: Database &amp;amp; Collection creation\" width=\"820\" height=\"247\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-guide-3_rgb.jpg 849w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-guide-3_rgb-300x90.jpg 300w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-guide-3_rgb-768x232.jpg 768w\" sizes=\"(max-width: 820px) 100vw, 820px\" \/><\/a><figcaption id=\"caption-attachment-56764\" class=\"wp-caption-text\">Fig. 4: Database &amp; Collection creation<\/figcaption><\/figure><\/p>\n<h4>2.2.4 Check Mongo database and collection<\/h4>\n<p>If the script works well, the database and the collection will be shown in the Mongo Workbench. Using the <code>db.collection_name.find()<\/code> or the <code>db.collection_name.find().pretty()<\/code> command the documents of a collection will be shown as below.<\/p>\n<p><figure id=\"attachment_56765\" aria-describedby=\"caption-attachment-56765\" style=\"width: 399px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-guide-4_rgb.jpg\"><img decoding=\"async\" class=\"wp-image-56765 size-full\" src=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-guide-4_rgb.jpg\" alt=\"Fig. 5: Mongo database &amp;amp; collection\" width=\"399\" height=\"696\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-guide-4_rgb.jpg 399w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-guide-4_rgb-172x300.jpg 172w\" sizes=\"(max-width: 399px) 100vw, 399px\" \/><\/a><figcaption id=\"caption-attachment-56765\" class=\"wp-caption-text\">Fig. 5: Mongo database &amp; collection<\/figcaption><\/figure><\/p>\n<h4>2.2.5 Implementation of Aggregation method<\/h4>\n<p>Now, go back to the Mongo shell and let\u2019s understand the practical implementation of the &#8216;aggregation&#8217; function in the Mongo world. The following Mongo database command can be used.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>Query 1<\/em><\/span><\/p>\n<pre class=\"brush:bash;wrap-lines:false;\">&gt; db.employee.aggregate([ {\"$match\": { \"emp_dept\": \"Technology\" }}, {\"$group\": {\"_id\": {\"emp_dept\" : \"$emp_dept\"}, \"No_of_Times\": {\"$sum\": 1}}} ])\r\n<\/pre>\n<p>As shown in Fig. 6, the Query 1 snippet will start looking into the <code>employee<\/code> collection for the documents where <code>emp_dept<\/code> equals to &#8220;<em>Technology<\/em>&#8221; and group the matching documents by the <code>emp_dept<\/code> field and calculates the no. of times each group appears.<\/p>\n<p><figure id=\"attachment_56766\" aria-describedby=\"caption-attachment-56766\" style=\"width: 820px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-guide-5_rgb.jpg\"><img decoding=\"async\" class=\"wp-image-56766\" src=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-guide-5_rgb.jpg\" alt=\"Fig. 6: Mongo database 'Aggregation' function\" width=\"820\" height=\"58\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-guide-5_rgb.jpg 849w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-guide-5_rgb-300x21.jpg 300w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-guide-5_rgb-768x54.jpg 768w\" sizes=\"(max-width: 820px) 100vw, 820px\" \/><\/a><figcaption id=\"caption-attachment-56766\" class=\"wp-caption-text\">Fig. 6: Mongo database &#8216;Aggregation&#8217; function<\/figcaption><\/figure><\/p>\n<p>Let\u2019s say developers want to group the documents of a collection on the basis of employee department and display the total number of employees present under that department. The following Mongo database command can be used.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>Query 2<\/em><\/span><\/p>\n<pre class=\"brush:bash;wrap-lines:false;\">&gt; db.employee.aggregate([ {\"$group\": {\"_id\": {\"emp_dept\" : \"$emp_dept\"}, \"Total_count_of_employees\": {\"$sum\": 1}}} ])\r\n<\/pre>\n<p>As shown in Fig. 7, the Query 2 aggregate function will group the collection data based on the <em>departments<\/em> and display the total number of employees.<\/p>\n<p><figure id=\"attachment_56768\" aria-describedby=\"caption-attachment-56768\" style=\"width: 820px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-guide-6_rgb.jpg\"><img decoding=\"async\" class=\"wp-image-56768\" src=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-guide-6_rgb.jpg\" alt=\"Fig. 7: Mongo database 'Aggregation' function with '$group' and '$sum' Operators\" width=\"820\" height=\"93\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-guide-6_rgb.jpg 849w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-guide-6_rgb-300x34.jpg 300w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/mongodb-aggregation-project-guide-6_rgb-768x87.jpg 768w\" sizes=\"(max-width: 820px) 100vw, 820px\" \/><\/a><figcaption id=\"caption-attachment-56768\" class=\"wp-caption-text\">Fig. 7: Mongo database &#8216;Aggregation&#8217; function with &#8216;$group&#8217; and &#8216;$sum&#8217; Operators<\/figcaption><\/figure><\/p>\n<p>That\u2019s all for this post. Happy Learning!!<\/p>\n<h2>3. Conclusion<\/h2>\n<p>In this tutorial, we learned about the different <span style=\"text-decoration: underline;\">aggregation<\/span> operations in the Mongo database. Developers can download the sample Mongo shell commands in the <a href=\"#projectDownload\">Downloads<\/a> section.<\/p>\n<h2><a name=\"projectDownload\"><\/a>4. Download the Eclipse Project<\/h2>\n<p>This was an example of implementing and using the aggregation operations in the Mongo database.<\/p>\n<div class=\"download\"><strong>Download<\/strong><br \/>\nYou can download the full source code of this example here: <a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2018\/04\/CodeSnippet.zip\" target=\"_blank\" rel=\"noopener\"><strong>Aggregation Operations<\/strong><\/a><\/div>\n","protected":false},"excerpt":{"rendered":"<p>Hello readers, aggregation in Mongo database is an operation that processes the multiple documents and returns a single computed result. In this tutorial, we will learn how to use the different aggregation operations in the Mongo database. 1. Introduction If you have installed the MongoDB application (version 3.6) on Windows or Ubuntu operating system and &hellip;<\/p>\n","protected":false},"author":119,"featured_media":36154,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1447],"tags":[1717,1194],"class_list":["post-56755","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-mongodb","tag-aggregation","tag-mongodb"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>MongoDB Aggregation Example - Java Code Geeks<\/title>\n<meta name=\"description\" content=\"Hello readers, in this tutorial, we will learn how to use the different aggregation operations in the Mongo database.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/examples.javacodegeeks.com\/software-development\/mongodb\/mongodb-aggregation-example\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"MongoDB Aggregation Example - Java Code Geeks\" \/>\n<meta property=\"og:description\" content=\"Hello readers, in this tutorial, we will learn how to use the different aggregation operations in the Mongo database.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/examples.javacodegeeks.com\/software-development\/mongodb\/mongodb-aggregation-example\/\" \/>\n<meta property=\"og:site_name\" content=\"Examples Java Code Geeks\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/javacodegeeks\" \/>\n<meta property=\"article:published_time\" content=\"2018-04-11T08:00:30+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2018-04-18T12:22:23+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/04\/mongodb-logo.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"150\" \/>\n\t<meta property=\"og:image:height\" content=\"150\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Yatin\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:site\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Yatin\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"7 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/software-development\/mongodb\/mongodb-aggregation-example\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/software-development\/mongodb\/mongodb-aggregation-example\/\"},\"author\":{\"name\":\"Yatin\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/9874407a37b028e8be3276e2b5960d13\"},\"headline\":\"MongoDB Aggregation Example\",\"datePublished\":\"2018-04-11T08:00:30+00:00\",\"dateModified\":\"2018-04-18T12:22:23+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/software-development\/mongodb\/mongodb-aggregation-example\/\"},\"wordCount\":1101,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/software-development\/mongodb\/mongodb-aggregation-example\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/04\/mongodb-logo.jpg\",\"keywords\":[\"Aggregation\",\"MongoDb\"],\"articleSection\":[\"MongoDB\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/examples.javacodegeeks.com\/software-development\/mongodb\/mongodb-aggregation-example\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/software-development\/mongodb\/mongodb-aggregation-example\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/software-development\/mongodb\/mongodb-aggregation-example\/\",\"name\":\"MongoDB Aggregation Example - Java Code Geeks\",\"isPartOf\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/software-development\/mongodb\/mongodb-aggregation-example\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/software-development\/mongodb\/mongodb-aggregation-example\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/04\/mongodb-logo.jpg\",\"datePublished\":\"2018-04-11T08:00:30+00:00\",\"dateModified\":\"2018-04-18T12:22:23+00:00\",\"description\":\"Hello readers, in this tutorial, we will learn how to use the different aggregation operations in the Mongo database.\",\"breadcrumb\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/software-development\/mongodb\/mongodb-aggregation-example\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/examples.javacodegeeks.com\/software-development\/mongodb\/mongodb-aggregation-example\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/software-development\/mongodb\/mongodb-aggregation-example\/#primaryimage\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/04\/mongodb-logo.jpg\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/04\/mongodb-logo.jpg\",\"width\":150,\"height\":150},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/software-development\/mongodb\/mongodb-aggregation-example\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/examples.javacodegeeks.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Software Development\",\"item\":\"https:\/\/examples.javacodegeeks.com\/category\/software-development\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"MongoDB\",\"item\":\"https:\/\/examples.javacodegeeks.com\/category\/software-development\/mongodb\/\"},{\"@type\":\"ListItem\",\"position\":4,\"name\":\"MongoDB Aggregation Example\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#website\",\"url\":\"https:\/\/examples.javacodegeeks.com\/\",\"name\":\"Java Code Geeks\",\"description\":\"Java Examples and Code Snippets\",\"publisher\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\"},\"alternateName\":\"JCG\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/examples.javacodegeeks.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\",\"name\":\"Exelixis Media P.C.\",\"url\":\"https:\/\/examples.javacodegeeks.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"width\":864,\"height\":246,\"caption\":\"Exelixis Media P.C.\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/javacodegeeks\",\"https:\/\/x.com\/javacodegeeks\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/9874407a37b028e8be3276e2b5960d13\",\"name\":\"Yatin\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2023\/09\/cropped-Yatin-Batra_avatar_1515758148-96x96.jpg\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2023\/09\/cropped-Yatin-Batra_avatar_1515758148-96x96.jpg\",\"caption\":\"Yatin\"},\"description\":\"An experience full-stack engineer well versed with Core Java, Spring\/Springboot, MVC, Security, AOP, Frontend (Angular &amp; React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).\",\"sameAs\":[\"https:\/\/www.javacodegeeks.com\"],\"url\":\"https:\/\/examples.javacodegeeks.com\/author\/yatin-batra\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"MongoDB Aggregation Example - Java Code Geeks","description":"Hello readers, in this tutorial, we will learn how to use the different aggregation operations in the Mongo database.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/examples.javacodegeeks.com\/software-development\/mongodb\/mongodb-aggregation-example\/","og_locale":"en_US","og_type":"article","og_title":"MongoDB Aggregation Example - Java Code Geeks","og_description":"Hello readers, in this tutorial, we will learn how to use the different aggregation operations in the Mongo database.","og_url":"https:\/\/examples.javacodegeeks.com\/software-development\/mongodb\/mongodb-aggregation-example\/","og_site_name":"Examples Java Code Geeks","article_publisher":"https:\/\/www.facebook.com\/javacodegeeks","article_published_time":"2018-04-11T08:00:30+00:00","article_modified_time":"2018-04-18T12:22:23+00:00","og_image":[{"width":150,"height":150,"url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/04\/mongodb-logo.jpg","type":"image\/jpeg"}],"author":"Yatin","twitter_card":"summary_large_image","twitter_creator":"@javacodegeeks","twitter_site":"@javacodegeeks","twitter_misc":{"Written by":"Yatin","Est. reading time":"7 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/examples.javacodegeeks.com\/software-development\/mongodb\/mongodb-aggregation-example\/#article","isPartOf":{"@id":"https:\/\/examples.javacodegeeks.com\/software-development\/mongodb\/mongodb-aggregation-example\/"},"author":{"name":"Yatin","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/9874407a37b028e8be3276e2b5960d13"},"headline":"MongoDB Aggregation Example","datePublished":"2018-04-11T08:00:30+00:00","dateModified":"2018-04-18T12:22:23+00:00","mainEntityOfPage":{"@id":"https:\/\/examples.javacodegeeks.com\/software-development\/mongodb\/mongodb-aggregation-example\/"},"wordCount":1101,"commentCount":0,"publisher":{"@id":"https:\/\/examples.javacodegeeks.com\/#organization"},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/software-development\/mongodb\/mongodb-aggregation-example\/#primaryimage"},"thumbnailUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/04\/mongodb-logo.jpg","keywords":["Aggregation","MongoDb"],"articleSection":["MongoDB"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/examples.javacodegeeks.com\/software-development\/mongodb\/mongodb-aggregation-example\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/examples.javacodegeeks.com\/software-development\/mongodb\/mongodb-aggregation-example\/","url":"https:\/\/examples.javacodegeeks.com\/software-development\/mongodb\/mongodb-aggregation-example\/","name":"MongoDB Aggregation Example - Java Code Geeks","isPartOf":{"@id":"https:\/\/examples.javacodegeeks.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/examples.javacodegeeks.com\/software-development\/mongodb\/mongodb-aggregation-example\/#primaryimage"},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/software-development\/mongodb\/mongodb-aggregation-example\/#primaryimage"},"thumbnailUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/04\/mongodb-logo.jpg","datePublished":"2018-04-11T08:00:30+00:00","dateModified":"2018-04-18T12:22:23+00:00","description":"Hello readers, in this tutorial, we will learn how to use the different aggregation operations in the Mongo database.","breadcrumb":{"@id":"https:\/\/examples.javacodegeeks.com\/software-development\/mongodb\/mongodb-aggregation-example\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/examples.javacodegeeks.com\/software-development\/mongodb\/mongodb-aggregation-example\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/software-development\/mongodb\/mongodb-aggregation-example\/#primaryimage","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/04\/mongodb-logo.jpg","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/04\/mongodb-logo.jpg","width":150,"height":150},{"@type":"BreadcrumbList","@id":"https:\/\/examples.javacodegeeks.com\/software-development\/mongodb\/mongodb-aggregation-example\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/examples.javacodegeeks.com\/"},{"@type":"ListItem","position":2,"name":"Software Development","item":"https:\/\/examples.javacodegeeks.com\/category\/software-development\/"},{"@type":"ListItem","position":3,"name":"MongoDB","item":"https:\/\/examples.javacodegeeks.com\/category\/software-development\/mongodb\/"},{"@type":"ListItem","position":4,"name":"MongoDB Aggregation Example"}]},{"@type":"WebSite","@id":"https:\/\/examples.javacodegeeks.com\/#website","url":"https:\/\/examples.javacodegeeks.com\/","name":"Java Code Geeks","description":"Java Examples and Code Snippets","publisher":{"@id":"https:\/\/examples.javacodegeeks.com\/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/examples.javacodegeeks.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/examples.javacodegeeks.com\/#organization","name":"Exelixis Media P.C.","url":"https:\/\/examples.javacodegeeks.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/javacodegeeks","https:\/\/x.com\/javacodegeeks"]},{"@type":"Person","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/9874407a37b028e8be3276e2b5960d13","name":"Yatin","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/image\/","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2023\/09\/cropped-Yatin-Batra_avatar_1515758148-96x96.jpg","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2023\/09\/cropped-Yatin-Batra_avatar_1515758148-96x96.jpg","caption":"Yatin"},"description":"An experience full-stack engineer well versed with Core Java, Spring\/Springboot, MVC, Security, AOP, Frontend (Angular &amp; React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).","sameAs":["https:\/\/www.javacodegeeks.com"],"url":"https:\/\/examples.javacodegeeks.com\/author\/yatin-batra\/"}]}},"_links":{"self":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/56755","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/users\/119"}],"replies":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/comments?post=56755"}],"version-history":[{"count":0,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/56755\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/media\/36154"}],"wp:attachment":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/media?parent=56755"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/categories?post=56755"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/tags?post=56755"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}