Docs Menu

Docs HomeMongoDB Shell

Run Commands

On this page

  • Switch Databases
  • Terminate a Running Command
  • Command Exceptions
  • Clear the mongosh Console

To run commands in mongosh, you must first connect to a MongoDB deployment.

To display the database you are using, type db:


The operation should return test, which is the default database.

To switch databases, issue the use <db> helper, as in the following example:

use <database>

To access a different database from the current database without switching your current database context, see the db.getSiblingDB() method.

To list the databases available to the user, use the helper show dbs.

To create a new database, issue the use <db> command with the database that you would like to create. For example, the following commands create both the database myNewDatabase and the collection myCollection using the insertOne() operation:

use myNewDatabase
db.myCollection.insertOne( { x: 1 } );

If a collection does not exist, MongoDB creates the collection when you first store data for that collection.

To terminate a running command or query in mongosh, press Ctrl + C.

When you enter Ctrl + C, mongosh:

  • interrupts the active command,

  • tries to terminate the ongoing, server-side operation, and

  • returns a command prompt.

If mongosh cannot cleanly terminate the running process, it issues a warning.


Pressing Ctrl + C in mongosh does not terminate asynchronous code. Asynchronous operations such as setTimeout or operations like fs.readFile continue to run.

There is no way to terminate asynchronous code in mongosh. This is the same behavior as in the Node.js REPL.

Pressing Ctrl + C once will not exit mongosh, press Ctrl + C twice to exit mongosh.

In scenarios where the output of a command includes { ok: 0 }, mongosh throws an exception and does not return the raw output from the server.


In the legacy mongo shell, when a command's output included { ok: 0 }, the behavior differs between commands. mongosh provides consistent behavior by always throwing an exception in these scenarios.

The cls command clears the console. You can also clear the console with Ctrl + L and console.clear().

←  Configure Free MonitoringPerform CRUD Operations →
Share Feedback
© 2023 MongoDB, Inc.


  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2023 MongoDB, Inc.