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

4

13

I can see the statistics from Mongo shell as

db.stats()

or

db.collection_name.stats()

How do I view statistics of a database, or of a collection, from PHP and Python.

EDIT: I have done it in PHP but still cant do it in Python.

Help?

Growl answered 25/7, 2012 at 11:25 Comment(0)
K
20

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
  • Kolivas answered 17/8, 2012 at 23:5 Comment(2)
    Can anyone confirm that this and docs are actually accurate? I'm getting command() missing 1 required positional argument: 'command' no matter what I pass as an argument. Has this been deprecated and not updated in docs?Helotry
    (incase anyone wants in size other than bytes, for which I struggled alot) - for passing scale 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.Flute
    G
    10

    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?

    Growl answered 25/7, 2012 at 13:23 Comment(0)
    A
    1

    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.

    Algorithm answered 30/6, 2015 at 22:13 Comment(0)
    T
    0

    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']);
    }
    
    Telephone answered 25/10, 2017 at 14:47 Comment(0)

    © 2022 - 2024 — McMap. All rights reserved.