Learn MongoDB Step by Step

Introduction

I read somewhere that MongoDB is the database for the modern web which induced a thought in me that what’s so special about this new database that everybody is talking about it and believe me when I started digging into this I was really impressed. So this article is dedicated to MongoDB. In this article we will learn the basics about MongoDB. I have tried to make things easier and clear to understand. I hope in the end of this article you will have enough understanding about MongoDB.

What is MongoDB?

MongoDB is an open source document oriented database. MongoDB falls in the category of the NoSQL – Database which means it do not follow fixed schema structure like in relational databases.

MongoDB cannot replace Relational databases but it should be viewed as an alternative to it.

MongoDB can be installed on Windows, Linux and MAC, so it is a cross platform database. It do not support joins but it can represent rich, hierarchical data structures. And the best feature like the most is that it is easily scalable and can give high performance.

The MongoDB database consists of a set of databases in which each database contains multiple collections. MongoDB is schema-less that means every collection can contain different types of object. Every object is also called document which is represented as a JSON (JavaScript Object Notation) structure: a list of key-value pairs. The value can be of three types: a primitive value, an array of documents or again a list of key-value pairs.

MongoDB database

Let’s see how RDBMS and MongoDB differ:

RDBMS vs MongoDB

Getting started: Installing MongoDB

Let’s install MongoDB on windows to dive into the world of MongoDB. Note in this article we will see the steps to install MongoDB on windows only.

The following are the steps to install and run MongoDB:

  • Head over to the official website of MongoDB and grab the latest version of MongoDB. If your windows system is 64-bit, then download the 64-bit version, else download the 32-bit version.

    Note: 32-Bit versions of MongoDB support databases smaller than 2GB so they are suitable only for testing and evaluation purposes.
  • Run the setup (.msi) downloaded.

  • Follow the instructions in the installation wizard.

  • By default MongoDB will be installed in C: drive.

  • Create a directory named data in the C: drive and then create another directory named db in data directory. All the databases get stored here.

  • Set the path of MongoDB (C:\Program Files\MongoDB\Server\3.0\bin) in environment variable.

If you followed above steps then your MongoDB is up and running to create our databases and collection.

Document-Oriented Data-Model

But before we move into the next step of creating our own database let’s see what exactly document oriented data-model is:

A typical document in MongoDB looks something like this:

  1. {  
  2.     _id: ObjectID('4bd9e8e17cefd644108961bb'),  
  3.     name: 'Vivek',  
  4.     class'12th',  
  5.     subjects: ['physics''chemistry''math''english''computer'],  
  6.     address: {  
  7.         house_no: '12B',  
  8.         block: 'B',  
  9.         sector: 12,  
  10.         city: 'noida',  
  11.     },  
  12.     grade: [{  
  13.             exam: 'unit test 1',  
  14.             score: '60%'  
  15.         }, {  
  16.             exam: 'unit test 2',  
  17.             score: '70%'  
  18.         }  
  19.   
  20.     ]  
  21. }  
Above document contains information of a student in the key-value pair. It contains unique _id for the record, name and its value, class and its value, subjects and its value is in the form of array, address contains its value in the form of another in-document and grade contains its value in the form of arrays of documents.

If we have to represent the same record in Relational world then we would require at least three tables. One to store basic information like _id, name, class, address and another to store subjects and another one to store grades, etc. But here we stored the whole relational information in one complete document this is how we managed the deficiency of joins and constraints in MongoDB. In MongoDB we do not have joins but it’s up to us the developers how we are designing our schema to manage relations.

I hope this would have given you the basic idea of document-oriented data model. Let’s see how we perform CRUD operations in MongoDB.

Diving into the MongoDB-shell

If you have successfully installed and setup the environment variable of MongoDB then you are ready to start MongoDB.

Open the command prompt of windows and type ‘mongod’ to start the MongoDB server. MongoDB server will get started, you will see the message ‘waiting for connections’ at the end of the screen and cursor will be blinking that means your server has been started and waiting for connections from MongoDB clients.

