Mongodb Tutorial

Download as odg, pdf, or txt
Download as odg, pdf, or txt
You are on page 1of 54

MongoDB

Table of Contents

About the Tutorial ............................................................................................................................................... i


Audience .............................................................................................................................................................. i
Prerequisites ........................................................................................................................................................ i
Copyright & Disclaimer ........................................................................................................................................ i
Table of Contents................................................................................................................................................ ii

MONGODB .................................................................................................................................. 1

1. MongoDB - Overview ............................................................................................................................... 2

2. MongoDB - Advantages ............................................................................................................................ 4

3. MongoDB - Environment .......................................................................................................................... 5

4. MongoDB - Data Modelling .................................................................................................................... 10

5. MongoDB - Create Database .................................................................................................................. 12

6. MongoDB - Drop Database ..................................................................................................................... 14

7. MongoDB - Create Collection ................................................................................................................. 15

8. MongoDB - Drop Collection .................................................................................................................... 18

9. MongoDB - Datatypes ............................................................................................................................ 19

10. MongoDB - Insert Document .............................................................................................................. 20

11. MongoDB - Query Document ............................................................................................................. 22

12. MongoDB - Update Document ........................................................................................................... 26

13. MongoDB - Delete Document ............................................................................................................. 28

14. MongoDB - Projection ........................................................................................................................ 30

15. MongoDB - Limit Records ................................................................................................................... 31

16. MongoDB - Sort Records .................................................................................................................... 33

17. MongoDB - Indexing ........................................................................................................................... 34

18. MongoDB - Aggregation ..................................................................................................................... 36

19. MongoDB - Replication ....................................................................................................................... 40

20. MongoDB - Sharding .......................................................................................................................... 43

ii
MongoDB

21. MongoDB - Create Backup .................................................................................................................. 45

22. MongoDB - Deployment ..................................................................................................................... 48

23. MongoDB - Java.................................................................................................................................. 51

24. MongoDB - PHP .................................................................................................................................. 64

ADVANCED MONGODB ............................................................................................................. 70

25. MongoDB - Relationships ................................................................................................................... 71

26. MongoDB - Database References ....................................................................................................... 74

27. MongoDB - Covered Queries .............................................................................................................. 76

28. MongoDB - Analyzing Queries ............................................................................................................ 78

29. MongoDB - Atomic Operations ........................................................................................................... 81

30. MongoDB - Advanced Indexing .......................................................................................................... 83

31. MongoDB - Indexing Limitations ........................................................................................................ 85

32. MongoDB – ObjectId .......................................................................................................................... 86

33. MongoDB - Map Reduce ..................................................................................................................... 88

34. MongoDB - Text Search ...................................................................................................................... 91

35. MongoDB - Regular Expression........................................................................................................... 93

36. MongoDB - RockMongo...................................................................................................................... 95

37. MongoDB - GridFS .............................................................................................................................. 96

38. MongoDB - Capped Collections .......................................................................................................... 98

39. MongoDB - Auto-Increment Sequence ............................................................................................. 100

iii
MongoDB

MongoDB

1
1. MongoDB - Overview
MongoDB

MongoDB is a cross-platform, document oriented database that provides, high


performance, high availability, and easy scalability. MongoDB works on concept of
collection and document.

Database
Database is a physical container for collections. Each database gets its own set of files on
the file system. A single MongoDB server typically has multiple databases.

Collection
Collection is a group of MongoDB documents. It is the equivalent of an RDBMS table. A
collection exists within a single database. Collections do not enforce a schema. Documents
within a collection can have different fields. Typically, all documents in a collection are of
similar or related purpose.

Document
A document is a set of key-value pairs. Documents have dynamic schema. Dynamic
schema means that documents in the same collection do not need to have the same set
of fields or structure, and common fields in a collection's documents may hold different
types of data.

The following table shows the relationship of RDBMS terminology with MongoDB.

RDBMS MongoDB

Database Database

Table Collection

Tuple/Row Document

column Field

Table Join Embedded Documents

Primary Key (Default key _id provided by


Primary Key
mongodb itself)

Database Server and Client

Mysqld/Oracle mongod

mysql/sqlplus mongo

2
2. MongoDB - Advantages
MongoDB

Any relational database has a typical schema design that shows number of tables and the
relationship between these tables. While in MongoDB, there is no concept of relationship.

Advantages of MongoDB over RDBMS


 Schema less: MongoDB is a document database in which one collection holds
