- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 }
- Related Articles
- Get the count of a specific value in MongoDB quickly
- Get count of array elements from a specific field in MongoDB documents?
- How to get the count of a specific value in a column with MySQL?
- Fetch data between two dates and with a specific value in MongoDB. Group and get the sum with count?
- Find value above a specific value in MongoDB documents?
- Get the count of the number of documents in a MongoDB Collection?
- How to get items with a specific value from documents using MongoDB shell?
- MongoDB query to get a specific number of items
- Count distinct value in MongoDB?
- How to get values greater than a specific value from an embedded list in MongoDB?
- Get specific value of cell in MySQL
- Update only a specific value in a MongoDB document
- MongoDB $unwind to get the count
- MongoDB query to get specific list of names from documents where the value of a field is an array
- MongoDB query to get only a specific number of elements

Advertisements