Docs HomeNode.js

Run a Command运行命令

Overview概述

In this guide, you can learn how to run a database command with the Node.js driver. 在本指南中,您可以学习如何使用Node.js驱动程序运行数据库命令。You can use database commands to perform a variety of administrative and diagnostic tasks, such as fetching server statistics, initializing a replica set, or running an aggregation pipeline.您可以使用数据库命令执行各种管理和诊断任务,例如获取服务器统计信息、初始化副本集或运行聚合管道。

Important

Prefer Driver Methods to Database Commands首选驱动程序方法而非数据库命令

The driver provides wrapper methods for many database commands. 驱动程序为许多数据库命令提供包装方法。We recommend using driver methods instead of executing database commands when possible.我们建议尽可能使用驱动程序方法,而不是执行数据库命令。

To perform administrative tasks, use the MongoDB Shell instead of the Node.js driver. 要执行管理任务,请使用MongoDB Shell而不是Node.js驱动程序。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.在shell内部调用db.runCommand()方法是发出数据库命令的首选方法,因为它在shell和驱动程序之间提供了一致的接口。

Execute a Command执行命令

To run a database command, you must specify the command and any relevant parameters in a command document, then pass the command document to a command execution method. 若要运行数据库命令,必须在命令文档中指定该命令和任何相关参数,然后将命令文档传递给命令执行方法。The Node.js driver provides the following methods to run database commands:Node.js驱动程序提供了以下方法来运行数据库命令:

  • command(), which returns the command response as a Document type. ,它将命令响应作为Document类型返回。You can use this method with any database command.您可以将此方法与任何数据库命令一起使用。
  • runCursorCommand(), which returns the command response as an iterable RunCommandCursor type. ,它将命令响应作为可迭代的RunCommandCursor类型返回。You can use this method only if your database command returns multiple result documents.只有当数据库命令返回多个结果文档时,才能使用此方法。

The following code shows how you can use the command() method to run the hello command, which returns information about the current member's role in the replica set, on a database:以下代码显示了如何使用command()方法在数据库上运行hello命令,该命令返回有关当前成员在副本集中角色的信息:

const result = await myDB.command({ hello: 1 });

For a full list of database commands and corresponding parameters, see the Additional Information section.有关数据库命令和相应参数的完整列表,请参阅附加信息部分。

Note

Read Preference读取首选项

command() and runCursorCommand() do not obey the read preference you may have set on your Db object elsewhere in your code. command()runCursorCommand()不遵守您可能在代码其他地方对Db对象设置的读取首选项。By default, these methods use the primary read preference.默认情况下,这些方法使用primary读取首选项。

You can set a read preference for command execution by passing an options object to either method. 您可以通过将选项对象传递给任一方法来设置命令执行的读取首选项。The command() method takes a RunCommandOptions object, and the runCursorCommand() method takes a RunCursorCommandOptions object.command()方法采用RunCommandOptions对象,而runCursorCommand()方法则采用RunCursorCommandOptions对象。

The following code shows how to specify a read preference and pass it as an option to the command() method:以下代码显示了如何指定读取首选项并将其作为选项传递给command()方法:

const commandOptions = { readPreference: "nearest" };
const result = await myDB.command(commandDoc, commandOptions);

For more information on read preference options, see Read Preference in the Server manual.有关读取首选项的详细信息,请参阅服务器手册中的读取首选项

Response回答

Each method returns a Document object or a cursor that contains the response from the database after the command has been executed. 每个方法都返回一个Document对象或一个游标,其中包含执行命令后数据库中的响应。Each database command performs a different function, so the response content can vary across commands. 每个数据库命令执行不同的功能,因此响应内容可能因命令而异。However, every response contains documents with the following fields:但是,每个响应都包含具有以下字段的文档:

Field字段Description描述
<command result>Provides fields specific to the database command. 提供特定于数据库命令的字段。For example, count returns the n field and explain returns the queryPlanner field.例如,count返回n字段,explain返回queryPlanner字段。
okIndicates whether the command has succeeded (1) or failed (0).指示命令是成功(1)还是失败(0)。
operationTimeIndicates the logical time of the operation. 指示操作的逻辑时间。MongoDB uses the logical time to order operations. MongoDB使用逻辑时间来订购操作。
Tip

See also: 另请参阅:

To learn more about logical time, see our blog post about the Global Logical Clock.要了解更多关于逻辑时间的信息,请参阅关于全局逻辑时钟的博客文章
$clusterTimeProvides a document that returns the signed cluster time. 提供一个返回已签名群集时间的文档。Cluster time is a logical time used for ordering of operations.集群时间是用于操作排序的逻辑时间。
The document contains the following fields:该文档包含以下字段:
  • clusterTime, which is the timestamp of the highest known cluster time for the member.,这是该成员已知的最高集群时间的时间戳。
  • signature, which is a document that contains the hash of the cluster time and the ID of the key used to sign the cluster time.,是一个文档,包含集群时间的哈希和用于对集群时间进行签名的键的ID。

Example实例

The following code shows how you can use the runCursorCommand() method to run the checkMetadataConsistency command on the testDB database and iterate through the results:以下代码显示了如何使用runCursorCommand()方法在testDB数据库上运行checkMetadataConsistency命令并迭代结果:

const db = client.db("testDB");
const cursor = await db.runCursorCommand({
checkMetadataConsistency: 1,
});
for await (const doc of cursor) {
console.log(doc);
}

Output输出

The output contains the contents of the cursor object. The documents describe any metadata inconsistencies in the database:输出包含游标对象的内容。这些文档描述了数据库中的任何元数据不一致:

{
type: ...,
description: ...,
details: {
namespace: ...,
info: ...
}
}
{
type: ...,
description: ...,
details: {
namespace: ...,
collectionUUID: ...,
maxKeyObj: ...,
...
}
}
Note

If you store the command response in a cursor, you see only the command result documents when you access the contents of the cursor. 如果将命令响应存储在游标中,则在访问游标内容时只能看到命令结果文档。You won't see the ok, operationTime, and $clusterTime fields.您将看不到okoperationTime$clusterTime字段。

Additional Information附加信息

For more information about the concepts in this guide, see the following documentation:有关本指南中概念的更多信息,请参阅以下文档:

To learn how to retrieve data from a cursor, see the Access Data From a Cursor fundamentals page.要了解如何从游标检索数据,请参阅从游标访问数据的基本页面。