Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 33

Mongo DB

BEGINNER MODULE

1. Introduction to MongoDB

Introduction

MongoDB is an open source database that uses a document-oriented data model. MongoDB
is one of several database types to arise in the mid-2000s under the NoSQL banner. Instead
of using tables and rows as in relational databases, MongoDB is built on an architecture of
collections and documents.

NoSQL what does it mean

NoSQL means Not Only SQL, implying that when designing a software solution or product,
there is more than one storage mechanism that could be used based on the needs. NoSQL
was a hashtag (#nosql) chosen for a meetup to discuss these new databases. The most
important result of the rise of NoSQL is Polyglot Persistence. NoSQL does not have a
prescriptive definition but we can make a set of common observations, such as:

 Not using the relational model


 Running well on clusters
 Mostly open-source
 Built for the 21st-century web estates
 Schema-less

Document Database¶

A record in MongoDB is a document, which is a data structure composed of field and value
pairs. Unlike relational databases where data is stored in the format of rows and columns
,MongoDB stores the data as  JSON objects. The values of fields may include other
documents, arrays, and arrays of documents. 

FirstName="Arun", Address="St. Xavier's Road", Spouse=[{Name:"Kiran"}],


Children=[{Name:"Rihit", Age:8}]. 

FirstName="Sameer",Address="8 Gandhi Road".

Notice there are two different documents (separated by "."). Storing data in this fashion is
called as document oriented database. MongoDb is a document oriented database.

If we have to store the same data in any relation db,the schema of the database may look
like this

PersonId FirstName LastName AddressId SpouseName

1
         

PersonId AddressId Line1 Line2 City Postcode

           

PersonId Child1 Child2

     

The advantages of using documents are:

 Documents (i.e. objects) correspond to native data types in many programming


languages.
 Embedded documents and arrays reduce need for expensive joins.
 Dynamic schema supports fluent polymorphism.

Schema Free

MongoDB is a JSON-style data store. The documents stored in the database can have
varying sets of fields, with different types for each field. One could have the following objects
in a single collection:{name : “Joe”, x : 3.3, y : [1,2,3]}{name : “Kate”, x : “abc”}{q : 456}One of
the great benefits of thesedynamic objects is that schema migrations become very easy.
With a traditional RDBMS, releases of code might contain data migration scripts. Further,
each release should have a reverse migration script in case a rollback is necessary. ALTER
TABLE operations can be very slow and result in scheduled downtime. With a schemaless
database, 90% of the time adjustments to the database become transparent and automatic.
For example, if we wish to add GPA to the student objects, we add the attribute, resave, and
all is well – if we look up an existing student and reference GPA, we just get back null.
Further, if we roll back our code, the new GPA fields in the existing objects are unlikely to
cause problems if our code was well written.

Sharding

Sharding is the process of storing data records across multiple machines and it is MongoDB's
approach to meet the demands of data growth. As the size of the data increases, a single
machine may not be sufficient to store the data nor provide an acceptable read and write
throughput. Sharding solves the problem with horizontal scaling. With sharding, you add
more machines to support data growth and the demands of read and write operations.

Mongo DB VS RDBMS

Many concepts in MySQL have close analogs in MongoDB. This table outlines some of the
common concepts in each system.

2
MySQL MongoDB

Table Collection

Row Document

Column Field

Joins Embedded documents, linking

Collection is not strict about what goes in it


Schema Oriented
It(schema-less)

Query Language

Both MySQL and MongoDB have a rich query language. A comprehensive list of statements
can be found in theMongoDB documentation.

MySQL

INSERT INTO users (user_id, age, status)  VALUES ("bcd001", 45, "A")

MongoDB

db.users.insert({ 

user_id: "bcd001",  

age: 45,  

status: "A"})

MongoDB Installation

Use this tutorial to install MongoDB Community Edition on Windows systems.

PLATFORM SUPPORT :

Starting in version 2.2, MongoDB does not support Windows XP. Please use a more recent
version of Windows to use more recent releases of MongoDB.

IMPORTANT :

If you are running any edition of Windows Server 2008 R2 or Windows 7, please install a
hotfix to resolve an issue with memory-mapped files on Windows.

3
Requirements

MongoDB Community Edition requires Windows Server 2008 R2, Windows Vista, or later. The
.msiinstaller includes all other software dependencies and will automatically upgrade any
older version of MongoDB installed using an .msi file.

Get MongoDB Community Edition

NOTE

To install a version of MongoDB prior to 3.2, please refer to that version’s documentation.
For example, see version 3.0.

 Determine which MongoDB build you need.

The following MongoDB builds are available for Windows:

MongoDB for Windows 64-bit runs only on Windows Server 2008 R2, Windows 7 64-bit,
and newer versions of Windows. This build takes advantage of recent enhancements to the
Windows Platform and cannot operate on older versions of Windows.

MongoDB for Windows 64-bit Legacy runs on Windows Vista, and Windows Server 2008
and does not include recent performance enhancements.

To find which version of Windows you are running, enter the following commands in
the Command Prompt or Powershell:

wmic os get caption wmic os get osarchitecture

 Download MongoDB for Windows.

Download the latest production release of MongoDB from the MongoDB downloads page.
Ensure you download the correct version of MongoDB for your Windows system. The 64-bit
versions of MongoDB do not work with 32-bit Windows.

Install MongoDB Community Edition

Interactive Installation

 Install MongoDB for Windows.

In Windows Explorer, locate the downloaded MongoDB .msi file, which typically is located in


the default Downloads folder. Double-click the .msi file. A set of screens will appear to guide
you through the installation process.

You may specify an installation directory if you choose the “Custom” installation option.

NOTE

4
These instructions assume that you have installed MongoDB to C:\mongodb.

MongoDB is self-contained and does not have any other system dependencies. You can run
MongoDB from any folder you choose. You may install MongoDB in any folder
(e.g. D:\test\mongodb).

Unattended Installation

You may install MongoDB Community unattended on Windows from the command line
usingmsiexec.exe.

 Open an Administrator command prompt.

Press the Win key, type cmd.exe, and press Ctrl + Shift + Enter to run the Command


Prompt as Administrator.

Execute the remaining steps from the Administrator command prompt.

 Install MongoDB for Windows.

Change to the directory containing the .msi installation binary of your choice and invoke:

msiexec.exe /q /i mongodb-win32-x86_64-2008plus-ssl-3.2.5-signed.msi ^
INSTALLLOCATION="C:\mongodb" ^             ADDLOCAL="all"

You can specify the installation location for the executable by modifying
the INSTALLLOCATION value.

By default, this method installs all MongoDB binaries. To install specific MongoDB
component sets, you can specify them in the ADDLOCAL argument using a comma-
separated list including one or more of the following component sets:

Component Set Binaries

Server mongod.exe

Router mongos.exe

Client mongo.exe

MonitoringTools mongostat.exe, mongotop.exe

ImportExportTools      mongodump.exe, mongorestore.exe, mongo
                      export.exe, mongoimport.exe

bsondump.exe, mongofiles.exe, mongooplog
MiscellaneousTools
.exe, mongoperf.exe

5
For instance, to install only the MongoDB utilities, invoke:

msiexec.exe /q /i mongodb-win32-x86_64-2008plus-ssl-3.2.5-signed.msi ^             

                     INSTALLLOCATION="C:\mongodb" ^           

ADDLOCAL="MonitoringTools,ImportExportTools,MiscellaneousTools"

Run MongoDB Community Edition

WARNING

Do not make mongod.exe visible on public networks without running in “Secure Mode” with


the auto setting. MongoDB is designed to be run in trusted environments, and the database
does not enable “Secure Mode” by default.

 Set up the MongoDB environment.

MongoDB requires a data directory to store all data. MongoDB’s default data directory path
is\data\db. Create this folder using the following commands from a Command Prompt:

md \data\db

You can specify an alternate path for data files using the --dbpath option to mongod.exe, for
example:

C:\mongodb\bin\mongod.exe --dbpath d:\test\mongodb\data

If your path includes spaces, enclose the entire path in double quotes, for example:

C:\mongodb\bin\mongod.exe --dbpath "d:\test\mongo db data"

You may also specify the dbpath in a configuration file.

 Start MongoDB.

To start MongoDB, run mongod.exe. For example, from the Command Prompt:

C:\mongodb\bin\mongod.exe

This starts the main MongoDB database process. The waiting for connections message in the


console output indicates that the mongod.exe process is running successfully.

Depending on the security level of your system, Windows may pop up a Security Alert dialog
box about blocking “some features” of C:\mongodb\bin\mongod.exe from communicating
on networks. All users should select Private Networks, such as my home or work network and
click Allow access. For additional information on security and MongoDB, please see
theSecurity Documentation.

6
 Connect to MongoDB.

To connect to MongoDB through the mongo.exe shell, open another Command Prompt.

C:\mongodb\bin\ mongo.exe

If you want to develop applications using .NET, see the documentation of C# and
MongoDB for more information.

 Begin using MongoDB.

To help you start using MongoDB, MongoDB provides Getting Started Guides in various
driver editions. See Getting Started for the available editions.

Before deploying MongoDB in a production environment, consider the Production


Notes document.

Later, to stop MongoDB, press Control+C in the terminal where the mongod instance is


running.

Configure a Windows Service for MongoDB Community Edition

 Open an Administrator command prompt.

Press the Win key, type cmd.exe,and press Ctrl + Shift + Enter to run the Command


Prompt as Administrator.

Execute the remaining steps from the Administrator command prompt.

 Create directories.

Create directories for your database and log files:

mkdir c:\data\db mkdir c:\data\log

 Create a configuration file.

Create a configuration file. The file must set systemLog.path. Include additional configuration


options as appropriate.

For example, create a file at C:\mongodb\mongod.cfg that specifies


both systemLog.path andstorage.dbPath:

systemLog:     destination: file     path: c:\data\log\mongod.log storage:     dbPath: c:\data\db

 Install the MongoDB service.

IMPORTANT

7
Run all of the following commands in Command Prompt with “Administrative Privileges”.

Install the MongoDB service by starting mongod.exe with the --install option and the -


configoption to specify the previously created configuration file.

"C:\mongodb\bin\mongod.exe" --config "C:\mongodb\mongod.cfg" --install

To use an alternate dbpath, specify the path in the configuration file


(e.g.C:\mongodb\mongod.cfg) or on the command line with the --dbpath option.

If needed, you can install services for multiple instances of mongod.exe or mongos.exe.


Install each service with a unique --serviceName and --serviceDisplayName. Use multiple
instances only when sufficient system resources exist and your system design requires it.

 Start the MongoDB service.

net start MongoDB

 Stop or remove the MongoDB service as needed.

To stop the MongoDB service use the following command:

net stop MongoDB

To remove the MongoDB service use the following command:

"C:\mongodb\bin\mongod.exe" --remove

Manually Create a Windows Service for MongoDB Community Edition


You can set up the MongoDB server as a Windows Service that starts automatically at boot
time.

The following procedure assumes you have installed MongoDB Community using
the .msi installer with the path C:\mongodb\.

If you have installed in an alternative directory, you will need to adjust the paths as
appropriate.

Open an Administrator command prompt.


Press the Win key, type cmd.exe, and press Ctrl + Shift + Enter to run the Command
Prompt as Administrator.

Execute the remaining steps from the Administrator command prompt.

8
Create directories.
Create directories for your database and log files:

mkdir c:\data\db mkdir c:\data\log

Create a configuration file.


Create a configuration file. The file must set systemLog.path. Include
additional configuration options as appropriate.

For example, create a file at C:\mongodb\mongod.cfg that specifies


both systemLog.path andstorage.dbPath:

systemLog:     destination: file     path: c:\data\log\mongod.log storage:     dbPath:


c:\data\db 

Create the MongoDB service.


Create the MongoDB service.

sc.exe create MongoDB binPath="C:\mongodbin\mongod.exe --service


--config=\"C:\mongodb\mongod.cfg\"" DisplayName="MongoDB" start="auto"

sc.exe requires a space between “=” and the configuration values (eg “binPath=”), and a “\”
to escape double quotes.

If successfully created, the following log message will display:

[SC] CreateService SUCCESS

 Start the MongoDB service.

net start MongoDB 

Stop or remove the MongoDB service as needed.


To stop the MongoDB service, use the following command:

net stop MongoDB

To remove the MongoDB service, first stop the service and then run the following command:

sc.exe delete MongoDB

Trouble Shooting

1.I am getting the following error in Mac when I try to start mongodb

9
Solution:

You just have to give access to your /data/db folder.

Type sudo chown -R <USERNAME> /data/db, replace <USERNAME> by your username.

You can find your username by typing whoami.

2. Setting Environment Variables

In this section,we are going to see how to set the environment variables for mongodb .

 Why we need to set the environment variables.

If we don’t set it each time we have to launch  the mongodb from the install location of the
mongodb

Once the environment variable has been set.mongod can be invoked directly from command
prompt

 Steps to set environment variable

10
Windows 10 and Windows 8

In Search, search for and then select: System (Control Panel)

Click the Advanced system settings link.

Click Environment Variables. ...

In the Edit System Variable window, specify the value of the PATH environment variable.

Add the location of the bin folder of the mongodb  in PATH variable

Click Ok

Click OK again

After setting the environment variable now we can invoke mongo db from command prompt

1. Open Command Prompt as admin


2. Type mongod.exe
3. The mongod service will be launched and it will start listening in port 27017

Default
Description
Port
The default port for mongod and mongos instances. You can
27017
change this port with port or --port.
 

MongoChef for MongoDB 3.2

MongoChef is the best tool to work with MongoDB. Whether you’re exploring your local
database or working with shards and replica sets, MongoChef is here to help and make
working with MongoDB a pleasure.

You can install the version of MongoChef based on your OS .Download Mongochef from
below link

http://3t.io/mongochef/

3. Start the mongo Shell

To start the mongo shell and connect to your MongoDB instance running


on localhost with default port:

 Go to your <mongodb installation dir>:

                  cd <mongodb installation dir>

11
 Type ./bin/mongo to start mongo:

                 ./bin/mongo

If you have added the <mongodb installation dir>/bin to the PATH environment variable,


you can just type mongo instead of ./bin/mongo.

The use Command

 MongoDB uses DATABASE_NAME is used to create a database. The command will create a


new database, if it doesn't exist otherwise it will return the existing database.

 Syntax:

        Basic syntax of use DATABASE statement is as follows:

                use DATABASE_NAME

 Example:

         If you want to create a database with name <mydb>, then use DATABASEstatement


would be as follows:

                      >use mydb switched to db mydb

        To check your currently selected database use the command db

                      >db mydb

         If you want to check your databases list, then use the command show dbs.

                     >show dbs

                             local     0.78125GB

                             test      0.23012GB

         Your created database (mydb) is not present in the list. To display database, you need
to insert at least one document into it.

                    >db.myCollection.insert({"name":"guvi"})

                    >show dbs

                             local      0.78125GB

                             mydb       0.23012GB

12
                             test       0.23012GB

In mongodb default database is test database. If you didnt ' create any database then
collections will be stored in the test database.

TroubleShooting

1. Mongo client (mongo.exe) successfully connected mongodb server(mongod.exe). When i


created data base, it created and showed. But when i run this command "show dbs;", it did
not show anything. Check the following command line.

Solution: You need to create at least one document in database, after you database will
show up in list.

The dropDatabase() Method

MongoDB db.dropDatabase() command is used to drop a existing database.

Syntax:

         Basic syntax of dropDatabase() command is as follows:

         Note:db always refers to the current database in use.

         db.dropDatabase()

         This will delete the selected database. If you have not selected any database, then it will
delete default 'test' database

Example:

  First, check the list available databases by using the command show dbs

                    >show dbs

                             local      0.78125GB

13
                             mydb       0.23012GB

                             test       0.23012GB >

 If you want to delete new database <mydb>, then dropDatabase()command would


be as follows:

                  >use mydb switched to db mydb

                  >db.dropDatabase()

                  >{"dropped" : "mydb", "ok" : 1}

 Now check list of databases

                 >show dbs

                         local      0.78125GB

                         test       0.23012GB >

4. Creating Collections

The create Collection() Method

MongoDB db.createCollection(name, options) is used to create collection.

Syntax

Basic syntax of createCollection() command is as follows

        db.createCollection(name, options)

In the command, the name is the name of the collection to be created. Options is a


document and used to specify the configuration of the collection.

Paramete
Type Description
r
Name String Name of the collection to be created
Documen (Optional) Specify options about memory size and
Options
t indexing
The options parameter is optional, so you need to specify the only name of the collection.
Following is the list of options you can use:

Field Type Description


capped    Boolean   (Optional) If true, enables a capped collection. Capped
collection is a collection fixed size collection that

14
automatically overwrites its oldest entries when it
reaches its maximum size. If you specify true, you
need to specify size parameter also.
autoIndexI (Optional) If true, automatically create the index on a
Boolean
D _id field.s Default value is false.
(Optional) Specifies a maximum size in bytes for a
size number capped collection. If capped is true, then you need to
specify this field also.
(Optional) Specifies the maximum number of
max number
documents allowed in the capped collection.
While inserting the document, MongoDB first checks size field of capped collection, then it
checks max field.

Examples:

 Basic syntax of createCollection() method without options is as follows

         >use test switched to db test

         >db.createCollection("mycollection")

          {"ok" : 1}

 You can check the created collection by using the command show collections

>show collections

mycollection

system.indexes

 Following example shows the syntax of createCollection() method with few important


options:

>db.createCollection("mycol",{capped : true, autoIndexID : true, size : 6142800, max : 10000})

{"ok" : 1}

 In mongodb you don't need to create collection. MongoDB creates collection


automatically, when you insert some document.

>db.guvi.insert({"name" : "tutorialspoint"})

>show collections

mycol

15
mycollection

guvi

Drop Collection

The drop() Method

MongoDB's db.collection.drop() is used to drop a collection from the database.

Syntax:

 Basic syntax of drop() command is as follows

db.COLLECTION_NAME.drop()

Example:

 First, check the available collections into your database mydb

>use mydb switched to db mydb

>show collections

mycol

mycollection

 Now drop the collection with the name mycollection

>db.mycollection.drop()

true

Again check the list of collections into database

                      >show collections

                       mycol

drop() method will return true if the selected collection is dropped successfully otherwise it
will return false

INTERMEDIATE MODULE

1.Creating and Dropping Documents

The insert() Method

16
To insert data into MongoDB collection, you need to use
MongoDB's insert()or save()method.

Syntax

 Basic syntax of insert() command is as follows −

                  >db.COLLECTION_NAME.insert(document)

Example

                  >db.mycol.insert({_id: ObjectId(7df78ad8902c),    

                  title: 'MongoDB Overview',   

                 description: 'MongoDB is no sql database',    

                                        by: 'guvi,    

                                        url: 'https://www.guvi.in,    

                                        tags: ['mongodb', 'database', 'NoSQL'],    

                                        likes: 100})

Here mycol is the collection name. If the collection doesn't exist in the database, then
MongoDB will create this collection and then insert document into it.

In the inserted document if we don't specify the _id parameter, then MongoDB assigns a
unique ObjectId for this document.

_id is 12 bytes hexadecimal number unique for every document in a collection. 12 bytes are
divided as follows −

_id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id, 3 bytes incrementer)

 To insert multiple documents in the single query, you can pass an array of documents
