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.
Note
Use the MongoDB Shell for administrative tasks instead of the Node.js driver whenever possible.
You can specify additional options in the options
object passed in
the second parameter of the command()
method. For more information
on the options you can pass, see the
db.command() API documentation.
Example
Note
You can use this example to connect to an instance of MongoDB and interact with a database that contains sample data. To learn more about connecting to your MongoDB instance and loading a sample dataset, see the Usage Examples guide.
1 import { MongoClient } from "mongodb"; 2 3 // Replace the uri string with your MongoDB deployment's connection string. 4 const uri = "<connection string uri>"; 5 6 const client = new MongoClient(uri); 7 8 async function run() { 9 try { 10 const db = client.db("sample_mflix"); 11 // find the storage statistics for the "sample_mflix" database using the 'dbStats' command 12 const result = await db.command({ 13 dbStats: 1, 14 }); 15 console.log(result); 16 } finally { 17 await client.close(); 18 } 19 } 20 run().catch(console.dir);
1 import { MongoClient } from "mongodb"; 2 3 // Replace the uri string with your MongoDB deployment's connection string. 4 const uri = "<connection string uri>"; 5 6 const client = new MongoClient(uri); 7 8 async function run() { 9 try { 10 const db = client.db("sample_mflix"); 11 // find the storage statistics for the "sample_mflix" database using the 'dbStats' command 12 const result = await db.command({ 13 dbStats: 1, 14 }); 15 console.log(result); 16 } finally { 17 await client.close(); 18 } 19 } 20 run().catch(console.dir);
Note
Identical Code Snippets
The JavaScript and TypeScript code snippets above are identical. There are no TypeScript specific features of the driver relevant to this use case.
When you run the preceding command, you should see the following output:
{ db: 'sample_mflix', collections: 6, views: 0, objects: 75620, ... }