Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the count of the number of documents in a Collection Mongodb

Is there a way to list all the collection names and the document count for each collection in a single query?

The one that I could find only gives the count for a particular collection. For example, if Users was a collection then

db.Users.count()

Would give me the count of the number of documents in the collection Users.

like image 296
Vaulstein Avatar asked Aug 10 '15 09:08

Vaulstein


People also ask

How do you count documents in a collection?

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

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.

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().


2 Answers

In the shell all you need to do is this:

db.getCollectionNames().map(function(name) { 
    return { "name": name, "count": db[name].count() } 
})

There is no "command" and there is not "singular" collection query ( it is technically still multiple queries made for each collection, and a "source" query ) to do this since that is not how MongoDB stores the data. But there is a simple programitic method, and this is basically available to all drivers as well.

like image 181
Blakes Seven Avatar answered Oct 14 '22 00:10

Blakes Seven


If you just want to print the numbers and count, then you can use forEach.

db.getCollectionNames().forEach(function(colName){
  print(colName+": "+db.collection(colName).count());
});

If you want to use it for any other operations, then you can use map function.

db.getCollectionNames().map(function(colName){
  return {
    "columnName":colName,
    "count":db.getCollection(colName).count()
  }
});
like image 40
Laxmikant Dange Avatar answered Oct 13 '22 23:10

Laxmikant Dange