in the insert() command.

Example

                >db.post.insert([    

               {title: 'MongoDB Overview',        

                description: 'MongoDB is no sql database',       

                 by: 'guvi',       

17
                 url: 'https://www.guvi.in,       

                 tags: ['mongodb', 'database', 'NoSQL'],       

                 likes: 100},    

                {title: 'NoSQL Database',        

                 description: “NoSQL database doesn't have tables”,      

                 by: 'guvi',       

                 url: 'https://www.guvi.in”,

                 tags: ['mongodb', 'database', 'NoSQL'],       

                 likes: 20,        

                 comments: [{            

                 user:'user1',             

                 message: 'My first comment',             

                 dateCreated: new Date(2013,11,10,2,35),             

                  like: 0}]}])

To insert the document you can use db.post.save(document) also. If you don't specify _id in


the document then save() method will work same asinsert() method. If you specify _id then it
will replace whole data of document containing _id as specified in save() method

2. Query Document

The find() Method

To query data from MongoDB collection, you need to use MongoDB's find()method.

Syntax

 Basic syntax of find() method is as follows

>db.COLLECTION_NAME.find()

find()method will display all the documents in a non structured way.

The pretty() Method

18
To display the results in a formatted way, you can use pretty() method.

Syntax

>db.mycol.find().pretty()

