How to count the number of documents in a MongoDB collection?

MongoDBDatabaseBig Data Analytics

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
raja
Published on 11-Apr-2019 11:28:05
Advertisements