Fundamental of MongoDB and an introduction to MongoDB CRUD operations

In this post, we will discuss the fundamentals of MongoDB and I will also introduce you to MongoDB CRUD operations with examples.

Before we head towards the CRUD operations and their example let’s understand some of the key terminologies.

key terminologies

Database: Inside a Mongo server we can have multiple databases, similar to SQL where we have multiple schemas under one database server. Inside a database, all the collections are stored.

Collection: Collection in MongoDB which holds the documents, it is similar to tables in SQL with no restricted schema.

The term no restricted schema means MongoDB does not enforce a schema to be followed by all the documents inside a particular collection, Unlike SQL where we have to define a table schema and all the records have to follow it. However, we can have schema and MongoDB allows you to validate the document against it.

Document: Document in mongodb is a single record inside a collection. The document is JSON which mogo prefers to call BSON. It is like a row in the table in terms of RDBMS.

BSON: As per wiki The name “BSON” is based on the term JSON and stands for “Binary JSON”. It is a binary form for representing simple or complex data structures including associative arrays (also known as name-value pairs), integer indexed arrays and a suite of fundamental scalar types. BSON originated in 2009 at MongoDB.

It’s time to move to the CRUD operations in MongoDB. In this section, we will discuss the following.

  • Create a database
  • Display the list of all the databases
  • The first operation of CRUD, insert record in a collection
  • Display all the collections inside a database
  • Read the document from the collection, the second operation of CRUD
  • The third operation of CRUD, update documents
  • The fourth operation of CRUD, delete documents
  • Drop collection
  • Drop database

I will use Mongo shell in this section for all the examples, if you haven’t configured it, you can read Setting up MongoDB and an introduction to Mongo shell.

Create a database

Create a database or use a database using use ‘database name’. We will create a database shop using the command, use the shop.

use shop
switched to DB shop

Display all the databases

To display all the databases we can use “show dbs” command.

show dbs
admin 0.000GB
analytics 0.003GB
config 0.000GB
local 0.000GB

Notice the shop db we have created above is not appearing here. This is because we haven’t created a single collection inside this database. No worries, let’s create one.

Insert record in a collection

db.products.insertOne({productName:'Product 1', price:299, receivedOn:new Date()})
{
"acknowledged": true,
"insertedId" : ObjectId("5ed06aa81dba2aa6bdb7a6ab")
}
> show dbs
admin 0.000GB
analytics 0.003GB
config 0.000GB
local 0.000GB
shop 0.000GB
test 0.000GB

Now you can see, after creating a document the shop db is appearing in the database list. Let’s create more documents in products collection.

db.products.insertMany([{productName:'Product 2', price:199, receivedOn:new Date()},{productName:'Product 3', price:399, receivedOn:new Date()},{productName:'Product 4', price:499, receivedOn:new Date()},{productName:'Product 5', price:599, receivedOn:new Date()}])
{
"acknowledged": true,
"insertedIds" : [
ObjectId("5ed06baf1dba2aa6bdb7a6ac"),
ObjectId("5ed06baf1dba2aa6bdb7a6ad"),
ObjectId("5ed06baf1dba2aa6bdb7a6ae"),
ObjectId("5ed06baf1dba2aa6bdb7a6af")
]
}

Display collections inside a database

To display all the collections inside a database we can “show collections” command like below.

show collections
products

Read/Fetch document from the collection

TO read documents we can use the find method like below. MongoDB also provides an aggregation framework to read the document, which will be covered in a later post.