Example

>db.mycol.find().pretty()

                             {   

"_id": ObjectId(7df78ad8902c),    

                      "title": "MongoDB Overview",     

                      "description": "MongoDB is no sql database",   

                       "by": "guvi",   

                       "url": “https://www.guvi.in”,   

                       "tags": ["mongodb", "database", "NoSQL"],   

                        "likes": "100"}>

Apart from find() method there is findOne() method, that returns only one document.

"

3. Query Document AND OR C

RDBMS Where Clause Equivalents in MongoDB

To query the document on the basis of some condition, you can use following operations

AND in MongoDB

Syntax

 In the find() method if you pass multiple keys by separating them by ',' then


MongoDB treats it AND condition. Basic syntax of AND is shown below −

                  >db.mycol.find({key1:value1, key2:value2}).pretty()

Example

19
 Below given example will show all the tutorials written by 'guvi' and whose title is
'MongoDB Overview'

                 >db.mycol.find({"by":"guvi","title": "MongoDB Overview"}).pretty()

                {   "_id": ObjectId(7df78ad8902c),   

                 "title": "MongoDB Overview",    

                 "description": "MongoDB is no sql database",    

                  "by": "guvi",   

                   "url": "https://www.guvi.in",  

                    "tags": ["mongodb", "database", "NoSQL"],  

                      "likes": "100"}