Now open another command prompt and type ‘mongo’ to make connection to the server. Remember don’t close the first command prompt.

Mongo Server

Mongo Server

Mongo Client

Mongo Client

As you can see in Mongo Client you will some important information:
  • MongoDB shell version: 3.0.6 ( It may be differ depending upon your version of MongoDB).

  • Connecting to: test ( It is the test database which MongoDB automatically creates for you and connects you to it.).

All the queries and commands we are going to write in this shell. MongoDB shell is an interactive JavaScript interpreter which means if you know javascript, then writing MongoDB commands/queries is a cake-walk for you.

In the MongoDB shell type ‘help’ and press enter then you will see bunch of helper functions that MongoDB provides for us.

Well we talked a lot now it’s time for some action let’s see some commands now.

  • show dbs : Will show the databases in your system.
  • show collections : Will show the collections in a db.
  • db.help() : Will show the help on db methods.
  • db.mycoll.help() : Will show the help on collections methods.

Creating our own database:

Type use [database name] and press enter. If the database exists the MongoDB will switch to database else it will create a brand new database for you.

For example: Type ‘ use students’ to create a database named students.

CRUD Operations

We have already created our database and now it’s time to create our collection. So how do we create collection, it’s as easy as eating pie just use insert command. Let me show you.

  1. db.mycol.insert({name:'vikas'})  
Here mycol is the name of collection and we have inserted a document in it. We just have to write the name of collection and insert record in it. MongoDB will automatically create collection if it’s been not created else will insert the record in the existing collection.

switch database

So for CRUD (Create Read Update Delete) operation we have the following commands in the MongoDB:

commands in the MongoDB

Insert()

Insert command is used to insert documents in a collection as we know document in MongoDB stores JSON object as document so insert command accept JSON object as parameter.
  1. doc = {  
  2.     name: 'xyx',  
  3.     class'12th',  
  4.     subjects: ['physics''chemisrty''maths''english''computer'],  
  5.     address: {  
  6.         house_no: '123',  
  7.         sector: '50',  
  8.         city: 'noida'  
  9.     }  
  10. }  
  11. db.mycol.insert(doc);  
Here we created an object named doc and used that object as a parameter in insert command.

You can also insert document without creating any variable and directly pass document in the insert command. Here's an example.
  1. db.mycol.insert({  
  2.     name: 'Vivek',  
  3.     class'12th',  
  4.     subjects: ['physics''chemistry''math''english''computer'],  
  5.     address: {  
  6.         house_no: '12B',  
  7.         block: 'B',  
  8.         sector: 12,  
  9.         city: 'noida',  
  10.     },  
  11.     grade: [{  
  12.             exam: 'unit test 1',  
  13.             score: '60%'  
  14.         }, {  
  15.             exam: 'unit test 2',  
  16.             score: '70%'  
  17.         }  
  18.   
  19.     ]  
  20. });  
If you type the command db.my.col.find() you will see all the records inserted so far. Note if you type the db.my.col.find().pretty() output displayed will be well indented and formatted.

see all the records inserted

One thing to notice here that we didn’t provided _id for any of the above document but MongoDB itself inserted unique _id which is something like the following:

"_id" : ObjectId("560f767315f507b3c0bae3f5")

When we insert a document in MongoDB, server require that all documents coming have a unique identifying field, in fact it uses _id for that. The _id field in a document is a primary key which means it requires that the value of _id field should be unique. _id field is immutable which means you cannot change it. ObjectId is a type to generate unique keys which takes current time, identifier for the machine that constructing the ObjectId, the process id of the process that constructing the ObjectId and the counter that is global to object that constructing the ObjectId, by pushing these information together MongoDB creates a unique id for us. Of course we can create our own _id field but for every other document it must be unique.

So we have seen that how we can insert documents in MongoDB which means we have completed our C part of CRUD operation. Let’s move to the next part.

