MongoShell (Mongosh) Commands

  • Read
  • Discuss

Show all Databases

To show all databases, use the show dbs command 

Syntax:

show dbs;

Switch Database

To switch databases, use the use command 

Syntax:

use <database_name>;

Create a New Database 

To create a new database, issue the use <db> command with the database that you would like to create.

Syntax:

use <database_name>;

If a database does not exist, MongoDB creates the database when you first use that database

INSERT: 

Create or insert a new document into a collection. If the collection does not exist, a new collection will be created.

db.collection.insertOne() inserts one document into a collection.

db.collection.insertMany() inserts multiple documents into a collection at once.

Syntax:

db.collection.insertOne();

FIND:

 This queries a collection of documents and displays all documents present within a collection. Query filters and criteria can be applied to find specific documents.

Syntax:

db.collection.find();

UPDATE:

This modifies existing documents in a collection.

db.collection.updateOne()

db.collection.updateMany()

db.collection.replaceOne()

Syntax:

db.collection.update(<query/condition>,<update>);

DELETE:

Deletes documents from a collection.

The db.collection.delete() method can have one of two syntaxes. 

The deleteMany() method 

The deleteOne() method

Syntax:

db.collection.deleteOne(<query>);

Clear the mongosh Console

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

Leave a Reply

Scroll to Top