Count number of rows in a MongoDB collection


To count number of documents, use count() in MongoDB. Let us create a collection with documents −

> db.demo664.insertOne({_id:1,ClientName:"Chris"});
{ "acknowledged" : true, "insertedId" : 1 }
> db.demo664.insertOne({_id:2,ClientName:"Bob"});
{ "acknowledged" : true, "insertedId" : 2 }
> db.demo664.insertOne({_id:3,ClientName:"Sam"});
{ "acknowledged" : true, "insertedId" : 3 }
> db.demo664.insertOne({_id:4,ClientName:"David"});
{ "acknowledged" : true, "insertedId" : 4 }

Display all documents from a collection with the help of find() method −

> db.demo664.find();

This will produce the following output −

{ "_id" : 1, "ClientName" : "Chris" }
{ "_id" : 2, "ClientName" : "Bob" }
{ "_id" : 3, "ClientName" : "Sam" }
{ "_id" : 4, "ClientName" : "David" }

Following is the query to count number of rows −

> var numberOfRows=db.demo664.count();
> print ("Number Of Rows="+numberOfRows);

This will produce the following output −

Number Of Rows=4

Updated on: 13-May-2020

654 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements