How to run raw mongodb commands from pymongo

At the mongo command line mongo I can run

 db.my_collection.stats() 

I need to get statistics of my collections 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 to send mongoDB source commands to mongo via Python ?

+7
source share
2 answers
 from pymongo import MongoClient client = MongoClient() db = client.test_database print(db.command("collstats", "test_collection")) 
+11
source

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 using 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 the django-mongodb-engine documentation:

django.db.connections is an object dictionary that contains all database connections, that is, for MongoDB databases, django_mongodb_engine.base.DatabaseWrapper instances.

These instances can be used to obtain connection objects, a database, and a PyMongo-level collection.

+2
source

Source: https://habr.com/ru/post/1208365/


All Articles