Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / MongoDB

Introduction to MongoDB

4.88/5 (24 votes)
7 Oct 2015CPOL12 min read 36.2K  
Introduction to MongoDB

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 really got impressed. So this article is dedicated to great MongoDB. In this article we will learn 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 doesn’t 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 doesn’t support joins but it can represent rich, hierarchical data structures. And of the best feature the 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 what it means is that 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.

Image 1

Let’s see how RDBMS and MongoDB differ:

Image 2

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.

Below are the steps to install and run MongoDB:

  • Head over to the official website of MongoDB (http://www.mongodb.org/downloads) and grab the latest 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:

{
	_id: ObjectID('4bd9e8e17cefd644108961bb'),
	name:'Vivek',
	class : '12th',
	subjects: [ 'physics', 'chemistry', 'math', 'english', 'computer'],
	address: {
					house_no: '12B',
					block: 'B',
					sector: 12,
					city : 'noida',
					},
	grade: [
					{
					exam: 'unit test 1',
					score: '60%'
					},
					{
					exam: 'unit test 2',
					score: '70%'
					}
					
				]				
}

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 form of another in-document and grade contains its value in 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 this 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

Image 3

Mongo Client

Image 4

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 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 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.

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.

Image 5

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

Image 6

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.

doc={
name:'xyx',
class:'12th',
subjects:['physics','chemisrty','maths','english','computer'],
address:{
		house_no:'123',
		sector:'50',
		city:'noida'
		}
}
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 see below for example:

db.mycol.insert({
	name:'Vivek',
	class : '12th',
	subjects: [ 'physics', 'chemistry', 'math', 'english', 'computer'],
	address: {
					house_no: '12B',
					block: 'B',
					sector: 12,
					city : 'noida',
					},
	grade: [
					{
					exam: 'unit test 1',
					score: '60%'
					},
					{
					exam: 'unit test 2',
					score: '70%'
					}
					
				]			
});

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.

Image 7

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:

"_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 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 below command to insert 100 records in one go.

for(i=0;i<100;i++)
{
	subjects=['chemistry','physics','maths','english','computer'];
	for(j=0;j<5;j++)
	{
		db.marks.insert({
			name:"student"+ i,
			subject:subjects[j],
			marks:Math.round(Math.random()*100)
		}
		);
	}
}

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 explain 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.

Image 8

Passing parameter in find() method:

  • Let’s say we want find all the records of student0 so we will write:
    db.marks.find({name:'student0'})

    Image 9

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

    Image 10

    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:
    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:
    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:
    db.marks.find({$or:[{subject:'computer'},{subject:'physics'}],marks:{$gt:90}})

    $or takes an array of criteria that needs to be matched.

    Image 11

  • 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:
    db.mycol.find({class:{$exists:true}})

    similarly, we can write $exists : false for records in which class field doesn’t exists.

  • Let’s say we have another collection named additionalsubject:
    db.additionalsubject.insert({name:'student1',subject:['arts','music']})
    
    db.additionalsubject.insert({name:'student2',subject:['sports','arts']})
    
    db.additionalsubject.insert({name:'student3',subject:['sports','cooking','music']})
    
    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 : 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:

    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.

    Image 12

  • 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:
    db.additionalsubject.find({subject:{$in:['sports','arts']}})
  • We have dot notations to query collections having nested documents.

    For example in 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:

    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 write like this then:
db.additionalsubject.update({name:'student1'},{subject:['craft']})

It will not only change the subject field but will replace the whole document.

Image 13

After updating document:

Image 14

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 replace the old document with new fields and new values.

  1. 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:
db.additionalsubject.update({name:'student2'},{$set:{name:'xyz'}})

Before Update:

Image 15

After update:

Image 16

  1. 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 to subject field for the student name ‘xyz’:
db.additionalsubject.update({name:'xyz'},{$unset:{subject:1}})

Before update:

Image 17

After update:

Image 18

  1. 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.
    db.additionalsubject.update({name:'student5'},{$set:{subject:['music']}},{upsert:true})
  2. 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:
      db.additionalsubject.update({name:'student3'},{$set:{'subject.0':'arts'}});

      subject is the array so if we want change the subject indexed at 0th place we will write subject.0

      Image 19

    2. Add one more subject to student3 record. For this we have $push:
      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)
      
      db.additionalsubject.update({name:'student3'},{$pop:{'subject':1}});

      Image 20

    4. We have $pushAll to add one or more value to array. Similarly we $pull to remove one specified value from array, and $pullAll to remove one or more values from the array. Let’s see example:
      db.additionalsubject.update({name:'student3'},{$pushAll:{'subject':['sports','craft']}})
      
      db.additionalsubject.update({name:'student3'},{$pullAll:{'subject':['sports','craft']}})
  3. MongoDB updates only one document that fulfills 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:

    db.additionalsubject.update({},{$set:{'class':’12<sup>th</sup>’}},{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 same as find command it requires one parameter which is the matching criteria for the document.

  • If we want remove the record of student named student3 then we will write:
    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.
    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.

Image 21

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)