Find()

To use find() command to query our collection we need some more records to see various form of find() command, so let’s insert some more records in our collection. I have used the following command to insert 100 records in one go.
  1. for(i=0;i<100;i++)  
  2. {  
  3.     subjects=['chemistry','physics','maths','english','computer'];  
  4.     for(j=0;j<5;j++)  
  5.     {  
  6.         db.marks.insert({  
  7.             name:"student"+ i,  
  8.             subject:subjects[j],  
  9.             marks:Math.round(Math.random()*100)  
  10.         }  
  11.         );  
  12.     }  
  13. }  
Note: I have used indentation just to make code readable but when you write the above code in MongoDB shell please remove all tabs and spaces.

Now we have a collection named marks and it has 100 records in it.

We have used find() command earlier also but I didn’t explained how it works, so let’s see how it works. Find command takes a pattern matching parameter to match its corresponding records just like where in Select query in SQL. If you write SELECT * FROM Table in SQL it will give you all records in a table similarly if you write db.CollectionName.find() it will return all the records in the collection.

find command

Passing parameter in find() method:
  • Let’s say we want to find all the records of student0, so we will write:
    1. db.marks.find({name:'student0'})  
    find all the records

  • Find record of student0 in subject computer:
    1. db.marks.find({name:'student0',subject:'computer'}).pretty()  
    record

    Here we passed two condition to match our document that is name should equal to student0 and subject should equal to computer.

  • Find records of all students whose marks in computer is greater than 50:
    1. db.marks.find({subject:'computer',marks:{$gt:50}}).pretty()  
    Find command takes an object as a parameter similarly we will also pass document to match condition that is marks should be greater than 50.

    Greater than: $gt
    Greater and Equal : $gte
    Less than: $lt
    Less and Equal: $lte

  • Find records of all students whose marks in computer is greater than 50 and less than equal to 90:
    1. db.marks.find({subject:'computer',marks:{$gt:50,$lte:90}}).pretty()  
  • Find records of all students whose marks in computer or physics is greater than 90:
    1. db.marks.find({$or:[{subject:'computer'},{subject:'physics'}],marks:{$gt:90}})  
    $or takes an array of criteria that needs to be matched.

    array of criteria

  • In our previous collection mycol, documents had different schema design,   so let’s say we want to find the records in which class field exists:
    1. db.mycol.find({class:{$exists:true}})  
    Similarly, we can write $exists : false for records in which class field doesn’t exist.

  • Let’s say we have another collection named additionalsubject:
    1. db.additionalsubject.insert({name:'student1',subject:['arts','music']})  
    2. db.additionalsubject.insert({name:'student2',subject:['sports','arts']})  
    3. db.additionalsubject.insert({name:'student3',subject:['sports','cooking','music']})  
    4. db.additionalsubject.insert({name:'student4',subject:['arts','craft','music']})  
    And we want to find the records of those students who are enrolled in arts. So the query will be written as:
    1. db.additionalsubject.find({subject:'arts'})  
    But if we want to find records of those students who are enrolled in arts and music both, then our query will be:
    1. db.additionalsubject.find({subject:{$all:['arts','music']}})  
    The important thing to notice here is that $all will look for all the values passed in the array irrespective of the sequence they are present in collection.

    sequence

  • Similarly we have $in to look for either of the values passed in it. Let’s say we want to find the records of students who are either enrolled in sports or arts. Then the query will be:
    1. db.additionalsubject.find({subject:{$in:['sports','arts']}})  
  • We have dot notations to query collections having nested documents.

    For example, in the first document shown earlier in which grades contains arrays of documents and if we want to find the grade of exam unit test 1 then the query will be written as:
    1. db.mycol.find({'grade.exam' :'unit test 1'})  

Update()

Update command takes two parameter first one is matching criteria and second one is updated value.

Syntax:

    db.[collectionName].update({matching criteria},{updated value});

