Skip to content

Instantly share code, notes, and snippets.

@mostafaasadi
Last active April 8, 2018 22:55
Show Gist options
  • Save mostafaasadi/171e2f1eb821ec4a08fe5101b7ff89f9 to your computer and use it in GitHub Desktop.
Save mostafaasadi/171e2f1eb821ec4a08fe5101b7ff89f9 to your computer and use it in GitHub Desktop.
A simple script to count all documents in all mongo databases
from pymongo import MongoClient
client = MongoClient()
cot = 0
size = 0
db_list = client.database_names()
db_list.sort()
# forked from persepolis download manager
def humanReadbleSize(size):
labels = ['KiB', 'MiB', 'GiB', 'TiB']
i = -1
if size < 1024:
return str(size) + ' B'
while size >= 1024:
i += 1
size = size / 1024
p = 2 if i > 1 else None
return str(round(size, p)) + ' ' + labels[i]
for i in db_list:
db = client[i]
col = db.collection_names(include_system_collections=False)
b = db.command("dbstats")
res1 = '\t' + b['db'] + '\t\t' + str(b['objects']) + '\t\t' + \
humanReadbleSize(b['fileSize'])
cot += b['objects']
size += b['fileSize']
print(res1)
print('\n\t〽️ ' + str(cot))
print('\t📊 ' + humanReadbleSize(size))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment