 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Grouping the array items in MongoDB and get the count the products with similar price?
To group the array items, use $group along with $sort. Let us create a collection with documents −
> db.demo566.insertOne( ... { ... ...    "ProductInformation" : [ ...       { ...          "ProductName" : "Product-1", ...          "ProductPrice" :100 ...       }, ...       { ...          "ProductName" : "Product-2", ...          "ProductPrice" :1100 ...       }, ...       { ...          "ProductName" : "Product-3", ...          "ProductPrice" :100 ...       }, ...       { ...          "ProductName" : "Product-4", ...          "ProductPrice" :1100 ...       }, ...       { ...          "ProductName" : "Product-5", ...          "ProductPrice" :100 ...       } ...    ] ... ... } ... ); {    "acknowledged" : true,    "insertedId" : ObjectId("5e908e2339cfeaaf0b97b57a") } Display all documents from a collection with the help of find() method −
> db.demo566.find();
This will produce the following output −
{ "_id" : ObjectId("5e908e2339cfeaaf0b97b57a"), "ProductInformation" : [    { "ProductName" : "Product-1", "ProductPrice" : 100 },    { "ProductName" : "Product-2", "ProductPrice" : 1100 },    { "ProductName" : "Product-3", "ProductPrice" : 100 },    { "ProductName" : "Product-4", "ProductPrice" : 1100 },    { "ProductName" : "Product-5", "ProductPrice" : 100 } ] } Following is the query to group the array items −
> db.demo566.aggregate([ ... { ...    "$unwind": "$ProductInformation" ... }, ... { ...    "$group": { ...       "_id": "$ProductInformation.ProductPrice", ...       "Value": { "$sum" : 1 } ...    } ... }, ... { "$sort": { "_id" :1 } } ... ]) This will produce the following output −
{ "_id" : 100, "Value" : 3 } { "_id" : 1100, "Value" : 2 }Advertisements
 