

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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
Get the count of a specific value in MongoDB quickly
For faster queries, create an index. To get the count, use count(). Let us create a collection with documents −
> db.demo311.ensureIndex({"Name":1}); { "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.demo311.insertOne({"Name":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50cd01f8647eb59e562044") } > db.demo311.insertOne({"Name":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50cd05f8647eb59e562045") } > db.demo311.insertOne({"Name":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50cd06f8647eb59e562046") } > db.demo311.insertOne({"Name":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50cd0af8647eb59e562047") } > db.demo311.insertOne({"Name":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50cd0df8647eb59e562048") } > db.demo311.insertOne({"Name":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50cd0ff8647eb59e562049") }
Display all documents from a collection with the help of find() method −
> db.demo311.find();
This will produce the following output −
{ "_id" : ObjectId("5e50cd01f8647eb59e562044"), "Name" : "Chris" } { "_id" : ObjectId("5e50cd05f8647eb59e562045"), "Name" : "David" } { "_id" : ObjectId("5e50cd06f8647eb59e562046"), "Name" : "David" } { "_id" : ObjectId("5e50cd0af8647eb59e562047"), "Name" : "Chris" } { "_id" : ObjectId("5e50cd0df8647eb59e562048"), "Name" : "Bob" } { "_id" : ObjectId("5e50cd0ff8647eb59e562049"), "Name" : "Chris" }
Following is the query to get the count of a specific value −
> db.demo311.find({"Name":"Chris"}).count();
This will produce the following output −
3
- Related Questions & Answers
- Get the count of a specific value in MongoDB
- How to get the count of a specific value in a column with MySQL?
- Get count of array elements from a specific field in MongoDB documents?
- Fetch data between two dates and with a specific value in MongoDB. Group and get the sum with count?
- Get the count of the number of documents in a MongoDB Collection?
- Find value above a specific value in MongoDB documents?
- Get specific value of cell in MySQL
- MongoDB query to get a specific number of items
- Update tag records in MongoDB quickly
- MongoDB $unwind to get the count
- Count distinct value in MongoDB?
- Update only a specific value in a MongoDB document
- How to get items with a specific value from documents using MongoDB shell?
- MongoDB query to get only a specific number of elements
- MongoDB query to get specific list of names from documents where the value of a field is an array
Advertisements