您可以使用 命令执行数据库命令() Db
实例上的方法。
可以在文档中指定命令和选项。如要运行命令,请将文档传递给 command()
方法。如要查看数据库命令的完整列表,请参阅服务器手册中的数据库命令部分。
提示
尽可能使用 MongoDB Shell 执行管理任务,而不是 Node.js 驱动程序。
您可以通过将RunCommandOptions
对象传递给command()
方法来指定可选命令行为。 要了解有关支持选项的更多信息,请参阅 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, ... }