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