Docs Home → Develop Applications → MongoDB Drivers → Node.js
Run a Command
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.
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. You can
also pass a callback method as an
optional third parameter.
Example
Note
This example connects to an instance of MongoDB and uses a sample data database. To learn more about connecting to your MongoDB instance and loading this database, see the Usage Examples guide.
1 const { MongoClient } = require("mongodb"); 2 3 // Replace the uri string with your MongoDB deployment's connection string. 4 const uri = 5 "mongodb+srv://<user>:<password>@<cluster-url>?writeConcern=majority"; 6 7 const client = new MongoClient(uri, { 8 useNewUrlParser: true, 9 useUnifiedTopology: true, 10 }); 11 12 async function run() { 13 try { 14 await client.connect(); 15 16 const db = client.db("sample_mflix"); 17 // find the storage statistics for the "sample_mflix" database using the 'dbStats' command 18 const result = await db.command({ 19 dbStats: 1, 20 }); 21 console.log(result); 22 } finally { 23 await client.close(); 24 } 25 } 26 run().catch(console.dir);
When you run the above command, you should see output similar to the following:
{ db: 'sample_mflix', collections: 6, views: 0, objects: 75620, ... }