How to run raw mongodb commands from pymongo

前端 未结 2 767
轻奢々
轻奢々 2020-12-30 07:08

In a mongo command line I can run

db.my_collection.stats()

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

相关标签:
2条回答
  • 2020-12-30 07:14
    from pymongo import MongoClient
    
    client = MongoClient()
    
    db = client.test_database
    
    print(db.command("collstats", "test_collection"))
    
    0 讨论(0)
  • 2020-12-30 07:28

    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.

    0 讨论(0)
提交回复
热议问题