MongoDB commands

21+ MongoDB commands developer should be aware of | Helpful MongoDB commands [2022]

MongoDB is one of the most popular open-source No-SQL databases. It is a document-based database. In this blog post, I will explain various MongoDB commands. We will also go over and install MongoDB using docker. So let’s get started.

Install MongoDB using docker

For this demo, I will be using docker to install MongoDB. Follow this link to download docker.

Now let’s verify if the docker is running.

➜  docker --version
Docker version 20.10.3, build 48d30b5

Awesome, now let’s proceed further and pull the mongo official image from dockerhub.

➜ docker pull mongo
Using default tag: latest
latest: Pulling from library/mongo
4bbfd2c87b75: Pull complete
d2e110be24e1: Pull complete
889a7173dcfe: Pull complete
6f6a1a25f35a: Pull complete
e87b34c16538: Pull complete
7099eef4dfe4: Pull complete
29b1d79d3b5b: Pull complete
b5c178e98a5a: Pull complete
ded800e62b93: Pull complete
b09aa2e255f0: Pull complete
c7e0f50ad27a: Pull complete
dcdad63a2ffa: Pull complete
Digest: sha256:482a562bf25f42f02ce589458f72866bbe9eded5b6f8fa5b1213313f0e00bba2
Status: Downloaded newer image for mongo:latest
docker.io/library/mongo:latest

Verify if the docker image gets downloaded

➜  docker images
REPOSITORY                     TAG       IMAGE ID       CREATED        SIZE
mongo                          latest    81a352f64d83   16 hours ago   449MB

Now let’s start the docker container

➜  docker run --name my-mongo -d mongo:latest
659e36f1f2b967c8cb20b1697181d03f43b83468af29c2091de40690601849ca

Type the below command to go inside the docker container

➜  docker exec -it my-mongo /bin/bash
[email protected]:/#

Verify mongo version

[email protected]:/# mongo --version
MongoDB shell version v4.4.6
Build Info: {
    "version": "4.4.6",
    "gitVersion": "72e66213c2c3eab37d9358d5e78ad7f5c1d0d0d7",
    "openSSLVersion": "OpenSSL 1.1.1  11 Sep 2018",
    "modules": [],
    "allocator": "tcmalloc",
    "environment": {
        "distmod": "ubuntu1804",
        "distarch": "x86_64",
        "target_arch": "x86_64"
    }
}
[email protected]:/#

Awesome, you have successfully installed MongoDB; let’s proceed further and see some of the commonly used MongoDB commands.

MongoDB commands

MongoDB has a vibrant command-line interface, using which we can easily interact with MongoDB.This tutorial will see some of the most widely used MongoDB commands.

Type the below command to get inside the mongo shell.

[email protected]:/# mongo
MongoDB shell version v4.4.6
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
................<supressed o/p>............
................<supressed o/p>............
---
>

List Databases

show dbs command will list all the databases present in MongoDB.By default, MongoDB has some system databases created.

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

Create new Database

use <dbname> command will create a new database in MongoDB

> use naivetech
switched to db naivetech

To view the current database

with the help of the db command; we can verify the current database user are in.

 > db
naivetech

Create a new collection

Now let’s create a test collection in the naivetech database

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

List collections in MongoDB

To list all the collections in the mongo naivetech database, type the below command:

> show collections
test

Drop a collection

Let’s drop the test collection that we have created earlier

> db.test.drop()
true

Delete a database

To drop any database, switch to that database and type the below command to delete:

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

Insert a document in MongoDB collection

Now let’s proceed further and create another database, naivetechblog, and new collection tech

> use naivetechblog
switched to db naivetechblog
> db.createCollection("tech")
{ "ok" : 1 }

Type the below command to insert a document in the tech collection

> db.tech.insert({
...     'Kind': 'Mobile',
...     'lang': 'iphone 6s',
...     'Rating': 4.2
...  })
WriteResult({ "nInserted" : 1 })
>

Show documents in a MongoDB collection

Let’s list all the documents present in the tech collection

> db.tech.find()
{ "_id" : ObjectId("60c37656a9c3d411ad96c6e6"), "Kind" : "Mobile", "lang" : "iphone 6s", "Rating" : 4.2 }

