Run a Command运行命令
You can run all raw database operations using the db.command()可以使用 method. Call the
command()
method with your command object on an instance of a database for diagnostic and administrative tasks such as fetching server stats or initializing a replica set.db.command()
方法运行所有原始数据库操作。在数据库实例上使用命令对象调用
command()
方法,以执行诊断和管理任务,例如获取服务器统计信息或初始化副本集。
Use the MongoDB Shell for administrative tasks instead of the Node.js driver whenever possible.尽可能使用MongoDB Shell执行管理任务,而不是使用Node.js驱动程序。
You can specify additional options in the 您可以在options
object passed in the second parameter of the command()
method. command()
方法的第二个参数中传递的options
对象中指定其他选项。For more information on the options you can pass, see the db.command() API documentation.有关可以传递的选项的更多信息,请参阅db.command()
API文档。
Example实例
You can use this example to connect to an instance of MongoDB and interact with a database that contains sample data. 您可以使用此示例连接到MongoDB的实例,并与包含示例数据的数据库进行交互。To learn more about connecting to your MongoDB instance and loading a sample dataset, see the Usage Examples guide.要了解有关连接到MongoDB实例和加载示例数据集的更多信息,请参阅用法实例指南。
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 {
const db = client.db("sample_mflix");
//find 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 {
await client.close();
}
}
run().catch(console.dir);
Identical Code Snippets相同的代码段
The JavaScript and TypeScript code snippets above are identical. 上面的JavaScript和TypeScript代码片段是相同的。There are no TypeScript specific features of the driver relevant to this use case.驱动程序没有与此用例相关的TypeScript特定功能。
When you run the preceding command, you should see the following output:当您运行前面的命令时,您应该会看到以下输出:
{
db: 'sample_mflix',
collections: 6,
views: 0,
objects: 75620,
...
}