MongoDB shell's db.stats() in php and python

我是研究僧i 提交于 2019-12-04 03:34:09
Sagar Hatekar

This is how you do it in Python if you are using the PyMongo driver:


connection = pymongo.Connection(host = "127.0.0.1", port = 27017)
db = connection["test_db"]
test_collection = db["test_collection"]
db.command("dbstats") # prints database stats for "test_db"
db.command("collstats", "test_collection") # prints collection-level stats for "test_collection" under "test_db".  

References:

  • db.command()
  • MongoDB: how to get db.stats() from API
  • This is how you do it in PHP

    $con= new Mongo()
    
    $stats=$con->dbName->command(array('dbStats' => 1));  // for db.stats()
    
    $stats=$con->dbName->command(array('collStats' => 'collection_name')); // for db.collection_name.stats()
    

    But how to do this in python?

    The easiest way I have found to do this with a Mongoengine model was this:

    import mongoengine
    from models import MyModel
    
    connection = mongoengine.connection.get_connection()
    db = connection[MyModel._get_db().name]
    stats = db.command("collstats", MyModel._get_collection_name())
    

    This should allow transparent changes in the collection and database using mongoengine's config settings.

    This is PHP code to execute dbStats command with new MongoDB driver:

    $mongo = new \MongoDB\Driver\Manager('mongodb://localhost:27017');
    $cmdstats = new \MongoDB\Driver\Command(['dbStats' => 1]);
    $dbstats = $mongo->executeCommand('databaseName', $cmdstats);
    $dbstats->setTypeMap(array(
        'array' => 'array',
        'document' => 'array',
        'root' => 'array'
    ));
    
    // There must be only one item in $dbstats
    
    foreach ($dbstats as $dbs)
    {
        echo($dbs['dataSize']);
    }
    
    易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
    该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!