Run a Command

Info With Circle IconCreated with Sketch.Note

If you specify a callback method, command() returns nothing. If you do not specify one, this method returns a Promise that resolves to the result object when it completes. See our guide on Promises and Callbacks for more information, or the API documentation for information on the result object.

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.

Info With Circle IconCreated with Sketch.Note

Use the mongo 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. You can also pass a callback method as an optional third parameter.

Info With Circle IconCreated with Sketch.Note

This example connects to an instance of MongoDB using a connection string. To learn more about connecting to your MongoDB instance, see the connection guide.

1const { MongoClient } = require("mongodb");
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri =
5 "mongodb+srv://<user>:<password>@<cluster-url>?writeConcern=majority";
7const client = new MongoClient(uri);
9async function run() {
10 try {
11 await client.connect();
13 const db = client.db("sample_mflix");
14 // find the storage statistics for the "sample_mflix" database using the 'dbStats' command
15 const result = await db.command({
16 dbStats: 1,
17 });
18 console.log(result);
19 } finally {
20 await client.close();
21 }

When you run the above command, you should see output similar to the following:

db: 'sample_mflix',
collections: 6,
views: 0,
objects: 75620,
Give Feedback