Introduction to MongoDB
(https://www.youtube.com/watch?v=oSIv-E60NiU)
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 Primary Key (Default key _id provided by MongoDB itself)
Database Server and Client
mysqld/Oracle mongod
mysql/sqlplus mongo
History of MongoDB
The initial development of MongoDB began in 2007 when the company was building a platform as a service
similar to window azure.
Window azure is a cloud computing platform and infrastructure, created by Microsoft, to build, deploy and
manage applications and service through a global network.
MongoDB was developed by a NewYork based organization named 10gen which is now known as
MongoDB Inc. It was initially developed as a PAAS (Platform as a Service). Later in 2009, it is introduced
in the market as an open source database server that was maintained and supported by MongoDB Inc.
The first ready production of MongoDB has been considered from version 1.4 which was released in March
2010. MongoDB2.4.9 was the latest and stable version which was released on January 10, 2014.
Purpose of Building MongoDB
It may be a very genuine question that - "what was the need of MongoDB although there were many
databases in action?" All the modern applications require big data, fast features development, flexible
deployment, and the older database systems not competent enough, so the MongoDB was needed.
The primary purpose of building MongoDB is:
o Scalability
o Performance
o High Availability
o Scaling from single server deployments to large, complex multi-site architectures.
o Key points of MongoDB
o Develop Faster
o Deploy Easier
o Scale Bigger
What is Document based storage?
A Document is nothing but a data structure with name-value pairs like in JSON. It is very easy to
map any custom Object of any programming language with a MongoDB Document. For
example: Student object has attributes name, rollno and subjects, where subjects is a List.
Document for Student in MongoDB will be like:
{
name : "Stduytonight",
rollno : 1,
subjects : ["C Language", "C++", "Core Java"]
}
We can see, Documents are actually JSON representation of custom Objects. Also, excessive
JOINS can be avoided by saving data in form of Arrays and Documents(Embedded) inside a
Document.
Sample Document
Following example shows the document structure of a blog site, which is simply a comma
separated key value pair.
{
_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,
comments: [
{
user:'user1',
message: 'My first comment',
dateCreated: new Date(2011,1,20,2,15),
like: 0
},
{
user:'user2',
message: 'My second comments',
dateCreated: new Date(2011,1,25,7,45),
like: 5
}
]
}
_id is a 12 bytes hexadecimal number which assures the uniqueness of every document. You can provide _id
while inserting the document. If you don’t provide then MongoDB provides a unique id for every document.
These 12 bytes first 4 bytes for the current timestamp, next 3 bytes for machine id, next 2 bytes for process
id of MongoDB server and remaining 3 bytes are simple incremental VALUE.
MongoDB is a document-oriented database. It is a key feature of MongoDB. It offers a document-oriented
storage. It is very simple you can program it easily. MongoDB stores data as documents, so it is known as
document-oriented database.
FirstName = "John",
Address = "Detroit",
Spouse = [{Name: "Angela"}].
FirstName ="John",
Address = "Wick"
There are two different documents (separated by ".").
Storing data in this manner is called as document-oriented database.
Mongo DB falls into a class of databases that calls Document Oriented Databases. There is also a
broad category of database known as No SQL Databases.
Features of MongoDB
These are some important features of MongoDB:
1. Support ad hoc queries
In MongoDB, you can search by field, range query and it also supports regular expression searches.
MongoDB provides high performance. Input/Output operations are lesser than relational databases
due to support of embedded documents(data models) and Select queries are also faster as Indexes in
MongoDB supports faster queries.
2. Indexing
You can index any field in a document.
3. Replication
MongoDB supports Master Slave replication. Feature of MongoDB leads to High Availability. It
provides an automatic failover mechanism, as data is restored through backup(replica) copy if
server fails. A master can perform Reads and Writes and a Slave copies data from the master and
can only be used for reads or back up (not writes)
4. Duplication of data
MongoDB can run over multiple servers. The data is duplicated to keep the system up and also
keep its running condition in case of hardware failure.
5. Load balancing
It has an automatic load balancing configuration because of data placed in shards.
6. Supports map reduce and aggregation tools.
7. Uses JavaScript instead of Procedures.
8. It is a schema-less database written in C++.
9. Provides high performance.
10. Stores files of any size easily without complicating your stack.
11. Easy to administer in the case of failures.
Overview of MongoDB
MongoDB advantages over RDBMS
In recent days, MongoDB is a new and popularly used database. It is a document based, non-
relational database provider.
Although it is 100 times faster than the traditional database but it is early to say that it will broadly
replace the traditional RDBMS. But it may be very useful in term to gain performance and
scalability.
A 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.
MongoDB Advantages
o MongoDB is schema less. It is a document database in which one collection holds different
documents.
o There may be difference between number of fields, content and size of the document from one to
other.
o Structure of a single object is clear in MongoDB.
o There are no complex joins in MongoDB.
o MongoDB provides the facility of deep query because it supports a powerful dynamic query on
documents.
o It is very easy to scale.
o It uses internal memory for storing working sets and this is the reason of its fast access.
Distinctive features of MongoDB
o Easy to use
o Light Weight
o Extremely faster than RDBMS
Where MongoDB should be used
o Big and complex data
o Mobile and social infrastructure
o Content management and delivery
o User data management
o Data hub
Performance analysis of MongoDB and RDBMS
o In relational database (RDBMS) tables are using as storing elements, while in MongoDB collection
is used.
o In the RDBMS, we have multiple schema and in each schema we create tables to store data while,
MongoDB is a document oriented database in which data is written in BSON format which is a
JSON like format.
o MongoDB is almost 100 times faster than traditional database systems.
MongoDB Datatypes
Following is a list of usable data types in MongoDB.
• 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.
Data Modelling in MongoDB
Data in MongoDB has a flexible schema.documents in the same collection. They do not need to
have the same set of fields or structure Common fields in a collection’s documents may hold
different types of data.
Data Model Design
MongoDB provides two types of data models: — Embedded data model and Normalized data
model. Based on the requirement, you can use either of the models while preparing your document.
Embedded Data Model
In this model, you can have (embed) all the related data in a single document, it is also known as
de-normalized data model.
For example, assume we are getting the details of employees in three different documents namely,
Personal_details, Contact and, Address, you can embed all the three documents in a single one as
shown below −
{
_id: ,
Emp_ID: "10025AE336"
Personal_details:{
First_Name: "Radhika",
Last_Name: "Sharma",
Date_Of_Birth: "1995-09-26"
},
Contact: {
e-mail: "radhika_sharma.123@gmail.com",
phone: "9848022338"
},
Address: {
city: "Hyderabad",
Area: "Madapur",
State: "Telangana"
}
}
Normalized Data Model
In this model, you can refer the sub documents in the original document, using references. For
example, you can re-write the above document in the normalized model as:
Employee:
{
_id: <ObjectId101>,
Emp_ID: "10025AE336"
}
Personal_details:
{
_id: <ObjectId102>,
empDocID: " ObjectId101",
First_Name: "Radhika",
Last_Name: "Sharma",
Date_Of_Birth: "1995-09-26"
}
Contact:
{
_id: <ObjectId103>,
empDocID: " ObjectId101",
e-mail: "radhika_sharma.123@gmail.com",
phone: "9848022338"
}
Address:
{
_id: <ObjectId104>,
empDocID: " ObjectId101",
city: "Hyderabad",
Area: "Madapur",
State: "Telangana"
}
Considerations while designing Schema in MongoDB
• Design your schema according to user requirements.
• Combine objects into one document if you will use them together. Otherwise separate them
(but make sure there should not be need of joins).
• Duplicate the data (but limited) because disk space is cheap as compare to compute time.
• Do joins while write, not on read.
• Optimize your schema for most frequent use cases.
• Do complex aggregation in the schema.
For example:
let us take an example of a client who needs a database design for his website. His website has the
following requirements:
Every post is distinct (contains unique title, description and url).
Every post can have one or more tags.
Every post has the name of its publisher and total number of likes.
Each post can have zero or more comments and the comments must contain user name, message,
data-time and likes.
For the above requirement, a minimum of three tables are required in RDBMS.
But in MongoDB, schema design will have one collection post and has the following structure:
{
_id: POST_ID
title: TITLE_OF_POST,
description: POST_DESCRIPTION,
by: POST_BY,
url: URL_OF_POST,
tags: [TAG1, TAG2, TAG3],
likes: TOTAL_LIKES,
comments: [
{
user: 'COMMENT_BY',
message: TEXT,
datecreated: DATE_TIME,
like: LIKES
},
{
user: 'COMMENT_BY',
message: TEST,
dateCreated: DATE_TIME,
like: LIKES
}}}
So while showing the data, in RDBMS you need to join three tables and in MongoDB, data will be
shown from one collection only.
MongoDB - Create Database
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 use 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
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.
MongoDB - Drop Database
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
>
MongoDB - Create Collection
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
Options Document (Optional) Specify options about memory 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 overwrites its oldest entries
capped Boolean
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.s Default
autoIndexId Boolean
value is false.
(Optional) Specifies a maximum size in bytes for a capped
size number collection. If capped is true, then you need to specify this field
also.
(Optional) Specifies the maximum number of documents allowed in
max number
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
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" : 0,
"errmsg" : "BSON field 'create.autoIndexID' is an unknown field.",
"code" : 40415,
"codeName" : "Location40415"
}
>
In MongoDB, you don't need to create collection. MongoDB creates collection automatically, when
you insert some document.
>db.tutorialspoint.insert({"name" : "tutorialspoint"}),
WriteResult({ "nInserted" : 1 })
>show collections
mycol
mycollection
system.indexes
tutorialspoint
>
MongoDB - 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
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.
MongoDB - Update Document
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(SELECTION_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'}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
>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})
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 shown below −
>db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})
Example
Following example will replace the document with the _id '5983548781331adf45ec5'.
>db.mycol.save(
{
"_id" : ObjectId("507f191e810c19729de860ea"),
"title":"Tutorials Point New Topic",
"by":"Tutorials Point"
}
)
WriteResult({
"nMatched" : 0,
"nUpserted" : 1,
"nModified" : 0,
"_id" : ObjectId("507f191e810c19729de860ea")
})
>db.mycol.find()
{ "_id" : ObjectId("507f191e810c19729de860e6"), "title":"Tutorials Point New Topic",
"by":"Tutorials Point"}
{ "_id" : ObjectId("507f191e810c19729de860e6"), "title":"NoSQL Overview"}
{ "_id" : ObjectId("507f191e810c19729de860e6"), "title":"Tutorials Point Overview"}
>
MongoDB findOneAndUpdate() method
The findOneAndUpdate() method updates the values in the existing document.
Syntax
The basic syntax of findOneAndUpdate() method is as follows −
>db.COLLECTION_NAME.findOneAndUpdate(SELECTIOIN_CRITERIA, UPDATED_DATA)
Example
Assume we have created a collection named empDetails and inserted three documents in it as
shown below −
> db.empDetails.insertMany(
[
{
First_Name: "Radhika",
Last_Name: "Sharma",
Age: "26",
e_mail: "radhika_sharma.123@gmail.com",
phone: "9000012345"
},
{
First_Name: "Rachel",
Last_Name: "Christopher",
Age: "27",
e_mail: "Rachel_Christopher.123@gmail.com",
phone: "9000054321"
},
{
First_Name: "Fathima",
Last_Name: "Sheik",
Age: "24",
e_mail: "Fathima_Sheik.123@gmail.com",
phone: "9000054321"
}
]
)
Following example updates the age and email values of the document with name 'Radhika'.
> db.empDetails.findOneAndUpdate(
{First_Name: 'Radhika'},
{ $set: { Age: '30',e_mail: 'radhika_newemail@gmail.com'}}
)
{
"_id" : ObjectId("5dd6636870fb13eec3963bf5"),
"First_Name" : "Radhika",
"Last_Name" : "Sharma",
"Age" : "30",
"e_mail" : "radhika_newemail@gmail.com",
"phone" : "9000012345"
}
MongoDB updateOne() method
This methods updates a single document which matches the given filter.
Syntax
The basic syntax of updateOne() method is as follows −
>db.COLLECTION_NAME.updateOne(<filter>, <update>)
Example
> db.empDetails.updateOne(
{First_Name: 'Radhika'},
{ $set: { Age: '30',e_mail: 'radhika_newemail@gmail.com'}}
)
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 0 }
>
MongoDB updateMany() method
The updateMany() method updates all the documents that matches the given filter.
Syntax
The basic syntax of updateMany() method is as follows −
>db.COLLECTION_NAME.update(<filter>, <update>)
Example
> db.empDetails.updateMany(
{Age:{ $gt: "25" }},
{ $set: { Age: '00'}}
)
{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }
You can see the updated values if you retrieve the contents of the document using the find method
as shown below −
> db.empDetails.find()
{ "_id" : ObjectId("5dd6636870fb13eec3963bf5"), "First_Name" : "Radhika", "Last_Name" :
"Sharma", "Age" : "00", "e_mail" : "radhika_newemail@gmail.com", "phone" : "9000012345" }
{ "_id" : ObjectId("5dd6636870fb13eec3963bf6"), "First_Name" : "Rachel", "Last_Name" :
"Christopher", "Age" : "00", "e_mail" : "Rachel_Christopher.123@gmail.com", "phone" :
"9000054321" }
{ "_id" : ObjectId("5dd6636870fb13eec3963bf7"), "First_Name" : "Fathima", "Last_Name" : "Sheik",
"Age" : "24", "e_mail" : "Fathima_Sheik.123@gmail.com", "phone" : "9000054321" }
>
MongoDB - Delete Document
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("507f191e810c19729de860e1"), title: "MongoDB Overview"},
{_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"},
{_id : ObjectId("507f191e810c19729de860e3"), title: "Tutorials Point Overview"}
Following example will remove all the documents whose title is 'MongoDB Overview'.
>db.mycol.remove({'title':'MongoDB Overview'})
WriteResult({"nRemoved" : 1})
> db.mycol.find()
{"_id" : ObjectId("507f191e810c19729de860e2"), "title" : "NoSQL Overview" }
{"_id" : ObjectId("507f191e810c19729de860e3"), "title" : "Tutorials Point Overview" }
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({})
WriteResult({ "nRemoved" : 2 })
> db.mycol.find()
>
MongoDB - Query Document
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.
Example
Assume we have created a collection named mycol as −
> use sampleDB
switched to db sampleDB
> db.createCollection("mycol")
{ "ok" : 1 }
>
And inserted 3 documents in it using the insert() method as shown below −
> db.mycol.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
}
]
}
])
Following method retrieves all the documents in the collection −
> db.mycol.find()
{ "_id" : ObjectId("5dd4e2cc0821d3b44607534c"), "title" : "MongoDB Overview", "description" :
"MongoDB is no SQL database", "by" : "tutorials point", "url" : "http://www.tutorialspoint.com", "tags"
: [ "mongodb", "database", "NoSQL" ], "likes" : 100 }
{ "_id" : ObjectId("5dd4e2cc0821d3b44607534d"), "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" : ISODate("2013-12-09T21:05:00Z"), "like" : 0 } ] }
>
The pretty() Method
To display the results in a formatted way, you can use pretty() method.
Syntax
>db.COLLECTION_NAME.find().pretty()
Example
Following example retrieves all the documents from the collection named mycol and arranges them
in an easy-to-read format.
> db.mycol.find().pretty()
{
"_id" : ObjectId("5dd4e2cc0821d3b44607534c"),
"title" : "MongoDB Overview",
"description" : "MongoDB is no SQL database",
"by" : "tutorials point",
"url" : "http://www.tutorialspoint.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
{
"_id" : ObjectId("5dd4e2cc0821d3b44607534d"),
"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" : ISODate("2013-12-09T21:05:00Z"),
"like" : 0
}
]
}
The findOne() method
Apart from the find() method, there is findOne() method, that returns only one document.
Syntax
>db.COLLECTIONNAME.findOne()
Example
Following example retrieves the document with title MongoDB Overview.
> db.mycol.findOne({title: "MongoDB Overview"})
{
"_id" : ObjectId("5dd6542170fb13eec3963bf0"),
"title" : "MongoDB Overview",
"description" : "MongoDB is no SQL database",
"by" : "tutorials point",
"url" : "http://www.tutorialspoint.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
RDBMS Where Clause Equivalents in MongoDB
To query the document on the basis of some condition, you can use following operations.
Operation Syntax Example RDBMS
Equivalent
Equality {<key>:{$eg;<value>}} db.mycol.find({"by":"tutorials where by =
point"}).pretty() 'tutorials
point'
Less Than {<key>:{$lt:<value>}} db.mycol.find({"likes":{$lt:50}}).pretty() where likes
< 50
Less Than {<key>:{$lte:<value>}} db.mycol.find({"likes":{$lte:50}}).pretty() where likes
Equals <= 50
Greater {<key>:{$gt:<value>}} db.mycol.find({"likes":{$gt:50}}).pretty() where likes
Than > 50
Greater {<key>:{$gte:<value>}} db.mycol.find({"likes":{$gte:50}}).pretty() where likes
Than >= 50
Equals
Not {<key>:{$ne:<value>}} db.mycol.find({"likes":{$ne:50}}).pretty() where likes
Equals != 50
Values in {<key>:{$in:[<value1>, db.mycol.find({"name":{$in:["Raj", Where
an array <value2>,……<valueN>]}} "Ram", "Raghu"]}}).pretty() name
matches
any of the
value in
:["Raj",
"Ram",
"Raghu"]
Values not {<key>:{$nin:<value>}} db.mycol.find({"name":{$nin:["Ramu", Where
in an array "Raghav"]}}).pretty() name
values is
not in the
array
:["Ramu",
"Raghav"]
or, doesn’t
exist at all
AND in MongoDB
Syntax
To query documents based on the AND condition, you need to use $and keyword. Following is the
basic syntax of AND −
>db.mycol.find({ $and: [ {<key1>:<value1>}, { <key2>:<value2>} ] })
Example
Following example will show all the tutorials written by 'tutorials point' and whose title is
'MongoDB Overview'.
> db.mycol.find({$and:[{"by":"tutorials point"},{"title": "MongoDB Overview"}]}).pretty()
{
"_id" : ObjectId("5dd4e2cc0821d3b44607534c"),
"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()
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 10 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"
}
>
NOR in MongoDB
Syntax
To query documents based on the NOT condition, you need to use $not keyword. Following is the
basic syntax of NOT −
>db.COLLECTION_NAME.find(
{
$not: [
{key1: value1}, {key2:value2}
]
}
)
Example
Assume we have inserted 3 documents in the collection empDetails as shown below −
db.empDetails.insertMany(
[
{
First_Name: "Radhika",
Last_Name: "Sharma",
Age: "26",
e_mail: "radhika_sharma.123@gmail.com",
phone: "9000012345"
},
{
First_Name: "Rachel",
Last_Name: "Christopher",
Age: "27",
e_mail: "Rachel_Christopher.123@gmail.com",
phone: "9000054321"
},
{
First_Name: "Fathima",
Last_Name: "Sheik",
Age: "24",
e_mail: "Fathima_Sheik.123@gmail.com",
phone: "9000054321"
}
]
)
Following example will retrieve the document(s) whose first name is not "Radhika" and last name
is not "Christopher"
> db.empDetails.find(
{
$nor:[
40
{"First_Name": "Radhika"},
{"Last_Name": "Christopher"}
]
}
).pretty()
{
"_id" : ObjectId("5dd631f270fb13eec3963bef"),
"First_Name" : "Fathima",
"Last_Name" : "Sheik",
"Age" : "24",
"e_mail" : "Fathima_Sheik.123@gmail.com",
"phone" : "9000054321"
}
NOT in MongoDB
Syntax
To query documents based on the NOT condition, you need to use $not keyword following is the
basic syntax of NOT −
>db.COLLECTION_NAME.find(
{
$NOT: [
{key1: value1}, {key2:value2}
]
}
).pretty()
Example
Following example will retrieve the document(s) whose age is not greater than 25
> db.empDetails.find( { "Age": { $not: { $gt: "25" } } } )
{
"_id" : ObjectId("5dd6636870fb13eec3963bf7"),
"First_Name" : "Fathima",
"Last_Name" : "Sheik",
"Age" : "24",
"e_mail" : "Fathima_Sheik.123@gmail.com",
"phone" : "9000054321"
}
MongoDB - 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 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 createIndex() Method
To create an index, you need to use createIndex() method of MongoDB.
Syntax
The basic syntax of createIndex() method is as follows().
>db.COLLECTION_NAME.createIndex({KEY:1})
Here key is the name of the field 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.createIndex({"title":1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
>
In createIndex() method you can pass multiple fields, to create index on multiple fields.
>db.mycol.createIndex({"title":1,"description":-1})
>
This 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
background Boolean not block other 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 the index key or keys match an
unique Boolean
existing value in the index. Specify true to create a unique index.
The default value is false.
The name of the index. If unspecified, MongoDB generates an
name string index name by concatenating the names of the indexed fields and
the sort order.
If true, the index only references documents with the specified
sparse Boolean field. These indexes use less space but behave differently in some
situations (particularly sorts). The default value is false.
Specifies a value, in seconds, as a TTL to control how long
expireAfterSeconds integer
MongoDB retains documents in this collection.
The weight is a number ranging from 1 to 99,999 and denotes the
weights document significance of the field relative to the other indexed fields in
terms of the score.
For a text index, the language that determines the list of stop
default_language string words and the rules for the stemmer and tokenizer. The default
value is English.
For a text index, specify the name of the field in the document that
language_override string contains, the language to override the default language. The
default value is language.
The dropIndex() method
You can drop a particular index using the dropIndex() method of MongoDB.
Syntax
The basic syntax of DropIndex() method is as follows().
>db.COLLECTION_NAME.dropIndex({KEY:1})
Here, "key" is the name of the file on which you want to remove an existing index. Instead of the
index specification document (above syntax), you can also specify the name of the index directly
as:
dropIndex("name_of_the_index")
Example
> db.mycol.dropIndex({"title":1})
{
"ok" : 0,
"errmsg" : "can't find index with key: { title: 1.0 }",
"code" : 27,
"codeName" : "IndexNotFound"
}
The dropIndexes() method
This method deletes multiple (specified) indexes on a collection.
Syntax
The basic syntax of DropIndexes() method is as follows() −
>db.COLLECTION_NAME.dropIndexes()
Example
Assume we have created 2 indexes in the named mycol collection as shown below −
> db.mycol.createIndex({"title":1,"description":-1})
Following example removes the above created indexes of mycol −
>db.mycol.dropIndexes({"title":1,"description":-1})
{ "nIndexesWas" : 2, "ok" : 1 }
>
The getIndexes() method
This method returns the description of all the indexes int the collection.
Syntax
Following is the basic syntax od the getIndexes() method −
db.COLLECTION_NAME.getIndexes()
Example
Assume we have created 2 indexes in the named mycol collection as shown below −
> db.mycol.createIndex({"title":1,"description":-1})
Following example retrieves all the indexes in the collection mycol −
> db.mycol.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "test.mycol"
},
{
"v" : 2,
"key" : {
"title" : 1,
"description" : -1
},
"name" : "title_1_description_-1",
"ns" : "test.mycol"
}
]
>
MongoDB - Capped Collections
Capped collections are fixed-size circular collections that follow the insertion order to support
high performance for create, read, and delete operations. By circular, it means that when the fixed
size allocated to the collection is exhausted, it will start deleting the oldest document in the
collection without providing any explicit commands.
Capped collections restrict updates to the documents if the update results in increased document
size. Since capped collections store documents in the order of the disk storage, it ensures that the
document size does not increase the size allocated on the disk. Capped collections are best for
storing log information, cache data, or any other high volume data.
Creating Capped Collection
To create a capped collection, we use the normal createCollection command but
with capped option as true and specifying the maximum size of collection in bytes.
>db.createCollection("cappedLogCollection",{capped:true,size:10000})
In addition to collection size, we can also limit the number of documents in the collection using
the max parameter −
>db.createCollection("cappedLogCollection",{capped:true,size:10000,max:1000})
If you want to check whether a collection is capped or not, use the following isCapped command −
>db.cappedLogCollection.isCapped()
If there is an existing collection which you are planning to convert to capped, you can do it with the
following code −
>db.runCommand({"convertToCapped":"posts",size:10000})
This code would convert our existing collection posts to a capped collection.
Querying Capped Collection
By default, a find query on a capped collection will display results in insertion order. But if you
want the documents to be retrieved in reverse order, use the sort command as shown in the
following code −
>db.cappedLogCollection.find().sort({$natural:-1})
There are few other important points regarding capped collections worth knowing −
• We cannot delete documents from a capped collection.
• There are no default indexes present in a capped collection, not even on _id field.
• While inserting a new document, MongoDB does not have to actually look for a place to
accommodate new document on the disk. It can blindly insert the new document at the tail of
the collection. This makes insert operations in capped collections very fast.
• Similarly, while reading documents MongoDB returns the documents in the same order as
present on disk. This makes the read operation very fast.