Click here to Skip to main content
12,818,785 members (28,760 online)
Click here to Skip to main content
Add your own
alternative version

Stats

16K views
59 downloads
47 bookmarked
Posted 25 Mar 2016

Mongo DB Tutorial and Mapping of SQL and Mongo DB Query

, 19 Apr 2016 CPOL
Rate this:
Please Sign up or sign in to vote.
Mongo DB Tutorial and Mapping of SQL and Mongo DB Query

Introduction

Welcome to MongoDB Tutorial, This is the first part in the MongoDB article series. Here is the link of all the three parts till now.

1. http://www.codeproject.com/Articles/1087008/Mongo-DB-Tutorial-and-Mapping-of-SQL-and-Mongo-DB

2. http://www.codeproject.com/Articles/1089786/MongoDB-Tutorial-Day

3. http://www.codeproject.com/Articles/1091645/MongoDB-Tutorial-Day-Performance-Indexing

In first part and as we are new to MongoDB and No-SQL i would like to start with the definition of No-SQL.

No-SQL : No-SQL stands for Not Only SQL.No-SQL is a not relational based database.No-SQL databases does not follow the rules of RDMS and No-SQL databases does not use SQL to query the data.

No-SQL databases can be divided in to four categories

1. Document Store  2. Graph Store 3. Column Value Store 5. Key-Value Store

MongoDB comes under Document Store database

Document Store Databases : In Document Store Database, Data stored in form of documents. it extends the Key value Store Database Concept.

Mongo DB and Couch DB are two main Document Store Databases .Mongo DB stores data in form of Documents. Here is an example of sample document.

Set up Mongo DB on Machine

Download MongoDB from below MongoDB official Site (Download MSI file as per your Operating System)

https://www.mongodb.org/downloads#production