db.products.find().pretty()
{
"_id" : ObjectId("5ed06aa81dba2aa6bdb7a6ab"),
"productName" : "Product 1",
"price" : 299,
"receivedOn" : ISODate("2020-05-29T01:51:36.729Z")
}
{
"_id" : ObjectId("5ed06baf1dba2aa6bdb7a6ac"),
"productName" : "Product 2",
"price" : 199,
"receivedOn" : ISODate("2020-05-29T01:55:59.532Z")
}
{
"_id" : ObjectId("5ed06baf1dba2aa6bdb7a6ad"),
"productName" : "Product 3",
"price" : 399,
"receivedOn" : ISODate("2020-05-29T01:55:59.532Z")
}
{
"_id" : ObjectId("5ed06baf1dba2aa6bdb7a6ae"),
"productName" : "Product 4",
"price" : 499,
"receivedOn" : ISODate("2020-05-29T01:55:59.532Z")
}
{
"_id" : ObjectId("5ed06baf1dba2aa6bdb7a6af"),
"productName" : "Product 5",
"price" : 599,
"receivedOn" : ISODate("2020-05-29T01:55:59.532Z")
}

Update documents

like find and insert we can use an update method to update a document like below.

db.products.updateOne({productName:"Product 1"},{$set:{isAvailable:true}})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

We can verify the update operation using the find method.

db.products.find().pretty()
{
"_id" : ObjectId("5ed06aa81dba2aa6bdb7a6ab"),
"productName" : "Product 1",
"price" : 299,
"receivedOn" : ISODate("2020-05-29T01:51:36.729Z"),
"isAvailable" : true
}
{
"_id" : ObjectId("5ed06baf1dba2aa6bdb7a6ac"),
"productName" : "Product 2",
"price" : 199,
"receivedOn" : ISODate("2020-05-29T01:55:59.532Z")
}
{
"_id" : ObjectId("5ed06baf1dba2aa6bdb7a6ad"),
"productName" : "Product 3",
"price" : 399,
"receivedOn" : ISODate("2020-05-29T01:55:59.532Z")
}
{
"_id" : ObjectId("5ed06baf1dba2aa6bdb7a6ae"),
"productName" : "Product 4",
"price" : 499,
"receivedOn" : ISODate("2020-05-29T01:55:59.532Z")
}
{
"_id" : ObjectId("5ed06baf1dba2aa6bdb7a6af"),
"productName" : "Product 5",
"price" : 599,
"receivedOn" : ISODate("2020-05-29T01:55:59.532Z")
}

Delete documents

Similar to update we can use the delete method to delete a document.

db.products.deleteOne({"_id" : ObjectId("5ed06baf1dba2aa6bdb7a6af")})
{ "acknowledged" : true, "deletedCount" : 1 }

The products collection after deleting a document.
db.products.find().pretty()
{
"_id" : ObjectId("5ed06aa81dba2aa6bdb7a6ab"),
"productName" : "Product 1",
"price" : 299,
"receivedOn" : ISODate("2020-05-29T01:51:36.729Z"),
"isAvailable" : true
}
{
"_id" : ObjectId("5ed06baf1dba2aa6bdb7a6ac"),
"productName" : "Product 2",
"price" : 199,
"receivedOn" : ISODate("2020-05-29T01:55:59.532Z")
}
{
"_id" : ObjectId("5ed06baf1dba2aa6bdb7a6ad"),
"productName" : "Product 3",
"price" : 399,
"receivedOn" : ISODate("2020-05-29T01:55:59.532Z")
}
{
"_id" : ObjectId("5ed06baf1dba2aa6bdb7a6ae"),
"productName" : "Product 4",
"price" : 499,
"receivedOn" : ISODate("2020-05-29T01:55:59.532Z")
}

Please note, each method mentioned above to insert, read, update, and delete has multiple variations as shown in the below table.

InsertFindUpdateDelete
insertOne()findOne()updateOne()deleteOne()
insertMany()find()UpdateMany()deleteMany()
insert()findAndModify()Update()remove()
findOneAndDelete()replaceOne()
findOneAndReplace()
findOneAndUpdate()

In the next post, we will discuss all the variations in detail.

Drop collection

db.collectionName.drop()

Drop database

db.dropDatabase()

Reference

https://docs.mongodb.com/manual/reference/method/

Happy Learning !!

Leave a Comment