MongoDB CRUD Operations with Mongo Shell

Brief Introduction

MongoDB is a NoSQL database developed by MongoDB Inc. The important part that you need to know is that it is a document-oriented database platform. This means the data is stored as documents (in place of rows/records/tuples in SQL). A database consists of collections (similar to tables in SQL) and these collections consists of the documents which are key value pairs similar to JSON.

{
    "device_type" : "Smart Phone", // --> Field consisting of key value pairs
    "brand" : "Apple Inc.",  // --> Field consisting of key value pairs
    "model" : "iPhone 7" // --> Field consisting of key value pairs
}

Prerequisite

To start with the blog, let's first have a look at the pre-requisites:

Getting Started

There are various interfaces where we can execute these commands. However we would be using the Mongo Shell from Command Prompt (Bash in case of Unix\Linux and Terminal in MacOS) to execute these commands so that we all can stay on the same page.
We will start the MongoDB database by typing the command:

We will now create an instance of the database to execute the commands. We can do this by executing the following command:

  • mongo - The mongo shell acts as an interactive JavaScript interface to MongoDB, which allows users to query and update data, and conduct administrative operations. (techtarget.com)

You will receive a response similar to this screenshot below:

Screenshot (73).png

The last step we are going to do is creating our own database. To create a database execute the command: use inventory - This would create a database named inventory if it doesn't exist. You would receive a message - switched to db inventory. You could name anything of your choice. To confirm that you are still in the right database, execute the command db and the name of the database you are using will be shown on the next line.

Screenshot (76).png

Inserting/Creating Document

Lets finally insert some data in our database. First step is to create a collection. Create a collection by executing the following command:

db.createCollection('smart_phones')

On succesful execution of this command you would receive a message similar to this:

{ "ok" : 1 }

Inserting Single Document

Now we will insert data, that is, a document into this collection with the command:

db.smart_phones.insertOne({
    "brand" : "Apple Inc.",
    "model" : "iPhone Xs Max"
})

On successful completion you receive the Acknowledgement:

{
        "acknowledged" : true,
        "insertedId" : ObjectId("61eed7602f805a6c81b0f83b")
}

Inserting Multiple Documents

To insert multiple document at once, we execute the insertMany command:

db.smart_phones.insertMany([
    {
        "brand" : "Apple Inc.",
        "model" : "iPhone 12 Pro Max"
    },
    {
        "brand" : "Google",
        "model" : "Pixel 6 Pro"
    },
    {
        "brand" : "Google",
        "model" : "Pixel 6"
    }    
])

Note here we insert an arrayof key value pairs. The ObjectId() for each are returned respectively with the acknowledgement. These ObjectId() are used to uniquely identify each document and are therefore unique.

Reading Data/Document

We can read this inserted data by executing the following:

Read All The Documents

db.smart_phones.find({})

Screenshot (77).png

This will return all the documents we have inserted. The {} curly braces can be used to filter the data to be obtained. So lets say we wanted to obtain all documents where brand name is Google. Then we can filter the query by:

db.smart_phones.find({
    "brand" : "Google"
})

Read Only One Document

To read only document instead of we execute:

db.smart_phones.findOne({
    "brand" : "Google"
})

Here we will receive the first document inserted with the matching filter.

Updating Document

Updating One Document

To update one document we use the updateOne() function which takes, the filter as first parameter and the updated document value as second one.

db.smart_phones.updateOne({"model": "Pixel 6"},
{
    $set: {
        "model" : "Pixel 5"
    }
})

$set is an atomic operator which tells which field of the document needs to be updated. Execute db.smart_phones.find({"brand" : "Google"}) to see the updated documents.

Update Multiple Documents

To update multiple documents we execute the command:

db.smart_phones.updateMany({"model": "Pixel 6"},
{
    $set: {
        "model" : "Pixel 5"
    }
})

Replace a document

To replace a single document:

db.smart_phones.replaceOne({"model" : "Pixel 5"},
{
        "brand" : "Google",
        "model" : "Pixel 6"
})

Deleteing Documents

Delete one document

To delete a document from our collection we use:

db.smart_phones.deleteOne({"brand" : "Google"})

Screenshot (79).png

Here deleteOne() takes a key value pair which acts as a filter to identify the document to be deleted. Here even though we had multiple documents with brand name Google it only deletes one.

Delete Multiple Document

To delete multiple documents:

 db.smart_phones.deleteMany({
     "brand" : "Google"
     })

Conclusion

In the following article we used examples to demonstrate the folowing CRUD operations on the MongoDB database:

  • Collection can be created by : use collectionName.
  • Document can be created by :
    • db.collectionName.insertOne() - To insert single document.
    • db.collectionName.insertMany() - To insert multiple documents.
  • To read documents:
    • db.collectionName.find({filter}) - To read all the documents.
    • db.collectionName.findOne({filter}) - To read first matching document.
  • To update documents:
    • db.collectionName.updateOne({filter}, {$set:{value}}) - To update single document.
    • db.collectionName.updateMany({filter}, {$set:{value}}) - To update many document.
    • db.collectionName.replaceOne({filter}, {value}) - To replace single document.
  • To delete documents:
    • db.collectionName.deleteOne({fiter}) - To delete first matched document.
    • db.collectionName.deleteMany({fiter}) - To delete all matching documents.