Database CRUD Operations with MongDB - BOOKC -->

Database CRUD Operations with MongDB

Monday, June 11, 2018


This is the second article I bring you on the topic of MongoDB! When I changed my database experience from SQL to NOSQL, I found this one is more easier and faster SQL.There are no heavy queries. The queries seem to be day to day English. So, I decided to write an article to introduce you the CRUD operations using MongoDB. CRUD means, Create, Retrieve, Update and Delete. Let's begin the work!

First you need to open up a connection to mongoDB. For that, open a command prompt and type mongod on it. Then it will start to run the DB setup.. Finally you can see this line in cmd, after a successful start of MongoDB.


Now keep this cmd alive and open another cmd or gitbash. Type mongo on this new cmd. Then you get the access to MongoDB through your cmd.

Basic Commands:

show dbs
This will output the existing databases in your MongoDB environment.

use DB_Name        Ex: use shop
Create a new database and select it. In MYSQL, we use two commands for this.
If you have to access a database already created, you can use the above command.

db.createCollection('Collection_Name')         Ex: db.createCollection('products')
Create a new collection. Collection is like a table in SQL. It holds the data records as objects with key value pairs.



Create a record object

In MongoDB, records are stored as Objects. They have keys and values.
db.products.insert({name: 'Product 1', qty: 20, price: 50})
db.products.insert({name: 'Product 2', qty: 10, price: 30})
db.products.insert({name: 'Product 3', qty: 30, price: 70})



Retrieve data object records

We did not give an ID for these records. But MongoDB automatically adds an ID in the form of a random string. To see the records, use the below command.

1. Get All Records

db.products.find()
db.products.find().pretty()
The second command will output data in a formatted way.



2. Get a particular object

We can retrieve a particlur object using any key you know.. Here I'm trying to find the record having name as Product 1.
db.products.find({name: 'Product 1'})
db.products.find({name: 'Product 1'}).pretty()

Output:


3. Get sorted objects according to a key

I use sort command to order the objects according to the price key. See the result..
db.products.find().sort()
db.products.find().sort({price:1}).pretty()


4. Get count of records

When we need to get a count of the all records in a collection, we can use this command.
db.products.find().count()

Update data object records 

Here, we have to do the update process using a key. That key is used to find the relevant record from database. I use Product Name as the key, since it's a unique one for each record.
db.products.update({name: 'Product 1'},{$set:{price: 40}})
Look at the new records. The price of Product 1 has been changed from 50 to 40.


In MongoDB, we can do another special thing when we update a record. When we are going to update a object record, If the particular object is not found, we can tell MongoDB to insert it as a new  object record.
db.products.update({name: 'Product 6'},{name: 'Product 6', price: 45, qty: 30}, {upsert: true})

Now, a new record will be added with the name of Product 6 since it is not found in the collection.



Delete record object

We have to use a unique key here also, to target a particular record.
db.products.remove({name: 'Product 3'})
You can see the 3rd object has been removed from the collection now. There are only 2 records in this collection now.


Change collection structure

1. Add new Key Field to only one object

In MYSQL, we have to give values for all fields in DB table. Otherwise there should be default values declared when the DB table is defined.
But in NO SQL, records are objects. We can add a new field with a value to only a particular object. I will add a new object with name Product 4.

db.products.insert({name: 'Product 4, qty: 50, price: 80, category: 'Electronics'})

Here you can see a new key has been added with no errors to Product 4. Only this object is having the key called category.


We can add a new Key to an existing object also with update command.

db.products.update({name: 'Product 1'},{$set:{category: 'Households'}})

See the below output. The first record has been modified.



2. Rename a Key Field of only one object

We can rename the key of an object. It will not affect to the objects.
db.products.update({name: 'Product 2'},{$rename:{'price','unit_price'}})

Look at this output! Only the Product 2's key has been changed from price to unitprice.



We have now practiced most of the basic commands with MongoDB. You may have already seen that the commands are completely different from MYSQL. That's why practice is needed to get familiar with MongoDB. This is totally different experience to me also. But I found it easy to learn these commands. There are so many commands.. Read their official documentation for more details. My intention was to give you the main CRUD operations with MongoDB databases.

Future, I will come up with a tutorial to connect MongoDB with NodeJS and handle some tasks. Till then, practice these commands..

Good Luck guys!