对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

运行命令

在本指南中,您可以学习如何使用C++驱动程序运行数据库命令。您可以使用数据库命令执行各种管理和诊断任务,例如获取服务器统计信息、初始化副本集或运行聚合管道。

重要

首选驱动程序方法而非数据库命令

驱动程序为许多数据库命令提供了封装方法。我们建议尽可能使用驱动程序方法,而不是执行数据库命令。

To perform administrative tasks, use the MongoDB Shell instead of the C++ driver. Calling the db.runCommand() method inside the shell is the preferred method to issue database commands, as it provides a consistent interface between the shell and drivers.

要运行数据库命令,请在 mongocxx::database实例上调用 run_command() 执行方法,并传入指定该命令和所有相关参数的文档。 该方法会以 bsoncxx::document::value对象的形式返回该命令的结果。

You can use the run_command() method with any database command. For a full list of database commands and corresponding parameters, see Database Commands in the MongoDB Server manual.

以下示例展示如何使用 run_command() 方法在数据库上运行hello 命令,该命令会返回有关副本集集中当前成员角色的信息:

auto db = client["my_database"];
auto command = make_document(kvp("hello" , 1));
auto result = db.run_command(command.view());
std::cout << bsoncxx::to_json(result) << std::endl;

To customize command execution behavior, you can set options in the command document that you pass to the run_command() method. To learn more about a command and the options that it accepts, locate the command and follow the corresponding link on the Database Commands page in the MongoDB Server manual.

示例,您可以通过在命令文档中将 showPrivileges 选项设置为 true,指示 connectionStatus 命令返回当前经过身份验证的用户拥有的完整权限设立:

auto db = client["my_database"];
auto command = make_document(kvp("connectionStatus" , 1), kvp("showPrivileges", true));
auto result = db.run_command(command.view());
std::cout << bsoncxx::to_json(result) << std::endl;

执行命令后,run_command() 方法会返回一个 bsoncxx::document::value对象,其中包含数据库的响应。 每个数据库命令执行不同的功能,因此响应内容可能因命令而异。 但是,每个响应都包含具有以下字段的文档:

字段
说明

<command result>

提供特定于数据库命令的字段。例如, count返回n字段, explain返回queryPlanner字段。

ok

表明命令是成功(1)还是失败(0)。

operationTime

指示操作的逻辑时间。 MongoDB 使用逻辑时间对操作进行排序。

$clusterTime

提供返回签名集群时间的文档。 集群时间是用于操作排序的逻辑时间。

该文档包含以下字段:

  • clusterTime,这是节点的已知最高集群时间的时间戳。

  • signature,这是一个文档,其中包含集群时间的哈希值以及用于对集群时间进行签名的密钥的 ID。

有关本指南中概念的更多信息,请参阅以下文档:

要进一步了解本指南所讨论的方法或类型,请参阅以下 API 文档: