MongoDB shell 的 php 和 python 中的 db.stats()

作者:编程家 分类: mongodb 时间:2025-04-30

使用 MongoDB shell 的 php 和 python 中的 db.stats() 函数可以方便地获取数据库的统计信息。该函数返回一个包含数据库各项统计数据的对象,可以用于了解数据库的整体情况和性能指标。本文将分别介绍如何在 php 和 python 中使用 db.stats() 函数,并提供相应的代码示例。

php 中使用 db.stats()

在 php 中,可以使用 MongoDB 的官方驱动程序来连接数据库并执行 db.stats() 函数。下面是一个示例代码:

php

// 连接 MongoDB

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

// 创建查询命令

$command = new MongoDB\Driver\Command(['dbstats' => 1]);

// 执行命令

$result = $manager->executeCommand("mydb", $command);

// 获取结果

$stats = current($result->toArray());

// 输出统计信息

echo "数据库名称:" . $stats->db . "\n";

echo "数据库大小:" . $stats->dataSize . "\n";

echo "集合数量:" . $stats->collections . "\n";

echo "文档数量:" . $stats->documents . "\n";

echo "索引数量:" . $stats->indexes . "\n";

?>

以上代码首先创建一个 MongoDB\Driver\Manager 对象来连接 MongoDB 数据库,然后使用 MongoDB\Driver\Command 类创建一个查询命令,其中指定了要执行的 db.stats() 函数。接下来,通过 executeCommand() 方法执行命令,并使用 toArray() 方法将结果转换为数组。最后,从结果数组中获取统计信息,并输出到屏幕上。

python 中使用 db.stats()

在 python 中,可以使用 pymongo 库来连接 MongoDB 并执行 db.stats() 函数。下面是一个示例代码:

python

from pymongo import MongoClient

# 连接 MongoDB

client = MongoClient('mongodb://localhost:27017')

# 获取数据库对象

db = client['mydb']

# 获取统计信息

stats = db.command('dbstats')

# 输出统计信息

print('数据库名称:', stats['db'])

print('数据库大小:', stats['dataSize'])

print('集合数量:', stats['collections'])

print('文档数量:', stats['documents'])

print('索引数量:', stats['indexes'])

以上代码首先使用 MongoClient 类连接 MongoDB 数据库,并指定了连接的 URL。接下来,通过 client 的索引操作符获取指定名称的数据库对象。然后,使用 db.command() 方法执行 db.stats() 命令,并将结果保存在 stats 变量中。最后,从 stats 字典中获取统计信息,并输出到屏幕上。

通过以上代码示例,我们可以看到,在 php 和 python 中使用 MongoDB shell 的 db.stats() 函数可以轻松获取数据库的统计信息。无论是在 php 还是 python 中,只需连接数据库并执行相应的命令,即可获取到数据库的各项指标。这些统计数据对于了解数据库的整体情况和性能分析非常有帮助。

案例代码

php 中使用 db.stats() 的案例代码:

php

// 连接 MongoDB

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

// 创建查询命令

$command = new MongoDB\Driver\Command(['dbstats' => 1]);

// 执行命令

$result = $manager->executeCommand("mydb", $command);

// 获取结果

$stats = current($result->toArray());

// 输出统计信息

echo "数据库名称:" . $stats->db . "\n";

echo "数据库大小:" . $stats->dataSize . "\n";

echo "集合数量:" . $stats->collections . "\n";

echo "文档数量:" . $stats->documents . "\n";

echo "索引数量:" . $stats->indexes . "\n";

?>

python 中使用 db.stats() 的案例代码:

python

from pymongo import MongoClient

# 连接 MongoDB

client = MongoClient('mongodb://localhost:27017')

# 获取数据库对象

db = client['mydb']

# 获取统计信息

stats = db.command('dbstats')

# 输出统计信息

print('数据库名称:', stats['db'])

print('数据库大小:', stats['dataSize'])

print('集合数量:', stats['collections'])

print('文档数量:', stats['documents'])

print('索引数量:', stats['indexes'])

通过以上案例代码,可以在 php 和 python 中使用 db.stats() 函数获取 MongoDB 数据库的统计信息,并进行相应的处理和分析。这些统计数据对于数据库管理和性能优化都非常重要,并且可以根据实际需求进行定制化的统计和分析。