 
  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
How to count the number of documents in a MongoDB collection?
Following is the syntax to count the number of documents in a MongoDB collection
let anyVariableName= db.getCollection(‘yourCollectionName’); yourVariableName.count();
Let us first create a collection with documents
> db.countNumberOfDocumentsDemo.insertOne({"CustomerName":"Bob"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5c9a5e2015e86fd1496b38a1") } >db.countNumberOfDocumentsDemo.insertOne({"CustomerName":"Ramit","CustomerAge":23}); {    "acknowledged" : true,    "insertedId" : ObjectId("5c9a5e3515e86fd1496b38a2") } >db.countNumberOfDocumentsDemo.insertOne({"CustomerName":"Adam","CustomerAge":27,"CustomerCountryName":"US"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5c9a5e4c15e86fd1496b38a3") } Following is the query to display all documents from a collection with the help of find() method
> db.countNumberOfDocumentsDemo.find().pretty();
This will produce the following output
{ "_id" : ObjectId("5c9a5e2015e86fd1496b38a1"), "CustomerName" : "Bob" } {    "_id" : ObjectId("5c9a5e3515e86fd1496b38a2"),    "CustomerName" : "Ramit",    "CustomerAge" : 23 } {    "_id" : ObjectId("5c9a5e4c15e86fd1496b38a3"),    "CustomerName" : "Adam",    "CustomerAge" : 27,    "CustomerCountryName" : "US" } Following is the query to count the number of documents in a MongoDB collection,
> let myCollectionName = db.getCollection('countNumberOfDocumentsDemo'); > myCollectionName.count(); This will produce the following output
3
Advertisements
 