Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the number of documents in a mongodb collection

Tags:

mongodb

I would like to know how to count the number of documents in a collection. I tried the follow

var value = collection.count(); && var value = collection.find().count() && var value = collection.find().dataSize() 

I always get method undefined.

Can you let me know what is the method to use to find the total documents in a collection.

like image 560
Tinniam V. Ganesh Avatar asked Nov 03 '14 17:11

Tinniam V. Ganesh


People also ask

Which function in MongoDB is used to count the records?

MongoDB Count Method is used to count the number of documents matching specified criteria. This method does not actually perform the find() operation, but rather returns a numerical count of the documents that meet the selection criteria.

How do I find the number of data in MongoDB?

count() The count() method counts the number of documents that match the selection criteria. It returns the number of documents that match the selection criteria. It takes two arguments first one is the selection criteria and the other is optional.

How do I count documents in MongoDB Python?

Python3. Method 2: count_documents() Alternatively, you can also use count_documents() function in pymongo to count the number of documents present in the collection. Example: Retrieves the documents present in the collection and the count of the documents using count_documents().

How many files are in a MongoDB collection?

If you specify a maximum number of documents for a capped collection using the max parameter to create, the limit must be less than 2^32 documents. If you do not specify a maximum number of documents when creating a capped collection, there is no limit on the number of documents.


2 Answers

Traverse to the database where your collection resides using the command:

use databasename; 

Then invoke the count() function on the collection in the database.

var value = db.collection.count(); 

and then print(value) or simply value, would give you the count of documents in the collection named collection.

Refer: http://docs.mongodb.org/v2.2/tutorial/getting-started-with-the-mongo-shell/

like image 135
BatScream Avatar answered Oct 07 '22 00:10

BatScream


If you want the number of documents in a collection, then use the count method, which returns a Promise. Here's an example:

let coll = db.collection('collection_name'); coll.count().then((count) => {     console.log(count); }); 

This assumes you're using Mongo 3.

Edit: In version 4.0.3, count is deprecated. use countDocument to achieve the goal.

like image 38
Rahul Avatar answered Oct 07 '22 00:10

Rahul