- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get the count of a specific value in MongoDB
To get the count of a specific value in MongoDB, use aggregate(). Let us create a collection with documents −
> db.demo210.insertOne( ... { ... details: [ ... { ... ClientName: "Robert" ... }, ... { ... ... lientName: "John Doe" ... }, ... { ... ... ClientName: "Robert" ... }, ... { ... ... ClientName: "Robert" ... }, ... { ... ... ClientName: "David Miller" ... } ... ] ... } ...); { "acknowledged" : true, "insertedId" : ObjectId("5e3d99ab03d395bdc21346f9") }
Display all documents from a collection with the help of find() method −
> db.demo210.find();
This will produce the following output −
{ "_id" : ObjectId("5e3d99ab03d395bdc21346f9"), "details" : [ { "ClientName" : "Robert" }, { "ClientName" : "John Doe" }, { "ClientName" : "Robert" }, { "ClientName" : "Robert" }, { "ClientName" : "David Miller" } ] }
Following is the query to get the count of a specific value −
> db.demo210.aggregate([ ... { "$match" : { "details.ClientName" : "Robert" } }, ... { "$unwind" : "$details" }, ... { "$match" : { "details.ClientName" : "Robert" } }, ... { "$group" : { "_id" : "$_id", "Size" : { "$sum" : 1 } } }, ... { "$match" : { "Size" : { "$gte" : 2 } } } ...]);
This will produce the following output −
{ "_id" : ObjectId("5e3d99ab03d395bdc21346f9"), "Size" : 3 }
Advertisements