MongoDB provides an interactive JavaScript interface called the mongo shell that you can use to connect to a running MongoDB instance from your command-line terminal.

The mongo shell can be used to query and update data as well as to perform administrative tasks. It is already included as part of the MongoDB installation package, so you don't need to install anything.

Note that this article assumes that MongoDB is already installed and running on your machine. If you have not installed MongoDB yet, look at these macOS and Ubuntu installation instructions.

Starting the mongo shell

To start the mongo shell without any command-line options, you use the mongo command:

$ mongo

It will launch the mongo shell and connect to a MongoDB instance running on the localhost with default port 27017:

MongoDB shell version v4.4.1
connecting to: mongodb://
Implicit session: session { "id" : UUID("b52d0db7-f3eb-4674-b1a7-4a774d704a3a") }
MongoDB server version: 4.4.1
The server generated these startup warnings when booting: 
        2020-12-06T16:07:11.633+05:00: ***** SERVER RESTARTED *****
        2020-12-06T16:07:12.718+05:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
        Enable MongoDB's free cloud-based monitoring service, which will then receive and display
        metrics about your deployment (disk utilization, CPU, operation statistics, etc).

        The monitoring data will be available on a MongoDB website with a unique URL accessible to you
        and anyone you share the URL with. MongoDB may use this information to make product
        improvements and to suggest MongoDB products and deployment options to you.

        To enable free monitoring, run the following command: db.enableFreeMonitoring()
        To permanently disable this reminder, run the following command: db.disableFreeMonitoring()

To explicitly specify the port, use the --port command-line option. For example, to connect to a MongoDB instance running on localhost with a non-default port 88657:

$ mongo --port 88657

Working with the mongo shell

Once the mongo shell is started, you can now type any command that it understands.

Display all databases

To display the currently active database, use the db command:

> db

To list all the available databases, use the show dbs command:

> show dbs
admin      0.000GB
config     0.000GB
local      0.000GB

To switch to any database, type use <db>:

> use local
switched to db local

Create a database

In MongoDB, there is no CREATE SCHEMA statement like the one you might have used before in MySQL.

To create a new database in MongoDB, you simply switch to a non-existent database, and then insert data into it:

> use hotel
switched to db hotel

However, the database is not actually created until you insert data into it. You can confirm it by typing show dbs:

> show dbs
admin      0.000GB
config     0.000GB
local      0.000GB

As you can see above, the hotel database is not listed among available databases, just because it doesn't include any collection yet.

Create a collection

In MongoDB, collections are like tables in a relational database. Collections are typically used to group the related documents. For example, you could create a collection called users to group all users.

You can create a new collection on the current database by using the db.createCollection() command. It accepts two arguments: the name of the collection and an optional object that you want to insert:

> db.createCollection('foods')
{ "ok" : 1 }

You could also create a collection on the fly by inserting a new document to a non-existent collection with the insert() method:

> db.foods.insert({ name: 'Pizza 🍕' })
WriteResult({ "nInserted" : 1 })

To list all the available collections in the current database:

> show collections

Once the first collection is created, you should see the hotel database listed among all available databases:

> show dbs
admin      0.000GB
config     0.000GB
hotel      0.000GB
local      0.000GB

Create a document

MongoDB provides the following three methods for inserting documents into a database:

  • insert()
  • insertOne()
  • insertMany()

The insert() method inserts one or more documents into a collection:

> db.foods.insert({ name: 'Cake 🎂' })
WriteResult({ "nInserted" : 1 })

# Insert multiple documents
> db.foods.insert([ { name: 'Burger 🍔' }, { name: 'Cookie 🍪' } ])
	"writeErrors" : [ ],
	"writeConcernErrors" : [ ],
	"nInserted" : 2,
	"nUpserted" : 0,
	"nMatched" : 0,
	"nModified" : 0,
	"nRemoved" : 0,
	"upserted" : [ ]

The insertOne() method is just like insert() but it can only be used to insert one document into a collection:

> db.foods.insertOne({ name: 'Apple 🍎' })
	"acknowledged" : true,
	"insertedId" : ObjectId("5fce1b8eebb8a835319c0adc")

The insertMany() method, as the name suggests, can be used to insert multiple documents at once:

> db.foods.insertMany([ { name: 'Orange 🍊' }, { name: 'Cheese 🧀' } ])
	"acknowledged" : true,
	"insertedIds" : [

List documents

To list all documents stored in a collection, use the find() method:

> db.foods.find()
{ "_id" : ObjectId("5fce1b62ebb8a835319c0ad8"), "name" : "Pizza 🍕" }
{ "_id" : ObjectId("5fce1b71ebb8a835319c0ad9"), "name" : "Cake 🎂" }
{ "_id" : ObjectId("5fce1b7debb8a835319c0ada"), "name" : "Burger 🍔" }
{ "_id" : ObjectId("5fce1b7debb8a835319c0adb"), "name" : "Cookie 🍪" }
{ "_id" : ObjectId("5fce1b8eebb8a835319c0adc"), "name" : "Apple 🍎" }
{ "_id" : ObjectId("5fce1bacebb8a835319c0add"), "name" : "Orange 🍊" }
{ "_id" : ObjectId("5fce1bacebb8a835319c0ade"), "name" : "Cheese 🧀" }

As you can see above, an additional _id attribute was added to each document we inserted. This is the unique ID automatically generated by MongoDB for us.

You can also pass an object as a parameter to find() to filter out results:

> db.foods.find({ name: 'Burger 🍔' })
{ "_id" : ObjectId("5fce1b7debb8a835319c0ada"), "name" : "Burger 🍔" }

Update a document

To update an existing document in MongoDB, you can use either use the update() method or the save() method.

The update() method updates values in one or more documents, while the save() method replaces the existing document with the object passed as a parameter.

Here is an example of the update() method:

# Fetch existing document
> db.foods.find({ _id: ObjectId('5fce1bacebb8a835319c0ade') })
{ "_id" : ObjectId("5fce1bacebb8a835319c0ade"), "name" : "Cheese 🧀" }

# Update the document
> db.foods.update({ _id: ObjectId('5fce1bacebb8a835319c0ade') }, { name: 'Fries 🍟' })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

# Fetch the updated document
> db.foods.find({ _id: ObjectId('5fce1bacebb8a835319c0ade') })
{ "_id" : ObjectId("5fce1bacebb8a835319c0ade"), "name" : "Fries 🍟" }

The save() method combines both insert() and update() methods into one. When you use the save() method, if the document exists, it will be updated. If the document doesn't exist, it will be created:

>{ name: 'Pancakes 🥞' })
WriteResult({ "nInserted" : 1 })

Delete a document

You can use the remove() method to delete a document from a collection:

> db.foods.remove({ _id: ObjectId('5fce1bacebb8a835319c0ade') })
WriteResult({ "nRemoved" : 1 })

To remove all the documents of a collection, just pass an empty object to the remove() method:

> db.foods.remove({})
WriteResult({ "nRemoved" : 7 })

MongoDB also provides two more methods — deleteOne() and deleteMany() — for removing one and multiple documents from a collection.

Delete a collection

To drop an existing collection form the current database, you can use the drop() method:

> db.foods.drop()

If you try to delete a non-existent collection, the drop() method returns fasle:

> db.rooms.drop()

Delete a database

In MongoDB, you can drop the current database by running the db.dropDatabase() method:

> db.dropDatabase()
{ "dropped" : "hotel", "ok" : 1 }

Alternatively, you could also use the dropDatabase command to achieve the same result:

# Switch to the database
> use test
switched to db test

# Drop database
> db.runCommand({ dropDatabase: 1 })
{ "ok" : 1 }

Exit the mongo shell

To exit the mongo shell, type quit() or use the <Ctrl-C> shortcut:

> quit()

What's next?

Take a look at this article to learn how to access MongoDB programmatically by using MongoDB native driver as well as Mongoose in a Node.js application.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.