different documents. Number of fields, content and size of the document can differ
from one document to another.

 Structure of a single object is clear.

 No complex joins.

 Deep query-ability. MongoDB supports dynamic queries on documents using a


document-based query language that's nearly as powerful as SQL.

 Tuning.

 Ease of scale-out: MongoDB is easy to scale.

 Conversion/mapping of application objects to database objects not needed.

 Uses internal memory for storing the (windowed) working set, enabling faster
access of data.

Why Use MongoDB?


 Document Oriented Storage: Data is stored in the form of JSON style documents.
 Index on any attribute
 Replication and high availability
 Auto-sharding
 Rich queries
 Fast in-place updates
 Professional support by MongoDB

Where to Use MongoDB?


 Big Data
 Content Management and Delivery
 Mobile and Social Infrastructure
 User Data Management
 Data Hub
4
3. MongoDB - Environment
MongoDB

Let us now see how to install MongoDB on Windows.

Install MongoDB on Windows


To install MongoDB on Windows, first download the latest release of MongoDB
from http://www.mongodb.org/downloads. Make sure you get correct version of MongoDB
depending upon your Windows version. To get your Windows version, open command
prompt and execute the following command.

C:\>wmic os get osarchitecture


OSArchitecture
64-bit
C:\>

32-bit versions of MongoDB only support databases smaller than 2GB and suitable only
for testing and evaluation purposes.

Now extract your downloaded file to c:\ drive or any other location. Make sure the name
of the extracted folder is mongodb-win32-i386-[version] or mongodb-win32-x86_64-
[version]. Here [version] is the version of MongoDB download.

Next, open the command prompt and run the following command.

C:\>move mongodb-win64-* mongodb


1 dir(s) moved.
C:\>

In case you have extracted the MongoDB at different location, then go to that path by
using command cd FOOLDER/DIR and now run the above given process.

MongoDB requires a data folder to store its files. The default location for the MongoDB
data directory is c:\data\db. So you need to create this folder using the Command Prompt.
Execute the following command sequence.

C:\>md data
C:\md data\db

If you have to install the MongoDB at a different location, then you need to specify an
alternate path for \data\db by setting the path dbpath in mongod.exe. For the same,
issue the following commands.

5
MongoDB

In the command prompt, navigate to the bin directory present in the MongoDB installation
folder. Suppose my installation folder is D:\set up\mongodb

C:\Users\XYZ>d:
D:\>cd "set up"
D:\set up>cd mongodb
D:\set up\mongodb>cd bin
D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data"

This will show waiting for connections message on the console output, which indicates
that the mongod.exe process is running successfully.

Now to run the MongoDB, you need to open another command prompt and issue the
following command.

D:\set up\mongodb\bin>mongo.exe
MongoDB shell version: 2.4.6
connecting to: test
>db.test.save( { a: 1 } )
>db.test.find()
{ "_id" : ObjectId(5879b0f65a56a454), "a" : 1 }
>

This will show that MongoDB is installed and run successfully. Next time when you run
MongoDB, you need to issue only commands.

D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data"


D:\set up\mongodb\bin>mongo.exe

Install MongoDB on Ubuntu


Run the following command to import the MongoDB public GPG key −

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10

Create a /etc/apt/sources.list.d/mongodb.list file using the following command.

echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen'


| sudo tee /etc/apt/sources.list.d/mongodb.list

Now issue the following command to update the repository −

sudo apt-get update

6
MongoDB

Next install the MongoDB by using the following command −

apt-get install mongodb-10gen=2.2.3

In the above installation, 2.2.3 is currently released MongoDB version. Make sure to install
the latest version always. Now MongoDB is installed successfully.

Start MongoDB
sudo service mongodb start

Stop MongoDB
sudo service mongodb stop

Restart MongoDB
sudo service mongodb restart

To use MongoDB run the following command.

mongo

This will connect you to running MongoDB instance.

7
MongoDB

MongoDB Help
To get a list of commands, type db.help() in MongoDB client. This will give you a list of
commands as shown in the following screenshot.

8
5. MongoDB - Create Database
MongoDB

In this chapter, we will see how to create a database in MongoDB.

The use Command


MongoDB use DATABASE_NAME is used to create 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 DATABASE statement
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, use the command show dbs.

>show dbs
local 0.78125GB
test 0.23012GB

12
MongoDB

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

