【问题标题】:MongoDB shell's db.stats() in php and pythonMongoDB shell 在 php 和 python 中的 db.stats()
【发布时间】:2012-07-25 11:25:12
【问题描述】:

我可以看到来自 Mongo shell 的统计数据

db.stats()

db.collection_name.stats()

如何通过 PHP 和 Python 查看数据库或集合的统计信息。

编辑: 我已经用 PHP 完成了,但仍然无法用 Python 完成。

帮助?

【问题讨论】:

    标签: python php mongodb pymongo mongodb-php


    【解决方案1】:

    如果您使用PyMongo 驱动程序,这就是您在Python 中的操作方式:

    
    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".  
    

    参考资料:

  • db.command()
  • MongoDB: how to get db.stats() from API
  • 【讨论】:

    • 任何人都可以确认这和文档实际上是准确的吗?无论我作为论点传递什么,我都会得到command() missing 1 required positional argument: 'command'。这是否已被弃用且未在文档中更新?
    【解决方案2】:

    这就是你在 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()
    

    但是如何在 python 中做到这一点?

    【讨论】:

      【解决方案3】:

      我发现使用 Mongoengine 模型执行此操作的最简单方法是:

      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())
      

      这应该允许使用 mongoengine 的配置设置对集合和数据库进行透明更改。

      【讨论】:

        【解决方案4】:

        这是用新的MongoDB驱动程序执行dbStats命令的PHP代码:

        $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']);
        }
        

        【讨论】:

          猜你喜欢
          • 2012-02-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-11-18
          • 2014-05-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多