Update command in MongoDB performs four major tasks.

  1. Performing Whole-Sale Replacement, means it will replace the whole document except for the ObjectId. For example, in our additionalsubject collection if want to change the subject of student1, and we wrote like this then:
    1. db.additionalsubject.update({name:'student1'},{subject:['craft']})  
    It will not only change the subject field but will replace the whole document.

    change the subject field

    After updating the document:

    After updating document

    Now there is no name field only ObjectId and subject field, so we can say this is not the right way to update a document because updating in this manner will replace the whole document with new updated value but this command is useful when you want to replace the old document with new fields and new values.

  2. Modifying only the desired field, if we want to just modify some values of field then we have $set operator for this. For example. Let’s say we want to change the name of student2 to ‘xyz’, in this case we only want to modify the name field and don’t want to touch other field so we will write:
    1. db.additionalsubject.update({name:'student2'},{$set:{name:'xyz'}})  
    Before Update:

    old value

    After update:

    new value

  3. Removing undesirable field means we can remove a field from a document when we don’t require it. For this we have $unset opearator. For example, let’s say we want subject field for the student name ‘xyz’:

    db.additionalsubject.update({name:'xyz'},{$unset:{subject:1}})

    Before update:

    Before update

    After update:

    After update

  4. Update command searches for the record that matches the criteria specified in the parameter and if finds the record then it updates it otherwise nothing is updated. We have a special operator upsert that creates the new record and then update it. So if we will try to update the record of student5 nothing will happen because we do not have student5 record but if we use upsert then a new record for student5 gets created and updated.
    1. db.additionalsubject.update({name:'student5'},{$set:{subject:['music']}},{upsert:true})  
  5. If we want to update arrays in a document then we can easily do this in MongoDB. We also have some special operators in MongoDB to update arrays in a document. Let’s see some examples to update arrays in a document:

    1. Change subject of student3 from sports to arts:
      1. db.additionalsubject.update({name:'student3'},{$set:{'subject.0':'arts'}});  
      Subject is the array so if we want to change the subject indexed at 0th place we will write subject.0

      Change subject

    2. Add one more subject to student3 record. For this we have $push:
      1. db.additionalsubject.update({name:'student3'},{$push:{'subject':'sports'}})  
      It will add one more subject ‘sports’ at the end of the subject field.

    3. Similarly, we have $pop to remove a value from the array. But it will remove the rightmost value from the array.

      $pop : 1 (remove rightmost value)
      $pop : -1 (remove leftmost value)
      1. db.additionalsubject.update({name:'student3'},{$pop:{'subject':1}});  
      remove a value

    4. We have $pushAll to add one or more value to array. Similarly, $pull to remove one specified value from array, and $pullAll to remove one or more values from the array.

      Let’s see an example:
      1. db.additionalsubject.update({name:'student3'},{$pushAll:{'subject':['sports','craft']}})  
      2. db.additionalsubject.update({name:'student3'},{$pullAll:{'subject':['sports','craft']}})  
  6. MongoDB updates only one document that fulfil the matching criteria but if you want to update all document at a time, then we have to pass one additional parameter mult:true.

    For example, if we want one more additional field to all document of additionalsubject collection:
    1. db.additionalsubject.update({},{$set:{'class':’12th’}},{multi:true})  
    It will add a new field class to every document in the collection.

So we are done with update commands.

Remove()

Remove command is used to remove records from collection, it works the same as find command and requires one parameter which is the matching criteria for the document.

  • If we want to remove the record of student named student3, then we will write:
    1. db.additionalsubject.remove({name:'student3'})  
  • And we want to remove all documents of a collection, then we have to pass an empty document as a parameter to the remove command.
    1. db.additionalsubject.remove({})  
    It will remove all the documents of collection.

Conclusion

We used MongoDB to create our database and then we created our collection and learnt CRUD operations on our collection. I hope you have enjoyed this article. You will realize the real power of MongoDB when you start using it.

learn Mongodb


Similar Articles