Docs Home / Node.js Driver

Run a Database Command运行数据库命令

Overview概述

In this guide, you can learn how to run a database command with the Node.js driver. 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.在本指南中,您可以学习如何使用Node.js驱动程序运行数据库命令。您可以使用数据库命令执行各种管理和诊断任务,例如获取服务器统计信息、初始化副本集或运行聚合管道。

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

Execute a Command执行命令

To run a database command, you must specify the command and any relevant parameters in a document, then pass this 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. You can use this method with any database command.,它将命令响应作为Document类型返回。您可以将此方法与任何数据库命令一起使用。
  • 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.有关数据库命令和相应参数的完整列表,请参阅附加信息部分

Command Options命令选项

You can specify optional command behavior for the command() and runCursorCommand() methods.您可以为command()runCursorCommand()方法指定可选的命令行为。

The command() method accepts a RunCommandOptions object. To learn more about the RunCommandOptions type, see the API documentation.command()方法接受RunCommandOptions对象。要了解有关RunCommandOptions类型的更多信息,请参阅API文档

The runCursorCommand() method accepts a RunCursorCommandOptions object. To learn more about the RunCursorCommandOptions type, see the API documentation.runCursorCommand()方法接受RunCursorCommandOptions对象。要了解有关RunCursorCommandOptions类型的更多信息,请参阅API文档

Starting in version 6.0 of the Node.js driver, you can pass only the following options to the command() method:从Node.js驱动程序的6.0版本开始,您只能将以下选项传递给command()方法:

  • comment
  • enableUtf8Validation
  • raw
  • readPreference
  • session

You can set more options in the document that you pass to the command() method. To learn more about a command and the options that it accepts, locate the command and follow the link on the Database Commands section of the Server manual.您可以在传递给command()方法的文档中设置更多选项。要了解有关命令及其接受的选项的更多信息,请找到该命令并按照服务器手册“数据库命令”部分上的链接进行操作。

The following code shows how to specify a grantRolesToUser command that executes with a majority write concern:以下代码显示了如何指定以majority写入关注执行的grantRolesToUser命令:

const commandDoc = {
grantRolesToUser: "user011",
roles: [ "readWrite" ],
writeConcern: { w: "majority" }
};
const result = await myDB.command(commandDoc);

Note

Read Preference读取首选项

The command() and runCursorCommand() methods ignore the read preference setting you may have set on your Db object. By default, these methods use the primary read preference.command()runCursorCommand()方法忽略您可能在Db对象上设置的读取首选项设置。默认情况下,这些方法使用primary读取首选项。

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

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. To learn more about logical time, see our blog post about the Global Logical Clock.指示操作的逻辑时间。MongoDB使用逻辑时间来排序操作。要了解更多关于逻辑时间的信息,请参阅我们关于全局逻辑时钟的博客文章
$clusterTime

Provides 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命令并迭代结果:

// Connect to the "testDB" database连接到“testDB”数据库
const db = client.db("testDB");

// Run a cursor command to check metadata consistency within the database
const cursor = await db.runCursorCommand({
checkMetadataConsistency: 1,
});
// Iterate through the cursor's results and print the contents
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字段。

Run Command Example: Full File运行命令示例:完整文件

Note

Example Setup示例设置

This example connects to an instance of MongoDB by using a connection URI. To learn more about connecting to your MongoDB instance, see the Connect to MongoDB guide. 此示例通过使用连接URI连接到MongoDB的实例。要了解有关连接到MongoDB实例的更多信息,请参阅连接到MongoDB指南。This example also uses the movies collection in the sample_mflix database included in the Atlas sample datasets. 此示例还使用Atlas示例数据集中包含的sample_mflix数据库中的movies集合。You can load them into your database on the free tier of MongoDB Atlas by following the MongoDB Get Started.您可以按照MongoDB入门指南将它们加载到MongoDB Atlas免费层的数据库中。

Note

No TypeScript Specific Features没有TypeScript特定功能

The following code example uses JavaScript. There are no TypeScript specific features of the driver relevant to this use case.以下代码示例使用JavaScript。驱动程序中没有与此用例相关的TypeScript特定功能。

In the following sample code, we send the dbStats command to request statistics from the sample_mflix database:在以下示例代码中,我们发送dbStats命令以从sample_mflix数据库请求统计信息:

/* Run a database command运行数据库命令 */

import { MongoClient } from "mongodb";

// Replace the uri string with your MongoDB deployment's connection string将uri字符串替换为MongoDB部署的连接字符串
const uri = "<connection string uri>";

const client = new MongoClient(uri);

async function run() {
try {
// Get the "sample_mflix" database获取“sample_mflix”数据库
const db = client.db("sample_mflix");

// Find and print the storage statistics for the "sample_mflix" database using the 'dbStats' command使用“dbStats”命令查找并打印“sample_mflix”数据库的存储统计信息
const result = await db.command({
dbStats: 1,
});
console.log(result);
} finally {
// Close the database connection on completion or error完成或出错时关闭数据库连接
await client.close();
}
}
run().catch(console.dir);

Running the preceding command results in the following output:运行上述命令会得到以下输出:

{
db: 'sample_mflix',
collections: 6,
views: 0,
objects: 75620,
..

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.要了解如何从游标检索数据,请参阅从游标访问数据基本原理页面。