Pretty command

With MongoDB pretty command, we can print the output in pretty format

> db.tech.find().pretty()
{
	"_id" : ObjectId("60c37656a9c3d411ad96c6e6"),
	"Kind" : "Mobile",
	"lang" : "iphone 6s",
	"Rating" : 4.2
}
>

Insert many document in MongoDB collection

Sometimes we need to insert more than 1 document at one go in our MongoDB collection. With MongoDB insertmany command, we can insert multiple documents.

> db.tech.insertMany([
... {
...     'Kind': 'Mobile',
...     'lang': 'iphone 6s',
...     'Rating': 4.2
...  },
... {
...     'Kind': 'laptop',
...     'lang': 'acer',
...     'Rating': 3.9
...  },
...  {
...     'Kind': 'mobile',
...     'lang': 'samsung',
...     'Rating': 4.0
...  },
...  ])
{
	"acknowledged" : true,
	"insertedIds" : [
		ObjectId("60c37883a9c3d411ad96c6e7"),
		ObjectId("60c37883a9c3d411ad96c6e8"),
		ObjectId("60c37883a9c3d411ad96c6e9")
	]
}

Now let’s verify if all documents get created.

> db.tech.find()
{ "_id" : ObjectId("60c37656a9c3d411ad96c6e6"), "Kind" : "Mobile", "lang" : "iphone 6s", "Rating" : 4.2 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e7"), "Kind" : "Mobile", "lang" : "iphone 6s", "Rating" : 4.2 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e8"), "Kind" : "laptop", "lang" : "acer", "Rating" : 3.9 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e9"), "Kind" : "mobile", "lang" : "samsung", "Rating" : 4 }
>

Search MongoDB

With the help of the find command, we can filter out/search the documents. Let’s try to find the documents which contain mobile details.