>db.movie.insert({"name":"tutorials point"})
>show dbs
local 0.78125GB
mydb 0.23012GB
test 0.23012GB

In MongoDB default database is test. If you didn't create any database, then collections
will be stored in test database.

13
6. MongoDB - Drop Database
MongoDB

In this chapter, we will see how to drop a database using MongoDB command.

The dropDatabase() Method


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

Syntax
Basic syntax of dropDatabase() command is as follows:

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 of available databases by using the command, show dbs.

>show dbs
local 0.78125GB
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
>

14
7. MongoDB - Create Collection
MongoDB

In this chapter, we will see how to create a collection using MongoDB.

The createCollection() 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, name is name of collection to be created. Options is a document and


is used to specify configuration of collection.

Parameter Type Description

Name String Name of the collection to be created

(Optional) Specify options about memory


Options Document
size and indexing

Options parameter is optional, so you need to specify only the name of the collection.
Following is the list of options you can use:

Field Type Description

(Optional) If true, enables a capped collection. Capped


collection is a fixed size collection that automatically
capped Boolean overwrites its oldest entries when it reaches its maximum
size. If you specify true, you need to specify size
parameter also.

(Optional) If true, automatically create index on _id field.


autoIndexID Boolean
Default value is false.

15
MongoDB

(Optional) Specifies a maximum size in bytes for a capped collection.


size number
If capped is true, then you need to specify this field also.

(Optional) Specifies the maximum number of documents allowed in the


max number
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

The 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 }
>

16
MongoDB

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


automatically, when you insert some document.

>db.tutorialspoint.insert({"name" : "tutorialspoint"})
>show collections
mycol
mycollection
system.indexes
tutorialspoint
>

17
8. MongoDB - Drop Collection
MongoDB

In this chapter, we will see how to drop a collection using MongoDB.

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
system.indexes
tutorialspoint>

Now drop the collection with the name mycollection.

>db.mycollection.drop()
true
>

Again check the list of collections into database.

>show collections
mycol
system.indexes
tutorialspoint
>

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

18
9. MongoDB - Datatypes
MongoDB

MongoDB supports many datatypes. Some of them are:

 String: This is the most commonly used datatype to store the data. String in
MongoDB must be UTF-8 valid.

 Integer: This type is used to store a numerical value. Integer can be 32 bit or 64
bit depending upon your server.

 Boolean: This type is used to store a boolean (true/ false) value.

 Double: This type is used to store floating point values.

 Min/Max Keys: This type is used to compare a value against the lowest and
highest BSON elements.

 Arrays: This type is used to store arrays or list or multiple values into one key.

 Timestamp: ctimestamp. This can be handy for recording when a document has
been modified or added.

 Object: This datatype is used for embedded documents.

 Null: This type is used to store a Null value.

 Symbol: This datatype is used identically to a string; however, it's generally


reserved for languages that use a specific symbol type.

 Date: This datatype is used to store the current date or time in UNIX time format.
You can specify your own date time by creating object of Date and passing day,
month, year into it.

 Object ID: This datatype is used to store the document’s ID.

 Binary data: This datatype is used to store binary data.

 Code: This datatype is used to store JavaScript code into the document.

 Regular expression: This datatype is used to store regular expression.

19
10. MongoDB - Insert Document
MongoDB

In this chapter, we will learn how to insert document in MongoDB collection.

The insert() Method


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

Syntax
The 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: 'tutorials point',
url: 'http://www.tutorialspoint.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100
})

Here mycol is our collection name, as created in the previous chapter. If the collection
doesn't exist in the database, then MongoDB will create this collection and then insert a
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 a single query, you can pass an array of documents in
insert() command.

20
MongoDB

