To get number of records, use count() in MongoDB. Let us create a collection with documents −
> db.demo697.insertOne({Name:"Chris",Age:21}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6d7d1551299a9f98c9395") } > db.demo697.insertOne({Name:"Bob",Age:23}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6d7d8551299a9f98c9396") } > db.demo697.insertOne({Name:"David",Age:24}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6d7dd551299a9f98c9397") }
Display all documents from a collection with the help of find() method −
> db.demo697.find();
This will produce the following output −
{ "_id" : ObjectId("5ea6d7d1551299a9f98c9395"), "Name" : "Chris", "Age" : 21 } { "_id" : ObjectId("5ea6d7d8551299a9f98c9396"), "Name" : "Bob", "Age" : 23 } { "_id" : ObjectId("5ea6d7dd551299a9f98c9397"), "Name" : "David", "Age" : 24 }
Following is the query to get number of records −
> var numberOfRecords= db.demo697.count(); > print("Number of records=",numberOfRecords);
This will produce the following output −
Number of records= 3