Skip to content

Instantly share code, notes, and snippets.

@luizbraga
Created October 4, 2017 14:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save luizbraga/f386760d8c4fe138508a912e1f8b1fab to your computer and use it in GitHub Desktop.
Save luizbraga/f386760d8c4fe138508a912e1f8b1fab to your computer and use it in GitHub Desktop.
List collections, size and count of documents on MongoDB
from pymongo import MongoClient
MONGO_URI = ''
DATABASE_NAME = ''
client = MongoClient(MONGO_URI)
db = client[DATABASE_NAME]
collections = db.collection_names()
def readable_size(file_size):
index_unit = 0
units = ['byte', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
while (file_size > 1024):
file_size = file_size / 1024;
index_unit += 1
return "{0:.2f} {unit}".format(round(file_size, 2), unit=units[index_unit])
stats = {}
for collection in collections:
col_stats = db.command('collstats', collection)
stats[collection] = {
'count': col_stats['count'],
'size': readable_size(col_stats['size'])
}
print collection + ' Collection size: {size} / Documets count: {count}'.format(
size=stats[collection]['size'],
count=stats[collection]['count'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment