15

In a mongo command line I can run

db.my_collection.stats()

I need to get my collections stats from Python so I tried

from pymongo import MongoClient

client = MongoClient()
db = client.test_database

collection = db.test_collection

collection.stats()

But I get

TypeError: 'Collection' object is not callable. 
If you meant to call the 'stats' method on a 'Collection' object it is failing because no such method exists.

This is because pymongo does not support this method. How do I send raw mongoDB commands to mongo through Python?

jbihan
  • 3,053
  • 2
  • 24
  • 34
Dr Manhattan
  • 13,537
  • 6
  • 45
  • 41

2 Answers2

17
from pymongo import MongoClient

client = MongoClient()

db = client.test_database

print(db.command("collstats", "test_collection"))
radtek
  • 34,210
  • 11
  • 144
  • 111
Chris Nilsson
  • 488
  • 6
  • 11
  • for passing scale (since all sizes are given in bytes) you can do this: `db.command("collstats", "test_collection", scale=1024*1024)`. This will convert into MB. You can also also change it up as you like for KB, GB, etc. However, `avgObjSize` will always be in `bytes`. – raghavsikaria Jun 30 '22 at 11:47
4

Approach 1 with PyMongo:

client = pymongo.MongoClient(host = "127.0.0.1", port = 27017)
db = client.test_database
db.command("dbstats") # prints database stats for "test_db"
db.command("collstats", "test_collection") # prints collection-level stats

This can be done with this approach in Django.

    from django.db import connections

    database_wrapper = connections['my_db_alias']
    eggs_collection = database_wrapper.get_collection('eggs')
    eggs_collection.find_and_modify(...)

From django-mongodb-engine docs:

django.db.connections is a dictionary-like object that holds all database connections – that is, for MongoDB databases, django_mongodb_engine.base.DatabaseWrapper instances.

These instances can be used to get the PyMongo-level Connection, Database and Collection objects.

wolendranh
  • 4,202
  • 1
  • 28
  • 37