Install MSI file (In case of Window Operation System,Default Location is (C:\Program Files\MongoDB)

Copy this folder and Place this in your C Drive or any other drive and Create a Folder in C drive named data and a Folder named db inside data folder.

So In C Drive we have two folders now

1. MongoDB (Copied from Installation Location)

2. data/db (Create a folder named data and a folder named db inside data Folder)

Start Mongo DB

Go to the bin folder inside MongoDB folder which we placed in c Drive

In my case bin Folder is inside MongoDB folder(It can be inside server folder as well as below)

C:\Program Files\MongoDB\Server\3.0\bin

and double click on the Mongod.exe (It will open a command Prompt and it will start the MongoDB server)

Last line should say "Waiting for connections..." as below it means our Mongo DB server has been started successfully

Download RoboMongo

RoboMongo. Shell-centric cross-platform open source MongoDB management tool (i.e.... Admin GUI). [It] embeds the same JavaScript engine (based on Mozilla SpiderMonkey), that powers MongoDB's mongo shell. It means that you can reuse your existing skills of MongoDB Shell in Robomongo

We can download Robomongo from Robomongo Original Site named Robomongo.org. Here is the URL

https://robomongo.org/

Once download. Run the exe and Go to the File-->Connect (Make sure your mongodb server is up and running which we ran in last step through Mongod.exe)

MongoDB Terminology

Before going foreword we should know the terminology of MongoDB

OperationIn SQLIn MongoDB
CreateInsertInsert
ReadSelectFind
UpdateUpdateUpdate
DeleteDeleteRemove
TableTableCollection
RowRowDocument

Key points of MongoDB

1. MongoDB Stores Data in Json Format(We call it BSON(Binary JSON))

2. JSON stands for JavaScript Object Notations and looks like {“Name”:”Vijay”}

3. JSON documents store data in Key Value Pair like {“X”:1,”Y”:2,”Z”:3}

4. There are two basic structure inside JSON is

      a. Array : List of things is represented in List of Items [……..]

      b. Dictionaries : Associate Maps {key:Value}

For example {Name : ‘Vijay’,City : ‘Shamli’,interest : ["Sports" ,"Music"  ]}

Name and city is dictionary and Interest is an Array.

5. Mongo Db is Schema less , Schema Less means two documents don’t need to be same schema.

   First Document in a collection can be :  {Name:"Vijay",Email:"VijayRana1091@gmail.com"}

   Second Document in same collection can be : {Name:"Vijay",Email:"VijayRana1091@gmail.com",Address : "Delhi"}

6. MongoDB does not support Joins.

7. Mongo DB does not support Transactions.

Its Query Time

We will see here some of the query which we run in Sql server on daily basis and equivalent query in Mongo DB.

For this i created a table in SQL server with below schema and a same collection(Remember table is a collection in MongoDB) in MongoDB. 

Same table we will create in MongoDB and different operations on this table using MongoDB.

OperationSQLMongoDB
Select Databaseuse Testuse Test

We will get a message "switched to db Test" 

Insert Record

Insert into

Student Values(1,'Vijay',

'VijayRana1091@gmail.com',

'9711965544','Delhi')

db.Student.insert(

{"_id":1,"Name":"Vijay","Email":"VijayRana1091@gmail.com",

"PhoneNo":"9711965544","Address":"Delhi"}

)

Note : _id works as a primary key in MongoDb. if we will not insert any value in this column then MongoDB will automatically insert a unique ID in Table.

Inserting some more records in both Sql Server and in MongoDB (Attaching Sql script and MongoDB script)

Download InsertRecord.zip

After Running scripts we have below data in Student table (Sql server and in MongoDB) databases.

Select

Select all Columns :

select * from student

Select few Column :

select ID,Name from Student

Select all Columns :

db.Student.find()

Select few Column :

db.Student.find({},{"Name":true})

We use find() Method to pull all the records from the table.

Where Clause

select * from student where Name='Vijay'

 

db.Student.find({Name:"Vijay"})
Greater Than and Less Than

select * from student where ID>2

select * from student where ID>=2

select * from student where ID<2

select * from student where ID<=2

 

db.Student.find({_id:{$gt:2}})

db.Student.find({_id:{$gte:2}})

db.Student.find({_id:{$lt:2}})

db.Student.find({_id:{$lte:2}})

We use $gt/$gte for Greater Than/Greater Than Equal and $lt/$lte for Less Than/Less Than Equal 

Like

Below query will Find all the records where letter P exist somewhere in Name Column

select * from student where Name like '%P%'

Suppose we want to find all the records where Name ends with letter 'a'

select * from student where Name like '%a'

Suppose we want to fetch all the records where Name starts with Letter 'P'

select * from student where Name like 'p%'

 

In Mongo DB we use $regex operator to check whether letter 'P' exist somewhere in Name Column.

db.Student.find({Name:{$regex:"P"}})

Below query will Fetch all the records where Name ends with letter 'a'

db.Student.find({Name:{$regex:"a$"}})

Below query will Fetch all the records where Name starts with letter 'P'

db.Student.find({Name:{$regex:"^P"}})

And/Or

And : select * from Student 
where Name ='Vijay' 
and phoneNo='9711965544'

Or : select * from Student 
where Name ='Vijay' 
or phoneNo='9711997119'

And : db.Student.find({$and :[{Name :'Vijay'},{PhoneNo : '9711965544'}]})

Or : db.Student.find({$or:[{Name :'Vijay'},{PhoneNo : '9711997119'}]})

inselect * from Student where id in(1,3,5)db.Student.find({_id:{$in:[1,3,5]}})
Count/Sort

Count all the records :

select count(*) from Student 

Sort Records in ascending order:

select * from student order by Name

Sort in descending order :

select * from student order by Name desc

Count all the records :

db.Student.find().count()

Sort Records in ascending order:

db.Student.find().sort({Name:1})

 

Sort in descending order :

db.Student.find().sort({Name:-1})

Updateupdate student set phoneNo='2222222222',
Address='USA' 
where ID=4

db.Student.update({_id:4},{$set:{PhoneNo:'2222222222',Address:'USA'}})

Upsert :

db.Student.update({_id:9},{$set:{PhoneNo:'2222222222',Address:'USA'}},{upsert:true})

above query will search a document where _id is 9. it there will be a _id with 9 it will update phoneNo and Address otherwise it will insert a new document where _id is 9.

Multi : 

Suppose we execute below query 

db.Student.update({Name:"Vijay"},{$set:{PhoneNo:'2222222222',Address:'USA'}})

It will update only one record(remember only first Match where name is "Vijay"). But if we want to update all the records where Name is "Vijay" then we will pass multi argument also

db.Student.update({Name:"Vijay"},{$set:{PhoneNo:'2222222222',Address:'USA'}},{multi:true})

 

Delete/Remove/Drop

Delete with Condition :

Delete from student where ID=5

Delete all the records :

Delete from Student

Drop :

drop table Student

Delete with Condition :

db.Student.remove({_id:5})

Delete all the records :

db.Student.remove({})

Drop:

db.Student.drop()

Top

select Top 2* from Student

Limit:

db.Student.find().limit(2)

Skip :

db.Student.find().skip(2).limit(2)

As name suggest skip will skip the number of documents and limit will limit the number of records.

 
distinctselect distinct Name from Studentdb.Student.distinct("Name")
 
Backup

BACKUP DATABASE Test
TO DISK = 'C:\Vijay\Test.Bak'
   WITH FORMAT,
      MEDIANAME = 'Z_SQLServerBackups',
      NAME = 'Full Backup of Test Database';

 

Go to the command Prompt and run the below command (assuming your mongodump exe is inside bin folder, if it is a different location then change this location accordingly)

C:\Program Files\MongoDB\Server\3.0\bin\mongodump --db Test

 

 

MongoDB Functions

In MongoDB databases we can create functions like in Sql Server. MongoDB provides us a collection named as System.js for this.

System.js collection contains two keys

1. _id : _id is the function name.

2. value :  value contains actual function defination.

For example, suppose we want to create a function which will accept two parameters named  firstname and lastname and will return full name.

db.system.js.save
(
   {
     _id: "FullName",
     value : function(FirstName,LastName) { return FirstName + ' ' + LastName; }
   }
)

In order to call this function we need to load server scripts first, and than we can call this function as below

db.loadServerScripts();
FullName('Vijay','Rana')

Vijay Rana will be the result when we will call this function.

Auto Increment ID( Identity in Sql Server) in MongoDB

In MongoDB _id works as a primary key. if we don't insert any value in _id field then MongoDB automatically insert a unique hexadecimal value in this column.But if we want to enter auto increment integer value (Like Identity in Sql Server or Sequence in Oracle) in this field then there is no direct way to do so. For this we need to follow below steps

Step 1: Create a collection( Identity in my case) which will hold the counter

db.createCollection("Identity") // Identity is my collection Name

Step 2: Insert a document in this collection with intial counter value

db.Identity.insert({_id:"incrementID",sequence_value:0}) 

Step 3: Create a function which will increment this sequence_value and add that function in system.js as below

db.system.js.save
(
   {
     _id: "getNextIdentity",                                            
     value : function getNextIdentity(sequenceName)
     {
        var sequenceDocument = db.Identity.findAndModify
            ({
                query:{_id: sequenceName },
                update: {$inc:{sequence_value:1}},
                new:true
            });
        return sequenceDocument.sequence_value;
     }
   }
)

Step 4: While inserting a document we can call this function, which will return a incremented value as below

db.Employee.insert({
   "_id":getNextIdentity("incrementID"),
   "EmpName":"Vijay",
   "Age":"30"
})

 

In Next Article i will talk about the rest of the MongoDB commands, How we will Generate Auto Increment ID as we normally does in Sql Server(Identity Column) and we will see the connectivity of .Net with MongoDB.

License

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

Share

About the Author

VijayRana
Technical Lead
India India
Hi Myself Vijay having around 7 years of experience on Microsoft Technologies.

You may also be interested in...

Pro
Pro

Comments and Discussions

 
PraiseMY VOTE OF FIVE Pin
Tarun.Saini07171-Jul-16 2:03
memberTarun.Saini07171-Jul-16 2:03 
Questionplease help to develop mongo db query Pin
Tushar sangani7-Jun-16 0:12
professionalTushar sangani7-Jun-16 0:12 
Praisewonderful Pin
Rupal Gupta24-Apr-16 23:22
memberRupal Gupta24-Apr-16 23:22 
GeneralAmazing article Pin
Member 1247122619-Apr-16 9:07
memberMember 1247122619-Apr-16 9:07 
QuestionVery nice Vijay Pin
Member 124461708-Apr-16 16:16
memberMember 124461708-Apr-16 16:16 
GeneralMy vote of 5 Pin
priyanka choudhary8-Apr-16 15:49
memberpriyanka choudhary8-Apr-16 15:49 
GeneralMy vote of 5 Pin
priyanka choudhary8-Apr-16 15:48
memberpriyanka choudhary8-Apr-16 15:48 
SuggestionPlease research if you are about to write an article... Pin
Andreas Kroll31-Mar-16 7:22
memberAndreas Kroll31-Mar-16 7:22 
GeneralRe: Please research if you are about to write an article... Pin
Vijay Rana AON (+91-9711965544)31-Mar-16 8:23
professionalVijay Rana AON (+91-9711965544)31-Mar-16 8:23 
PraiseGood article on Mongo DB.. Thanks alot!!! My vote is 5... Pin
Munir Ahmd29-Mar-16 8:20
memberMunir Ahmd29-Mar-16 8:20 
PraiseExcellent! Pin
AJSON28-Mar-16 3:09
mvpAJSON28-Mar-16 3:09 
GeneralRe: Excellent! Pin
Vijay Rana (+91-9711965544)10-Apr-16 3:11
professionalVijay Rana (+91-9711965544)10-Apr-16 3:11 
GeneralRe: Excellent! Pin
AJSON10-Apr-16 8:17
mvpAJSON10-Apr-16 8:17 
GeneralBest article Pin
Member 1240810325-Mar-16 5:09
memberMember 1240810325-Mar-16 5:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170308.1 | Last Updated 19 Apr 2016
Article Copyright 2016 by VijayRana
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid