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
.
var value = db. collection. count(); and then print(value) or simply value , would give you the count of documents in the collection named 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.
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().
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.
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()
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With