运行命令
您可以通过使用command() 方法在Db
实例上执行数据库命令。
您可以在文档中指定一个命令和选项。要运行命令,请将此文档传递给 command()
方法。要查看数据库命令的完整列表,请参阅服务器手册中的 数据库命令。
提示
尽可能使用 MongoDB Shell 来执行管理任务,而不是 Node.js 驱动程序。
您可以通过向 command()
方法传递一个 RunCommandOptions
对象来指定可选的命令行为。要了解更多关于受支持选项的信息,请参阅 Db.command() API 文档
示例
注意
您可以使用此示例连接到 MongoDB 实例并交互具有样本数据的数据库。要了解有关连接到您的 MongoDB 实例和加载数据集的更多信息,请参阅使用示例指南.
1 /* Run a database command */ 2 3 import { MongoClient } from "mongodb"; 4 5 // Replace the uri string with your MongoDB deployment's connection string 6 const uri = "<connection string uri>"; 7 8 const client = new MongoClient(uri); 9 10 async function run() { 11 try { 12 // Get the "sample_mflix" database 13 const db = client.db("sample_mflix"); 14 15 // Find and print the storage statistics for the "sample_mflix" database using the 'dbStats' command 16 const result = await db.command({ 17 dbStats: 1, 18 }); 19 console.log(result); 20 } finally { 21 // Close the database connection on completion or error 22 await client.close(); 23 } 24 } 25 run().catch(console.dir);
1 /* Run a database command */ 2 3 import { MongoClient } from "mongodb"; 4 5 // Replace the uri string with your MongoDB deployment's connection string 6 const uri = "<connection string uri>"; 7 8 const client = new MongoClient(uri); 9 10 async function run() { 11 try { 12 // Get the "sample_mflix" database 13 const db = client.db("sample_mflix"); 14 15 // Find and print the storage statistics for the "sample_mflix" database using the 'dbStats' command 16 const result = await db.command({ 17 dbStats: 1, 18 }); 19 console.log(result); 20 } finally { 21 // Close the database connection on completion or error 22 await client.close(); 23 } 24 } 25 run().catch(console.dir);
注意
相同的代码片段
上面的 JavaScript 和 TypeScript 代码片段是相同的。此用例中没有与 TypeScript 相关的特定功能。
运行前面的命令,您将看到以下输出
{ db: 'sample_mflix', collections: 6, views: 0, objects: 75620, ... }