For the above given example equivalent where clause will be ' where by=‘guvi’ AND
title='MongoDB Overview' '. You can pass any number of key, value pairs in find clause.

OR in MongoDB

Syntax

 To query documents based on the OR condition, you need to use $orkeyword. Basic


syntax of OR is shown below –

                  >db.mycol.find(   

                 {$or: [{key1: value1},{key2:value2}      ]    }).pretty()

Example

 Below given example will show all the tutorials written by 'tutorials point' or whose
title is 'MongoDB Overview'

                >db.mycol.find({$or:[{"by":"guvi"},{"title": "MongoDB Overview"}]}).pretty()

                {"_id": ObjectId(7df78ad8902c),    

                 "title": "MongoDB Overview",     

                  "description": "MongoDB is no sql database",    

                  "by": "guvi",    

20
                   "url": "https://www.guvi.in",    

                   "tags": ["mongodb", "database", "NoSQL"],    

                    "likes": "100"}

Using AND and OR together

Example

 Below given example will show the documents that have likes greater than 100 and
whose title is either 'MongoDB Overview' or by is 'tutorials point'. Equivalent sql
where clause is 'where likes>10 AND (by='tutorials point' OR title='MongoDB
Overview')'

                   >db.mycol.find({"likes":{$gt:10}, $or: [{"by": "guvi"},{"title": "MongoDB


Overview"}]}).pretty()

                     {   

                     "_id": ObjectId(7df78ad8902c),    

                     "title": "MongoDB Overview",     

                    "description": "MongoDB is no sql database",    

                     "by": "guvi",    

                     "url": "https://www.guvi.in",    

                      "tags": ["mongodb", "database", "NoSQL"],   

                       "likes": "100"}>

4. MongoDB Update Document.

MongoDB's update() and save() methods are used to update document into a collection. The


update() method update values in the existing document while the save() method replaces
the existing document with the document passed in save() method.

MongoDB Update() method

The update() method updates values in the existing document.

Syntax

 Basic syntax of update() method is as follows

21
                >db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)

Example

 Consider the mycol collectioin has following data.

              {"_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}

             {"_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}

            {"_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}

 Following example will set the new title 'New MongoDB Tutorial' of the documents
whose title is 'MongoDB Overview'

            >db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}})

            >db.mycol.find()

           {"_id" : ObjectId(5983548781331adf45ec5), "title":"New MongoDB Tutorial"}

           {"_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}

           {"_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}>

 By default mongodb will update only single document, to update multiple you need
to set a paramter 'multi' to true.

              >db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB


Tutorial'}},{multi:true})

MongoDB Save() Method

The save() method replaces the existing document with the new document passed in save()
method

Syntax

 Basic syntax of mongodb save() method is shown below −

                  >db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})

Example

 Following example will replace the document with the _id '5983548781331adf45ec7'

                  >db.mycol.save(    {"_id" : ObjectId(5983548781331adf45ec7), "title":"guvi New


Topic",          "by":"guvi"    })

22
                  >db.mycol.find(){"_id" : ObjectId(5983548781331adf45ec5), "title":"guvi New
Topic",    "by":"guvi"}{"_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{"_id" :                                             ObjectId(5983548781331adf45ec7), "title":"Tutorials Point
Overview"}

ADVANCED MODULE

1. Delete Document

The remove() Method

MongoDB's remove() method is used to remove the document from the collection. remove()


method accepts two parameters. One is deletion criteria and the second is justOne flag

deletion criteria : (Optional) deletion criteria according to documents will be removed.

justOne : (Optional) if set to true or 1, then remove only one document.

Syntax:

 Basic syntax of remove() method is as follows

>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)

Example

 Consider the mycol collectioin has following data.

{"_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}

{"_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}

{"_id" : ObjectId(5983548781331adf45ec7), "title":"Database Overview"}

 Following example will remove all the documents whose title is 'MongoDB Overview'

>db.mycol.remove({'title':'MongoDB Overview'})

>db.mycol.find()

{"_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}

{"_id" : ObjectId(5983548781331adf45ec7), "title":"Database Overview"}

Remove only one

 If there are multiple records and you want to delete only first record, then
setjustOne parameter in remove() method

23
>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)

Remove All documents

 If you don't specify deletion criteria, then mongodb will delete whole documents
from the collection. This is equivalent of SQL's truncate command.

>db.mycol.remove()

>db.mycol.find()

2. MongoDB Projection

In MongoDB projection, meaning is selecting only necessary data rather than selecting whole
of the data of a document. If a document has 5 fields and you need to show only 3, then
select only 3 fields from them.

The find() Method

MongoDB's find() method, explained in MongoDB Query Document accepts a second


optional parameter that is the list of fields that you want to retrieve. In MongoDB when you
execute find() method, then it displays all fields of a document. To limit this you need to set
list of fields with value 1 or 0. 1 is used to show the field while 0 is used to hide the field.

Syntax:

 Basic syntax of find() method with projection is as follows

>db.COLLECTION_NAME.find({},{KEY:1})

Example

 Consider the collection mycol has the following data

{"_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}

{"_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}

{"_id" : ObjectId(5983548781331adf45ec7), "title":"Database Overview"}

 Following example will display the title of the document while quering the document.

>db.mycol.find({},{"title":1,_id:0})

{"title":"MongoDB Overview"}

{"title":"NoSQL Overview"}

24
{"title":"Database Overview"}

Please note _id field is always displayed while executing find() method, if you don't want this
field, then you need to set it as 0

3. Sort,Skip and Limit

The sort() Method

To sort documents in MongoDB, you need to use sort() method. sort()method accepts a


document containing the list of fields along with their sorting order. To specify sorting order
1 and -1 is used. 1 is used for ascending order while -1 is used for descending order.

Syntax:

 Basic syntax of sort() method is as follows

>db.COLLECTION_NAME.find().sort({KEY:1})

Example

 Consider the collection myycol has the following data

{"_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}

{"_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}

{"_id" : ObjectId(5983548781331adf45ec7), "title":"Database Overview"}

 Following example will display the documents sorted by title in descending order.

>db.mycol.find({},{"title":1,_id:0}).sort({"title":-1})

{"title":"NoSQL Overview"}

{"title":"MongoDB Overview"}

{"title":"Database Overview"}

Please note if you don't specify the sorting preference, then sort() method will display
documents in ascending order.

The Limit() Method

To limit the records in MongoDB, you need to use limit() method. limit()method accepts one


number type argument, which is a number of documents that you want to displayed.

Syntax:

25
 Basic syntax of limit() method is as follows

>db.COLLECTION_NAME.find().limit(NUMBER)

Example

Consider the collection myycol has the following data

{"_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}

{"_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}

{"_id" : ObjectId(5983548781331adf45ec7), "title":"Database Overview"}

 Following example will display only 2 documents while quering the document.

>db.mycol.find({},{"title":1,_id:0}).limit(2)

{"title":"MongoDB Overview"}

{"title":"NoSQL Overview"}>

If you don't specify number argument in limit() method then it will display all documents
from the collection.

MongoDB Skip() Method

Apart from limit() method, there is one more method skip() which also accepts number type
argument and used to skip a number of documents.

Syntax:

 Basic syntax of skip() method is as follows

>db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)

Example:

 Following example will only display only second document.

>db.mycol.find({},{"title":1,_id:0}).limit(1).skip(1)

{"title":"NoSQL Overview"}>

Please note default value in skip() method is 0

EXPERT MODULE

26
1. Indexing

Indexes support the efficient resolution of queries. Without indexes, MongoDB must scan
every document of a collection to select those documents that match the query statement.
This scan is highly inefficient and requires the MongoDB to process a large volume of data.

Indexes are special data structures, that store a small portion of the data set in an easy to
traverse form. The index stores the value of a specific field or set of fields, ordered by the
value of the field as specified in an index.

The ensureIndex() Method

To create an index you need to use ensureIndex() method of MongoDB.

Syntax:

 Basic syntax of ensureIndex() method is as follows()

>db.COLLECTION_NAME.ensureIndex({KEY:1})

Here the key is the name of filed on which you want to create index and 1 are for ascending
order. To create an index in descending order you need to use -1.

Example

>db.mycol.ensureIndex({"title":1}) >

 In ensureIndex() method you can pass multiple fields, to create an index on multiple


fields.

>db.mycol.ensureIndex({"title":1,"description":-1}) >

 ensureIndex() method also accepts list of options (which are optional), whose list is
given below

Parameter Type Description


Builds the index in the background so that
building an index does not block other
Background  Boolean  
database activities. Specify true to build in the
background. The default value is false.
Creates a unique index so that the collection
will not accept insertion of documents where
unique Boolean the index key or keys match an existing value
in the index. Specify true to create a unique
index. The default value is false.
name String The name of the index. If unspecified,
MongoDB generates an index name by

27
concatenating the names of the indexed fields
and the sort order.
Creates a unique index on a field that may
have duplicates. MongoDB indexes only the
first occurrence of a key and removes all
dropDups Boolean documents from the collection that contain
subsequent occurrences of that key. Specify
true to create a unique index. The default
value is false.
If true, the index only references documents
with the specified field. These indexes use less
sparse Boolean space but behave differently in some
situations (particularly sorts). The default
value is false.
Specifies a value, in seconds, as a TTL to
expireAfterSecond
Integer control how long MongoDB retains
s
documents in this collection.
The index version number. The default index
index
v version depends on the version of MongoDB
version
running when creating the index.
The weight is a number ranging from 1 to
99,999 and denotes the significance of the
weights document
field relative to the other indexed fields in
terms of the score.
For a text index, the language that determines
the list of stop words and the rules for the
default_language string
stemmer and tokenizer. The default value is
English.
For a text index, specify the name of the field
in the document that contains, the language
language_override string
to override the default language. The default
value is language.

2. MongoDB Aggregation

Aggregations operations process data records and return computed results. Aggregation
operations group values from multiple documents together and can perform a variety of
operations on the grouped data to return a single result. In SQL count(*) and with the group
by is an equivalent of mongodb aggregation.

The aggregate() Method

For the aggregation in mongodb you should use aggregate() method.

Syntax:

28
 Basic syntax of aggregate() method is as follows

>db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)

Example:

 In the collection you have the following data:

{id: ObjectId(7df78ad8902c),   

title: 'MongoDB Overview',     

description: 'MongoDB is no sql database',    

by_user: 'guvi',    

url: 'https://www.guvi.in’,    

tags: ['mongodb', 'database', 'NoSQL'],    

likes: 100},

{_id: ObjectId(7df78ad8902d),   

title: 'NoSQL Overview',     

description: 'No sql database is very fast',    

by_user: 'guvi’,   

url: 'https://www.guvi.in’,    

tags: ['mongodb', 'database', 'NoSQL'],    

likes: 10},

{_id: ObjectId(7df78ad8902e),    

title: 'Neo4j Overview',     

description: 'Neo4j is no sql database',    

by_user: 'Neo4j',    

url: 'http://www.neo4j.com',    

tags: ['neo4j', 'database', 'NoSQL'],    

29
likes: 750},

Now from the above collection if you want to display a list that how many tutorials are
written by each user then you will use aggregate() method as shown below:

db.mycol.aggregate([{$group :{_id : "$by_user", num_tutorial :{$sum : 1}}}])

{"result" : [{"_id" : "guvi",          "num_tutorial" : 2       },{         "_id" : "Neo4j",


"num_tutorial" : 1       }   ],    "ok" : 1}

Sql equivalent query for the above use case will be select by_user, count(*) from mycol group
by by_user

In the above example we have grouped documents by field by_user and on each occurance


of by_user previous value of sum is incremented. There is a list available aggregation
expressions.

Expressio
Description Example
n
Sums up the defined value db.mycol.aggregate([{$group :
$sum from all documents in the {_id : "$by_user", num_tutorial :
collection. {$sum : "$likes"}}}])
Calculates the average of all db.mycol.aggregate([{$group :
$avg given values from all {_id : "$by_user", num_tutorial :
documents in the collection. {$avg : "$likes"}}}])
Gets the minimum of the db.mycol.aggregate([{$group :
$min corresponding values from all {_id : "$by_user", num_tutorial :
documents in the collection. {$min : "$likes"}}}])
Gets the maximum of the db.mycol.aggregate([{$group :
$max corresponding values from all {_id : "$by_user", num_tutorial :
documents in the collection. {$max : "$likes"}}}])
db.mycol.aggregate([{$group :
Inserts the value to an array in
$push {_id : "$by_user", url :{$push:
the resulting document.
"$url"}}}])
Inserts the value to an array in db.mycol.aggregate([{$group :
$addToSe
the resulting document but {_id : "$by_user", url :{$addToSet :
t
does not create duplicates. "$url"}}}])
Gets the first document from
the source documents
according to the grouping. db.mycol.aggregate([{$group :
$first Typically this makes only {_id : "$by_user", first_url :{$first :
sense together with some "$url"}}}])
previously applied “$sort”-
stage.
$last Gets the last document from db.mycol.aggregate([{$group :

30
the source documents
according to the grouping.
Typically this makes only {_id : "$by_user", last_url :{$last :
sense together with some "$url"}}}])
previously applied “$sort”-
stage.

3. MongoDB Backup and Restore data

Dump MongoDB Data

To create backup of database in mongodb you should use mongodumpcommand. This


command will dump all data from your server into dump directory. There are many options
available by which you can limit the amount of data or create backup of your remote server.

Syntax:

 Basic syntax of mongodump command is as follows

>mongodump

Example

Start your mongod server. Assuming that your mongod server is running on localhost and
port 27017. Now open a command prompt and go to bin directory of your mongodb instance
and type the command mongodump

 Consider the mycol collection has following data.

>mongodump

The command will connect to the server running at 127.0.0.1 and port27017 and back all data
of the server to directory /bin/dump/. Output of the command is shown below:

31
There are a list of available options that can be used with the mongodumpcommand.

This command will backup only specified database at specified path

Syntax Description Example

This commmand will


mongodump --host mongodump --host
backup all databases of
HOST_NAME --port tutorialspoint.com --port
specified mongod
PORT_NUMBER 27017
instance.

mongodump --dbpath mongodump --dbpath


DB_PATH --out   /data/db/ --out
BACKUP_DIRECTORY /data/backup/

This command will


mongodump --collection backup only specified mongodump --collection
COLLECTION --db DB_NAME collection of specified mycol --db test
database.

Restore data

To restore backup data mongodb's mongorestore command is used. This command restore all


of the data from the backup directory.

Syntax

 Basic syntax of mongo restore command is

>mongorestore

Output of the command is shown below:

32
33

You might also like