> db.tech.find({Kind:'Mobile'})
{ "_id" : ObjectId("60c37656a9c3d411ad96c6e6"), "Kind" : "Mobile", "lang" : "iphone 6s", "Rating" : 4.2 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e7"), "Kind" : "Mobile", "lang" : "iphone 6s", "Rating" : 4.2 }
>

FindOne command in MongoDB

findOne command displays the first output based on the filter criteria

db.tech.findOne({Kind:'Mobile'})
{
	"_id" : ObjectId("60c37656a9c3d411ad96c6e6"),
	"Kind" : "Mobile",
	"lang" : "iphone 6s",
	"Rating" : 4.2
}
>

Limit command

With the limit command, we can limit the no of documents to be displayed in MongoDB

> db.tech.find().limit(2)
{ "_id" : ObjectId("60c37656a9c3d411ad96c6e6"), "Kind" : "Mobile", "lang" : "iphone 6s", "Rating" : 4.2 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e7"), "Kind" : "Mobile", "lang" : "iphone 6s", "Rating" : 4.2 }
>

Count command

Count command Counts the number of rows in the query output. Let’s try to find all documents present in the MongoDB tech database.

> db.tech.find().count()
4

Insert document with different schema in MongoDB

In MongoDB, we can insert data with different schema; we don’t have to stick to any schema while inserting data in mongo collection.

Let’s insert a document in mongo with a different schema that we have inserted earlier.

db.tech.insert({
    'Kind': 'Mobile',
    'lang': 'iphone 6s',
    'Build_year': 2013 ,
    'Rating': 4.2
 })

Let’s verify if the data gets inserted.

db.tech.find()
{ "_id" : ObjectId("60c37656a9c3d411ad96c6e6"), "Kind" : "Mobile", "lang" : "iphone 6s", "Rating" : 4.2 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e7"), "Kind" : "Mobile", "lang" : "iphone 6s", "Rating" : 4.2 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e8"), "Kind" : "laptop", "lang" : "acer", "Rating" : 3.9 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e9"), "Kind" : "mobile", "lang" : "samsung", "Rating" : 4 }
{ "_id" : ObjectId("60c38f5ca9c3d411ad96c6ea"), "Kind" : "Mobile", "lang" : "iphone 6s", "Build_year" : 2013, "Rating" : 4.2 }

Update command in MongoDB

Update command modifies the existing document or documents in a collection. With the update command, we can modify specific fields of an existing document or replace an existing document.

This session will see some of the most widely used update commands.

Update a row

Let’s use an update command to update a document where Kind: laptop.

verify the data before updating

> db.tech.find({Kind:'laptop'})
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e8"), "Kind" : "laptop", "lang" : "acer", "Rating" : 3.9

run the update command

>  db.tech.update({'Kind': 'laptop'},
... {   'Kind': 'laptop',
...     'Brand': 'samsung',
...     'Rating': 4.3
... })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Verify if the data gets successfully updated.

> db.tech.find({Kind:'laptop'})
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e8"), "Kind" : "laptop", "Brand" : "samsung", "Rating" : 4.3 }

Update with upsert

upsert flag in update command inserted a new document in MongoDB is the document does not exist.

>  db.tech.update({'Kind': 'game'},
... {   'Kind': 'game',
...     'Brand': 'sony',
...     'Rating': 4.3
... }, {upsert: true})
WriteResult({
	"nMatched" : 0,
	"nUpserted" : 1,
	"nModified" : 0,
	"_id" : ObjectId("60c3984464d905a23322abb1")
})

We got nUpserted”: 1 in the output, which means the record was not present in MongoDB, and the update command has added it as a new document.

Let’s verify the document.

> db.tech.find()
{ "_id" : ObjectId("60c37656a9c3d411ad96c6e6"), "Kind" : "Mobile", "lang" : "iphone 6s", "Rating" : 4.2 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e7"), "Kind" : "Mobile", "lang" : "iphone 6s", "Rating" : 4.2 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e8"), "Kind" : "laptop", "Brand" : "vivo", "Rating" : 4.3 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e9"), "Kind" : "mobile", "lang" : "samsung", "Rating" : 4 }
{ "_id" : ObjectId("60c38f5ca9c3d411ad96c6ea"), "Kind" : "Mobile", "lang" : "iphone 6s", "Build_year" : 2013, "Rating" : 4.2 }
{ "_id" : ObjectId("60c3984464d905a23322abb1"), "Kind" : "game", "Brand" : "sony", "Rating" : 4.3 }

Inc command

With the inc command, we can update the documents field by specific value. Let’s run this command and update the build_year by 2.

Document before updating

 db.tech.find({Kind:'Mobile'})
{ "_id" : ObjectId("60c37656a9c3d411ad96c6e6"), "Kind" : "Mobile", "lang" : "iphone 6s", "Rating" : 4.2 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e7"), "Kind" : "Mobile", "lang" : "iphone 6s", "Rating" : 4.2 }
{ "_id" : ObjectId("60c38f5ca9c3d411ad96c6ea"), "Kind" : "Mobile", "lang" : "iphone 6s", "Build_year" : 2013, "Rating" : 4.2 }

Now, let’s update the document

> db.tech.update({'Build_year': 2013},
... {$inc:{
...     Build_year: 2
... }})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
>

Now let’s verify the data after the update

db.tech.find({Kind:'Mobile'})
{ "_id" : ObjectId("60c37656a9c3d411ad96c6e6"), "Kind" : "Mobile", "lang" : "iphone 6s", "Rating" : 4.2 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e7"), "Kind" : "Mobile", "lang" : "iphone 6s", "Rating" : 4.2 }
{ "_id" : ObjectId("60c38f5ca9c3d411ad96c6ea"), "Kind" : "Mobile", "lang" : "iphone 6s", "Build_year" : 2015, "Rating" : 4.2 }

Rename command

With rename command, we can update the document field in the MongoDB collection

db.tech.update({'Build_year': 2015},
{$rename:{
    lang: "brand"
}})

verify the data after renamed

> db.tech.find({'Build_year': 2015})
{ "_id" : ObjectId("60c38f5ca9c3d411ad96c6ea"), "Kind" : "Mobile", "Build_year" : 2015, "Rating" : 4.2, "brand" : "iphone 6s" }

The complete list of update commands can be found here

Delete command in MongoDB

We can delete any document from the mongo collection with the delete command. Let’s delete the Kind: game from the tech collection

Data before deletion

db.tech.find()
{ "_id" : ObjectId("60c37656a9c3d411ad96c6e6"), "Kind" : "Mobile", "lang" : "iphone 6s", "Rating" : 4.2 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e7"), "Kind" : "Mobile", "lang" : "iphone 6s", "Rating" : 4.2 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e8"), "Kind" : "laptop", "Brand" : "vivo", "Rating" : 4.3 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e9"), "Kind" : "mobile", "lang" : "samsung", "Rating" : 4 }
{ "_id" : ObjectId("60c38f5ca9c3d411ad96c6ea"), "Kind" : "Mobile", "Build_year" : 2015, "Rating" : 4.2, "brand" : "iphone 6s" }
{ "_id" : ObjectId("60c3984464d905a23322abb1"), "Kind" : "game", "Brand" : "sony", "Rating" : 4.3 }

Delete the document

db.tech.remove({"Kind":"game"})
WriteResult({ "nRemoved" : 1 })

Verify the data after the deletion

db.tech.find()
{ "_id" : ObjectId("60c37656a9c3d411ad96c6e6"), "Kind" : "Mobile", "lang" : "iphone 6s", "Rating" : 4.2 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e7"), "Kind" : "Mobile", "lang" : "iphone 6s", "Rating" : 4.2 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e8"), "Kind" : "laptop", "Brand" : "vivo", "Rating" : 4.3 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e9"), "Kind" : "mobile", "lang" : "samsung", "Rating" : 4 }
{ "_id" : ObjectId("60c38f5ca9c3d411ad96c6ea"), "Kind" : "Mobile", "Build_year" : 2015, "Rating" : 4.2, "brand" : "iphone 6s" }

Less than command in mongoDB

In MongoDB, we can use less than one command to filter out the document based on filter criteria. Let’s filter out the Mobile whose rating is less than 4.2

db.tech.find({Rating: {$lt: 4.2}})
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e9"), "Kind" : "mobile", "lang" : "samsung", "Rating" : 4 }

Less than equal to command in MongoDB

Like less than command, we can use less than equal command in MongoDB to filter out documents.

db.tech.find({Rating: {$lte: 4.2}})
{ "_id" : ObjectId("60c37656a9c3d411ad96c6e6"), "Kind" : "Mobile", "lang" : "iphone 6s", "Rating" : 4.2 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e7"), "Kind" : "Mobile", "lang" : "iphone 6s", "Rating" : 4.2 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e9"), "Kind" : "mobile", "lang" : "samsung", "Rating" : 4 }
{ "_id" : ObjectId("60c38f5ca9c3d411ad96c6ea"), "Kind" : "Mobile", "Build_year" : 2015, "Rating" : 4.2, "brand" : "iphone 6s" }

Greater than command

Let’s filter out the Mobile whose rating is greater than 4.2

db.tech.find({Rating: {$gt: 4.2}})
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e8"), "Kind" : "laptop", "Brand" : "vivo", "Rating" : 4.3 }

Greater than equal to command

Similar to greater than command, we can use greater than equal to command in MongoDB to filter out documents.

db.tech.find({Rating: {$gte: 4.2}})
{ "_id" : ObjectId("60c37656a9c3d411ad96c6e6"), "Kind" : "Mobile", "lang" : "iphone 6s", "Rating" : 4.2 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e7"), "Kind" : "Mobile", "lang" : "iphone 6s", "Rating" : 4.2 }
{ "_id" : ObjectId("60c37883a9c3d411ad96c6e8"), "Kind" : "laptop", "Brand" : "vivo", "Rating" : 4.3 }
{ "_id" : ObjectId("60c38f5ca9c3d411ad96c6ea"), "Kind" : "Mobile", "Build_year" : 2015, "Rating" : 4.2, "brand" : "iphone 6s" }

Conclusion

I hope you have liked this tutorial. Please do let me know in the comment box. I will be more than happy to hear from you.

More to Read

Docker layers

Which docker base image to use

What docker images are available

Leave a Comment

Your email address will not be published.

Scroll to Top