Docs Menu
Docs Home
/ / /
Node.js Driver
/

Run a Command

You can execute database commands by using the command() method on a Db instance.

You can specify a command and options in a document. To run the command, pass this document to the command() method. To see a full list of database commands, see Database Commands in the Server manual.

Tip

Use the MongoDB Shell for administrative tasks instead of the Node.js driver whenever possible.

You can specify optional command behavior by passing a RunCommandOptions object to the command() method. To learn more about the supported options, see the Db.command() API documentation.

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/* Run a database command */
2
3import { MongoClient } from "mongodb";
4
5// Replace the uri string with your MongoDB deployment's connection string
6const uri = "<connection string uri>";
7
8const client = new MongoClient(uri);
9
10async 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}
25run().catch(console.dir);
1/* Run a database command */
2
3import { MongoClient } from "mongodb";
4
5// Replace the uri string with your MongoDB deployment's connection string
6const uri = "<connection string uri>";
7
8const client = new MongoClient(uri);
9
10async 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}
25run().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.

Running the preceding command, you see the following output:

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

Back

Distinct Field Values