Example
>db.post.insert([
{
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
by: 'tutorials point',
url: 'http://www.tutorialspoint.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100
},

{
title: 'NoSQL Database',
description: 'NoSQL database doesn't have tables',
by: 'tutorials point',
url: 'http://www.tutorialspoint.com',
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 as insert() method. If
the save() method.

21
11. MongoDB - Query Document
MongoDB

In this chapter, we will learn how to query document from MongoDB collection.

The find() Method


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

Syntax
The 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


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": "tutorials point",
"url": "http://www.tutorialspoint.com",
"tags": ["mongodb", "database", "NoSQL"],
"likes": "100"
}
>

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

22
MongoDB

RDBMS Where Clause Equivalents in MongoDB


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

RDBMS
Operati
Syntax Example Equivale
on
nt

where by
db.mycol.find({"by":"tutorials =
Equality {<key>:<value>}
point"}).pretty() 'tutorials
point'

Less {<key>:{$lt:<value db.mycol.find({"likes":{$lt:50}}).p where


Than >}} retty() likes < 50

Less where
{<key>:{$lte:<value db.mycol.find({"likes":{$lte:50}}).
Than likes <=
>}} pretty()
Equals 50

Greater {<key>:{$gt:<value db.mycol.find({"likes":{$gt:50}}). where


Than >}} pretty() likes > 50

Greater where
{<key>:{$gte:<valu db.mycol.find({"likes":{$gte:50}}).
Than likes >=
e>}} pretty()
Equals 50

where
Not {<key>:{$ne:<value db.mycol.find({"likes":{$ne:50}}).
likes !=
Equals >}} pretty()
50

AND in MongoDB

Syntax
In the find() method, if you pass multiple keys by separating them by ',' then MongoDB
treats it as AND condition. Following is the basic syntax of AND −

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

23
MongoDB

Example
Following example will show all the tutorials written by 'tutorials point' and whose title is
'MongoDB Overview'.

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


{
"_id": ObjectId(7df78ad8902c),
"title": "MongoDB Overview",
"description": "MongoDB is no sql database",
"by": "tutorials point",
"url": "http://www.tutorialspoint.com",
"tags": ["mongodb", "database", "NoSQL"],
"likes": "100"
}
>

For the above given example, equivalent where clause will be ' where by='tutorials
point' 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 $or keyword. Following
is the basic syntax of OR −

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

24
MongoDB

Example
Following example will show all the tutorials written by 'tutorials point' or whose title is
'MongoDB Overview'.

>db.mycol.find({$or:[{"by":"tutorials point"},{"title": "MongoDB


Overview"}]}).pretty()
{
"_id": ObjectId(7df78ad8902c),
"title": "MongoDB Overview",
"description": "MongoDB is no sql database",
"by": "tutorials point",
"url": "http://www.tutorialspoint.com",
"tags": ["mongodb", "database", "NoSQL"],
"likes": "100" } >

Using AND and OR Together

Example
The following 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": "tutorials point"},


{"title": "MongoDB Overview"}]}).pretty()
{
"_id": ObjectId(7df78ad8902c),
"title": "MongoDB Overview",
"description": "MongoDB is no sql database",
"by": "tutorials point",
"url": "http://www.tutorialspoint.com",
"tags": ["mongodb", "database", "NoSQL"],
"likes": "100" }
>

25
12. MongoDB - Update Document
MongoDB

MongoDB's update() and save() methods are used to update document into a collection.
The update() method updates the 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 the values in the existing document.

Syntax
The basic syntax of update() method is as follows:

>db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)

Example
Consider the mycol collection has the 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 a single document. To update multiple documents,
you need to set a parameter 'multi' to true.

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

26
MongoDB

MongoDB Save() Method


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

Syntax
The basic syntax of MongoDB save() method is −

>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":"Tutorials Point New
Topic",
"by":"Tutorials Point"
}
)
>db.mycol.find()
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"Tutorials Point New Topic",
"by":"Tutorials Point"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
>

27
13. MongoDB - Delete Document
MongoDB

In this chapter, we will learn how to delete a document using MongoDB.

The remove() Method


MongoDB's remove() method is used to remove a document from the collection.
remove() method accepts two parameters. One is deletion criteria and 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 collection has the following data.

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


{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point 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":"Tutorials Point Overview"}
>

28
MongoDB

Remove Only One


If there are multiple records and you want to delete only the first record, then set
justOne parameter in remove() method.

>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()
>

29
14. MongoDB - Projection
MongoDB

In MongoDB, projection means selecting only the 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 second
optional parameter that is 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 a list of fields with value 1 or 0. 1 is used to show the field while 0 is used to hide the
fields.

Syntax
The 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":"Tutorials Point Overview"}

Following example will display the title of the document while querying the document.

>db.mycol.find({},{"title":1,_id:0})
{"title":"MongoDB Overview"}
{"title":"NoSQL Overview"}
{"title":"Tutorials Point 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.

30
15. MongoDB - Limit Records
MongoDB

In this chapter, we will learn how to limit records using MongoDB.

The Limit() Method


To limit the records in MongoDB, you need to use limit() method. The method accepts
one number type argument, which is the number of documents that you want to be
displayed.

Syntax
The 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":"Tutorials Point Overview"}

Following example will display only two documents while querying the document.

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

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

31
MongoDB

MongoDB Skip() Method


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

Syntax
The basic syntax of skip() method is as follows:

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

Example
Following example will display only the second document.

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

Please note, the default value in skip() method is 0.

32
16. MongoDB - Sort Records
MongoDB

In this chapter, we will learn how to sort records in MongoDB.

The sort() Method


To sort documents in MongoDB, you need to use sort() method. The method accepts a
document containing a list of fields along with their sorting order. To specify sorting order
1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.

Syntax
The 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":"Tutorials Point Overview"}

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

>db.mycol.find({},{"title":1,_id:0}).sort({"title":-1})
{"title":"Tutorials Point Overview"}
{"title":"NoSQL Overview"}
{"title":"MongoDB Overview"}
>

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

33
17. MongoDB - Indexing
MongoDB

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 require 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 the index.

The ensureIndex() Method


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

Syntax
The basic syntax of ensureIndex() method is as follows().

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

Here key is the name of the file on which you want to create index and 1 is for ascending
order. To create 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 index on multiple fields.

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

ensureIndex() method also accepts list of options (which are optional). Following is the
list:

Parameter Type Description

Builds the index in the background so that


building an index does not block other database
background Boolean
activities. Specify true to build in the
background. The default value is false.

unique Boolean Creates a unique index so that the collection will


not accept insertion of documents where the
index key or keys match an existing value in the

34
MongoDB

index. Specify true to create a unique index.


The default value is false.

The name of the index. If unspecified, MongoDB


name String generates an index name by 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 documents
dropDups Boolean
from the collection that contain subsequent
occurrences of that key. Specify true to create
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 control


expireAfterSeconds Integer how long MongoDB retains documents in this
collection.

The index version number. The default index


v Index Version version depends on the version of MongoDB
running when creating the index.

The weight is a number ranging from 1 to


99,999 and denotes the significance of the field
weights Document
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 to
language_override String
override the default language. The default value
is language.

35
18. MongoDB - Aggregation
MongoDB

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 group
by is an equivalent of mongodb aggregation.

The aggregate() Method


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

Syntax
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: 'tutorials point',
url: 'http://www.tutorialspoint.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100
},
{
_id: ObjectId(7df78ad8902d)
title: 'NoSQL Overview',
description: 'No sql database is very fast',
by_user: 'tutorials point',
url: 'http://www.tutorialspoint.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 10

36
MongoDB

},
{
_id: ObjectId(7df78ad8902e)
title: 'Neo4j Overview',
description: 'Neo4j is no sql database',
by_user: 'Neo4j',
url: 'http://www.neo4j.com',
tags: ['neo4j', 'database', 'NoSQL'],
likes: 750
},

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

> db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum :


1}}}])
{
"result" : [
{
"_id" : "tutorials point",
"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.

37
MongoDB

In the above example, we have grouped documents by field by_user and on each
occurrence of by_user previous value of sum is incremented. Following is a list of available
aggregation expressions.

Expression Description Example

db.mycol.aggregate([{$group
Sums up the defined value from all : {_id : "$by_user",
$sum
documents in the collection. num_tutorial : {$sum :
"$likes"}}}])

db.mycol.aggregate([{$group
Calculates the average of all given values : {_id : "$by_user",
$avg
from all documents in the collection. num_tutorial : {$avg :
"$likes"}}}])

db.mycol.aggregate([{$group
Gets the minimum of the corresponding
: {_id : "$by_user",
$min values from all documents in the
num_tutorial : {$min :
collection.
"$likes"}}}])

db.mycol.aggregate([{$group
Gets the maximum of the corresponding
: {_id : "$by_user",
$max values from all documents in the
num_tutorial : {$max :
collection.
"$likes"}}}])

db.mycol.aggregate([{$group
Inserts the value to an array in the
$push : {_id : "$by_user", url :
resulting document.
{$push: "$url"}}}])

Inserts the value to an array in the db.mycol.aggregate([{$group


$addToSet resulting document but does not create : {_id : "$by_user", url :
duplicates. {$addToSet : "$url"}}}])

Gets the first document from the source


documents according to the grouping. db.mycol.aggregate([{$group
$first Typically this makes only sense together : {_id : "$by_user", first_url :
with some previously applied “$sort”- {$first : "$url"}}}])
stage.

Gets the last document from the source


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

38
MongoDB

Pipeline Concept
In UNIX command, shell pipeline means the possibility to execute an operation on some
input and use the output as the input for the next command and so on. MongoDB also
supports same concept in aggregation framework. There is a set of possible stages and
each of those is taken as a set of documents as an input and produces a resulting set of
documents (or the final resulting JSON document at the end of the pipeline). This can then
in turn be used for the next stage and so on.

Following are the possible stages in aggregation framework:

 $project: Used to select some specific fields from a collection.

 $match: This is a filtering operation and thus this can reduce the amount of
documents that are given as input to the next stage.

 $group: This does the actual aggregation as discussed above.

 $sort: Sorts the documents.

 $skip: With this, it is possible to skip forward in the list of documents for a given
amount of documents.

 $limit: This limits the amount of documents to look at, by the given number
starting from the current positions.

 $unwind: This is used to unwind document that are using arrays. When using an
array, the data is kind of pre-joined and this operation will be undone with this to
have individual documents again. Thus with this stage we will increase the amount
of documents for the next stage.

39
23. MongoDB - Java
MongoDB

In this chapter, we will learn how to set up MongoDB JDBC driver.

Installation
Before you start using MongoDB in your Java programs, you need to make sure that you
have MongoDB JDBC driver and Java set up on the machine. You can check Java tutorial
for Java installation on your machine. Now, let us check how to set up MongoDB JDBC
driver.

 You need to download the jar from the path Download mongo.jar. Make sure to
download the latest release of it.

 You need to include the mongo.jar into your classpath.

Connect to Database
To connect database, you need to specify the database name, if the database doesn't exist
then MongoDB creates it automatically.

Following is the code snippet to connect to the database:

import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;

import com.mongodb.ServerAddress;
import java.util.Arrays;

public class MongoDBJDBC {

public static void main( String args[] ) {

51
MongoDB

try{

// To connect to mongodb server


MongoClient mongoClient = new MongoClient( "localhost" , 27017 );

// Now connect to your databases


DB db = mongoClient.getDB( "test" );
System.out.println("Connect to database successfully");
boolean auth = db.authenticate(myUserName, myPassword);
System.out.println("Authentication: "+auth);

}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}

Now, let's compile and run the above program to create our database test. You can change
your path as per your requirement. We are assuming the current version of JDBC driver
mongo-2.10.1.jar is available in the current path.

$javac MongoDBJDBC.java
$java -classpath ".:mongo-2.10.1.jar" MongoDBJDBC
Connect to database successfully
Authentication: true

If you are going to use Windows machine, then you can compile and run your code as
follows −

$javac MongoDBJDBC.java
$java -classpath ".;mongo-2.10.1.jar" MongoDBJDBC
Connect to database successfully
Authentication: true

Value of auth will be true, if the username and password are valid for the selected
database.

52
MongoDB

Create a Collection
To create a collection, createCollection() method of com.mongodb.DB class is used.

Following is the code snippet to create a collection −

import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;

import com.mongodb.ServerAddress;
import java.util.Arrays;

public class MongoDBJDBC {

public static void main( String args[] ) {

try{

// To connect to mongodb server


MongoClient mongoClient = new MongoClient( "localhost" , 27017 );

// Now connect to your databases


DB db = mongoClient.getDB( "test" );
System.out.println("Connect to database successfully");

boolean auth = db.authenticate(myUserName, myPassword);


System.out.println("Authentication: "+auth);

53
MongoDB

DBCollection coll = db.createCollection("mycol");


System.out.println("Collection created successfully");
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}

When program is compiled and executed, it will produce the following result −

Connect to database successfully


Authentication: true
Collection created successfully

Getting/Selecting a Collection
To get/select a collection from the database, getCollection() method of
com.mongodb.DBCollection class is used.

Code snippets to get/select a collection −

import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;

import com.mongodb.ServerAddress;
import java.util.Arrays;

public class MongoDBJDBC {

public static void main( String args[] ) {


try{

54
MongoDB

// To connect to mongodb server


MongoClient mongoClient = new MongoClient( "localhost" , 27017 );

// Now connect to your databases


DB db = mongoClient.getDB( "test" );
System.out.println("Connect to database successfully");

boolean auth = db.authenticate(myUserName, myPassword);


System.out.println("Authentication: "+auth);

DBCollection coll = db.createCollection("mycol");


System.out.println("Collection created successfully");

DBCollection coll = db.getCollection("mycol");


System.out.println("Collection mycol selected successfully");
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}

When the program is compiled and executed, it will produce the following result −

Connect to database successfully


Authentication: true
Collection created successfully
Collection mycol selected successfully

55
MongoDB

Insert a Document
To insert a document into MongoDB, insert() method of
com.mongodb.DBCollection class is used.

Following is the code snippet to insert a document −

import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays;

public class MongoDBJDBC {


public static void main( String args[] ) {
try{

// To connect to mongodb server


MongoClient mongoClient = new MongoClient( "localhost" , 27017 );

// Now connect to your databases


DB db = mongoClient.getDB( "test" );
System.out.println("Connect to database successfully");

boolean auth = db.authenticate(myUserName, myPassword);


System.out.println("Authentication: "+auth);
DBCollection coll = db.getCollection("mycol");
System.out.println("Collection mycol selected successfully");

56
MongoDB

BasicDBObject doc = new BasicDBObject("title", "MongoDB").


append("description", "database").
append("likes", 100).
append("url", "http://www.tutorialspoint.com/mongodb/").
append("by", "tutorials point");

coll.insert(doc);
System.out.println("Document inserted successfully");
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}

When the program is compiled and executed, it will produce the following result −

Connect to database successfully


Authentication: true
Collection mycol selected successfully
Document inserted successfully

Retrieve All Documents


To select all documents from the collection, find() method of
com.mongodb.DBCollection class is used. This method returns a cursor, so you need
to iterate this cursor.

Following is the code snippet to select all documents −

import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;

57
MongoDB

import com.mongodb.ServerAddress;
import java.util.Arrays;

public class MongoDBJDBC {

public static void main( String args[] ) {

try{

// To connect to mongodb server


MongoClient mongoClient = new MongoClient( "localhost" , 27017 );

// Now connect to your databases


DB db = mongoClient.getDB( "test" );
System.out.println("Connect to database successfully");
boolean auth = db.authenticate(myUserName, myPassword);
System.out.println("Authentication: "+auth);

DBCollection coll = db.getCollection("mycol");


System.out.println("Collection mycol selected successfully");

DBCursor cursor = coll.find();


int i = 1;

while (cursor.hasNext()) {
System.out.println("Inserted Document: "+i);
System.out.println(cursor.next());
i++;
}
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}

58
MongoDB

When the program is compiled and executed, it will produce the following result −

Connect to database successfully


Authentication: true
Collection mycol selected successfully
Inserted Document: 1
{
"_id" : ObjectId(7df78ad8902c),
"title": "MongoDB",
"description": "database",
"likes": 100,
"url": "http://www.tutorialspoint.com/mongodb/",
"by": "tutorials point"
}

Update Document
To update a document from the collection, update() method of
com.mongodb.DBCollection class is used.

Following is the code snippet to select the first document −

import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;

import com.mongodb.ServerAddress;
import java.util.Arrays;

59
MongoDB

public class MongoDBJDBC {

public static void main( String args[] ) {

try{

// To connect to mongodb server


MongoClient mongoClient = new MongoClient( "localhost" , 27017 );

// Now connect to your databases


DB db = mongoClient.getDB( "test" );
System.out.println("Connect to database successfully");

boolean auth = db.authenticate(myUserName, myPassword);


System.out.println("Authentication: "+auth);

DBCollection coll = db.getCollection("mycol");


System.out.println("Collection mycol selected successfully");

DBCursor cursor = coll.find();

while (cursor.hasNext()) {
DBObject updateDocument = cursor.next();
updateDocument.put("likes","200")
col1.update(updateDocument);
}

60
MongoDB

System.out.println("Document updated successfully");


cursor = coll.find();

int i = 1;

while (cursor.hasNext()) {
System.out.println("Updated Document: "+i);
System.out.println(cursor.next());
i++;
}

}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}

When a program is compiled and executed, it will produce the following result −

Connect to database successfully


Authentication: true
Collection mycol selected successfully
Document updated successfully
Updated Document: 1
{ "_id" : ObjectId(7df78ad8902c),
"title": "MongoDB",
"description": "database",
"likes": 100,
"url": "http://www.tutorialspoint.com/mongodb/",
"by": "tutorials point"}

61
MongoDB

Delete First Document


To delete the first document from the collection, you need to first select the documents
using findOne() method and then remove method of
com.mongodb.DBCollection class.

Following is the code snippets to delete the first document −

import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;

import com.mongodb.ServerAddress;
import java.util.Arrays;

public class MongoDBJDBC {

public static void main( String args[] ) {

try{

// To connect to mongodb server


MongoClient mongoClient = new MongoClient( "localhost" , 27017 );

// Now connect to your databases


DB db = mongoClient.getDB( "test" );
System.out.println("Connect to database successfully");

boolean auth = db.authenticate(myUserName, myPassword);


System.out.println("Authentication: "+auth);

62
MongoDB

DBCollection coll = db.getCollection("mycol");


System.out.println("Collection mycol selected successfully");

DBObject myDoc = coll.findOne();


col1.remove(myDoc);
DBCursor cursor = coll.find();
int i = 1;

while (cursor.hasNext()) {
System.out.println("Inserted Document: "+i);
System.out.println(cursor.next());
i++;
}

System.out.println("Document deleted successfully");


}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}

When the program is compiled and executed, it will produce the following result −

Connect to database successfully


Authentication: true
Collection mycol selected successfully
Document deleted successfully

Remaining MongoDB methods save(), limit(), skip(), sort() etc. works same as
explained in the subsequent tutorial.

63
MongoDB

>db.products.findAndModify({
query:{_id:2,product_available:{$gt:0}},
update:{
$inc:{product_available:-1},
$push:{product_bought_by:{customer:"rob",date:"9-Jan-2014"}}
}
})

Our approach of embedded document and using findAndModify query makes sure that the
product purchase information is updated only if it the product is available. And the whole
of this transaction being in the same query, is atomic.

In contrast to this, consider the scenario where we may have kept the product availability
and the information on who has bought the product, separately. In this case, we will first
check if the product is available using the first query. Then in the second query we will
update the purchase information. However, it is possible that between the executions of
these two queries, some other user has purchased the product and it is no more available.
Without knowing this, our second query will update the purchase information based on the
result of our first query. This will make the database inconsistent because we have sold a
product which is not available.

82
39. MongoDB - Auto-Increment Sequence
MongoDB

MongoDB does not have out-of-the-box auto-increment functionality, like SQL databases.
By default, it uses the 12-byte ObjectId for the _id field as the primary key to uniquely
identify the documents. However, there may be scenarios where we may want the _id field
to have some auto-incremented value other than the ObjectId.

Since this is not a default feature in MongoDB, we will programmatically achieve this
functionality by using a counters collection as suggested by the MongoDB documentation.

Using Counter Collection


Consider the following products document. We want the _id field to be an auto-
incremented integer sequence starting from 1,2,3,4 upto n.

{
"_id":1,
"product_name": "Apple iPhone",
"category": "mobiles"
}

For this, create a counters collection, which will keep track of the last sequence value for
all the sequence fields.

>db.createCollection("counters")

Now, we will insert the following document in the counters collection with productid as
its key −

{
"_id":"productid",
"sequence_value": 0
}

The field sequence_value keeps track of the last value of the sequence.

Use the following code to insert this sequence document in the counters collection −

>db.counters.insert({_id:"productid",sequence_value:0})

100
MongoDB

Creating Javascript Function


Now, we will create a function getNextSequenceValue which will take the sequence
name as its input, increment the sequence number by 1 and return the updated sequence
number. In our case, the sequence name is productid.

>function getNextSequenceValue(sequenceName){

var sequenceDocument = db.counters.findAndModify({


query:{_id: sequenceName },
update: {$inc:{sequence_value:1}},
new:true
});

return sequenceDocument.sequence_value;
}

Using the Javascript Function


We will now use the function getNextSequenceValue while creating a new document and
assigning the returned sequence value as document's _id field.

Insert two sample documents using the following code −

>db.products.insert({
"_id":getNextSequenceValue("productid"),
"product_name":"Apple iPhone",
"category":"mobiles"
})

>db.products.insert({
"_id":getNextSequenceValue("productid"),
"product_name":"Samsung S3",
"category":"mobiles"
})

As you can see, we have used the getNextSequenceValue function to set value for the _id
field.

To verify the functionality, let us fetch the documents using find command −

>db.prodcuts.find()

101
MongoDB

The above query returned the following documents having the auto-incremented _id field

{ "_id" : 1, "product_name" : "Apple iPhone", "category" : "mobiles"}

{ "_id" : 2, "product_name" : "Samsung S3", "category" : "mobiles" }

102

You might also like