The document provides information about MongoDB including:
- MongoDB is an open-source, document-based NoSQL database that stores data in BSON format and collections instead of tables and rows.
- It has no schema and allows embedding of documents, dynamic queries, indexing, replication and sharding for scale and high performance.
- The core components of MongoDB are the mongod daemon and mongo shell used to connect and execute commands. Collections contain documents rather than rows/columns and support dynamic schemas.
2. Overview
MongoDB is an open-source, document-based NoSQL database.
The following are a few notable features of MongoDB database:
•It is an open-source, cross-platform, NoSQL, document-based database.
•There is no concept of database schema like relational databases. Data is stored
as collections and documents.
•There are no complex joins between collections which are usually done in
relational database tables. A join is generally performed while storing the data by
combining the documents.
•Data is stored in BSON format (Binary encoding of JSON-like documents).
•Data stored in collections need not have a similar structure. One document can
have a certain set of fields, whereas another document can have a completely
different set (both type and amount) of fields.
•MongoDB provides a default database named test. If there is no database
selected while storing data, MongoDB uses this database to store data.
DR.ROOPA R,ISE,BMSCE
4. This is an AdHoc Query as the entire query is known only at the
time of execution depending upon the value of username
passed.
"SELECT * FROM table WHERE name = " + username;
DR.ROOPA R,ISE,BMSCE
6. In RDBMS, defining the schema before inserting any record is mandatory, and the
structure of the record being inserted should strictly match with the schema.
RDBMS: Defined the schema for student Table.
CREATE TABLE student( id int PRIMARY KEY NOT
NULL, name varchar(30))
Now, let's try to insert the record
Insert into student values (1,"Kunal");
DR.ROOPA R,ISE,BMSCE
7. Now, suppose I want to add one more field in the student table. For
that, I have to alter the schema of the student table to do that.
Let's try without altering the schema:
mysql> Insert into student values
(1,"Kunal","kunal@gmail.com");
ERROR 1136 (21S01): Column count doesn't match value
count at row 1
DR.ROOPA R,ISE,BMSCE
8. Let's try the same thing with MongoDB.
Here, we don't need to create the schema.
There is no concept of a table. In MongoDB, we insert the record in the
collections, and we don't need to define any schema structure for any
operation.
Let's try to insert:
Here, I am inserting in the student collection.
Now let's try to insert the record in student collection with different schema.
DR.ROOPA R,ISE,BMSCE
9. Now, try to fetch all records.
DR.ROOPA R,ISE,BMSCE
10. •MongoDB is schema-less.
•There may be a difference between the number of fields,
content, and size of the document from one to other. But in
RDBMS, every record must adhere to a particular
predefined schema.
•MongoDB is horizontally scalable i.e we can add more
servers (sharding) but RDBMS is only vertically scalable i.e
increasing RAM.
•MongoDB emphasizes on the CAP theorem (Consistency,
Availability, and Partition tolerance) but RDBMS
emphasizes ACID properties (Atomicity, Consistency,
Isolation, and Durability).
DR.ROOPA R,ISE,BMSCE
11. •MongoDB supports JSON query language along with SQL but
RDBMS supports SQL query language only.
•MongoDB is easy to set up, configure, and run in comparison to
the RDBMS. It's Java client is also very easy to use.
•MongoDB is almost 100 times faster than traditional database
system like RDBMS, which is slower in comparison with the NoSQL
databases.
•There is no support for complex joins in MongoDB, but RDBMS
supports complex joins, which can be difficult to understand and
take too much time to execute.
•MongoDB uses internal memory for storing working sets
resulting in faster access time.
•MongoDB supports deep query-ability i.e we can perform
dynamic queries on documents using the document-based query
language that's nearly as powerful as SQL.
•In MongoDB, Conversion/mapping of application objects to
database objects is not needed.
DR.ROOPA R,ISE,BMSCE
12. Indexing
•Indexing is very important for improving the performances of search queries.
When we continuously perform searches in a document, we should index those
fields that match our search criteria.
•In MongoDB, we can index any field indexed with primary and secondary
indices. Making query searches faster, MongoDB indexing enhances the
performance.
DR.ROOPA R,ISE,BMSCE
13. Replication
•When it comes to redundancy, replication is the tool that MongoDB
uses. This feature distributes data to multiple machines. I
•t can have primary nodes and their one or more replica sets. Basically,
replication makes ready for contingencies.
•When the primary node is down for some reasons, the secondary node
becomes primary for the instance. This saves our time for maintenance
and makes operations smooth.
DR.ROOPA R,ISE,BMSCE
14. GridFS
GridFS is a feature of storing and retrieving files. For files larger than 16 MB this
feature is very useful. GridFS divides a document in parts called chunks and
stores them in a separate document. These chunks have a default size of 255kB
except the last chunk.
When we query GridFS for a file, it assembles all the chunks as needed.
DR.ROOPA R,ISE,BMSCE
15. Sharding
Basically, the concept of sharding comes when we need to deal with larger datasets. This
huge data can cause some problems when a query comes for them. This feature helps to
distribute this problematic data to multiple MongoDB instances.
The collections in the MongoDB which has a larger size are distributed in multiple
collections. These collections are called “shards”. Shards are implemented by clusters.
DR.ROOPA R,ISE,BMSCE
16. High Performance
MongoDB is an open source database with high performance. This shows high
availability and scalability. It has faster query response because of indexing and
replication. This makes it a better choice for big data and real-time applications.
DR.ROOPA R,ISE,BMSCE
17. Installing MongoDB
The installation of MongoDB on a local computer.
MongoDB is available in two flavors:
1. Community Edition
2. Enterprise Edition
•The Community edition of MongoDB is open-sourced and freely
available.
• Enterprise edition is licensed and is available with an array of
enterprise-grade features with commercial support.
Step by step instructions on how to download and install the
MongoDB community edition can be found here.
DR.ROOPA R,ISE,BMSCE
18. At the time of installation, MongoDB provides an option to install MongoDB
Compass, a GUI console to access MongoDB databases.
Alternatively,
the MongoDB database can be accessed from the command line shell as well.
The following is the command-line interface of MongoDB:
DR.ROOPA R,ISE,BMSCE
19. The following is the Graphical User Interface (MongoDB Compass):
DR.ROOPA R,ISE,BMSCE
20. MongoDB Components
There are several database components of MongoDB. However,
there are two primary components that are of interest to us.
These two components are:
•mongod: This is the database daemon that runs in the
background.
•mongo: MongoDB shell. This is used to connect to the daemon
and execute various database commands.
DR.ROOPA R,ISE,BMSCE
21. Understanding MongoDB Storage Structure
However, there is no concept of a schema in MongoDB. It primarily uses the
concept of database, collection, and documents.
Database: A database is a physical container for collections.
Collection: A collection is a group of MongoDB documents. In SQL
terminology, this is similar to a database table.
Document: A document is a set of key-value pairs. In SQL terminology, this is
similar to a row in a database table.
Field: A field is key in a document. In SQL terminology, this is similar to a
column in a database table.
Embedded Document: An embedded document is the joining of multiple
documents.In SQL terminology, this is similar to joining several database
tables.
DR.ROOPA R,ISE,BMSCE
22. Start using MongoDB
create databases, collections, retrieve data from existing collections
imposing conditions and so on.
Most MongoDB commands are structured with db.<task>(options). In that, Task name
follows a camelCase naming pattern.
For example, to create a new empty collection, we use
db.createCollection(collectionName)
Connecting to MongoDB via MongoDB Shell
Open Command Prompt and type mongo
DR.ROOPA R,ISE,BMSCE
23. Using Help
MongoDB provides a helpful list of database commands through db.help(). This commands
lists down all major commands with a concise description:
DR.ROOPA R,ISE,BMSCE
24. Using show
There is also a list of show commands to show various elements such as databases,
collections, users, and others. Following is the list of show commands:
DR.ROOPA R,ISE,BMSCE
25. For example, we can run show dbs to list all the existing databases:
Creating a MongoDB database
•We can create a new database by specifying use with the
database name.
•If the database exists, it will be used. Otherwise, a new one will
be created.
DR.ROOPA R,ISE,BMSCE
26. Command: use <dbname>
Command: use <dname>
Creation of a new database
Note that though the database is created, it will not be displayed in show
dbs command until there is at least one collection in it.
DR.ROOPA R,ISE,BMSCE
27. Dropping a MongoDB database
Switch to the database to be deleted using
use <dbname> command and then run below command:
Command: db.dropDatabase()
DR.ROOPA R,ISE,BMSCE
28. Creating a Collection
A new collection can be created with the following command.
Command: db.createCollection(name, options)
This creates an empty collection in the selected database
DR.ROOPA R,ISE,BMSCE
29. A collection can also be capped and we can define the maximum
size and number of documents that can be stored in that collection
with the optional options attribute.
Options:
•Capped: Possible values are true or false. This option decides
whether this collection is capped.
•Size: This option decides the maximum number of documents that
can be stored in this collection.
•Max: This option decides the maximum size in bytes that this
collection can hold. Max option is checked first and then the size is
validated.
DR.ROOPA R,ISE,BMSCE
30. Dropping a Collection
A collection can be dropped using the following command:
Command: db.<collectionName>.drop()
DR.ROOPA R,ISE,BMSCE
31. Inserting Documents
A document can be inserted into a collection using insert()
or save() methods
Command: db.<collectionName>.insert()
or
db.<collectionName>.save()
DR.ROOPA R,ISE,BMSCE
33. Following example shows how to insert multiple documents in a collection:
DR.ROOPA R,ISE,BMSCE
34. In the above insertion example, we have only supplied two fields which are perfectly valid.
Below is the list of documents present in movies collection:
In none of our documents, we have supplied ObjectId. MongoDB created one for each of
these documents.
DR.ROOPA R,ISE,BMSCE
35. Finding Documents
Documents from a collection can be retrieved from MongoDB
using find()
Command: db.<collectionName>.find()
1.Find all documents from a collection:
Command: db.<collectionName>.find()
Example: db.movies.find({})
We provide a {} in the find() to retrieve all the documents from a
collection.
In SQL, this is similar to as below:
SELECT * FROM <table>
pretty() is used along with find() to pretty-print the document output
DR.ROOPA R,ISE,BMSCE
37. In MongoDB, you don't need to create collection.
MongoDB creates collection automatically, when you
insert some document.
>db.tp.insert({"name" : “tp"}),
WriteResult({ "nInserted" : 1 })
>show collections
mycol
mycollection system.
indexes
tp
DR.ROOPA R,ISE,BMSCE
38. You can also pass an array of documents into the insert() method as shown below:
> db.createCollection("post")
> db.post.insert([
{
title: "MongoDB Overview",
description: "MongoDB is no SQL database",
by: “tt",
url: "http://www.tt.com",
tags: ["mongodb", "database", "NoSQL"],
likes: 100
},
{
title: "NoSQL Database",
description: "NoSQL database doesn't have tables",
by: “tt",
url: "http://www.tt.com",
tags: ["mongodb", "database", "NoSQL"],
likes: 20,
comments: [
{
user:"user1",
message: "My first comment",
dateCreated: new Date(2013,11,10,2,35),
DR.ROOPA R,ISE,BMSCE
42. The find() Method:
Similar to SELECT * FROM <table>
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.COLLECTION_NAME.find().pretty()
The findOne() method
Apart from the find() method, there is findOne() method, that returns only one
document.
Syntax
>db.COLLECTIONNAME.findOne()
Ex:
>db.mycol.findOne({title: "MongoDB Overview"})
{ "_id" : ObjectId("5dd6542170fb13eec3963bf0"),
"title" : "MongoDB Overview",
"description" : "MongoDB is no SQL database",
DR.ROOPA R,ISE,BMSCE
43. Using clauses to the find method
SELECT col1, col2 FROM table WHERE <condition(s)>
MongnDB let us add various clauses in our find() method to fetch data from a
collection:
Command: db.coll.find({key:value})
Example: db.movies.find({‘title’ : ‘Salt’})
o/p:
DR.ROOPA R,ISE,BMSCE
45. Operation Syntax Example RDBMS Equivalent
Equality {<key>:<value>}} db.mycol.find({"by":"
tt"}).pretty()
where by = 'tt'
Less Than {<key>:{$lt:<value>}} db.mycol.find({"likes"
:{$lt:50}}).pretty()
where likes < 50
Less Than Equals {<key>:{$lte:<value>}
}
db.mycol.find({"likes"
:{$lte:50}}).pretty()
where likes <= 50
Greater Than {<key>:{$gt:<value>}} db.mycol.find({"likes"
:{$gt:50}}).pretty()
where likes > 50
Greater Than Equals {<key>:{$gte:<value>}
}
db.mycol.find({"likes"
:{$gte:50}}).pretty()
where likes >= 50
Not Equals {<key>:{$ne:<value>}
}
db.mycol.find({"likes"
:{$ne:50}}).pretty()
where likes != 50
Values in an array {<key>:{$in:[<value1>
,
<value2>,……<valueN
>]}}
db.mycol.find({"nam
e":{$in:["Raj", "Ram",
"Raghu"]}}).pretty()
Where name
matches any of the
value in :["Raj",
"Ram", "Raghu"]
Values not in an array {<key>:{$nin:<value>}
}
db.mycol.find({"nam
e":{$nin:["Ramu",
Where name values
is not in the array
DR.ROOPA R,ISE,BMSCE
46. AND
Command: db.coll.find({$and : [{key:value}, {key:value}]})
Example: db.movies.find({$and: [{title : ‘Jai Ho’}, {releaseYear :
2016}]})
OR
Command: db.coll.find({$or : [{key:value}, {key:value}]})
Example: db.movies.find({$or: [{title : ‘Jai Ho’}, {releaseYear :
2016}]})
Combining AND and OR together
Command: db.coll.find({key : {$lt : value}, $or: [{key:value},
{key:value}]})
Example: db.coll.find({releaseYear : {$lte : 2016}, $or: [{title : ‘Jai
Ho’},{title : ‘Dangal’}]})
DR.ROOPA R,ISE,BMSCE
47. >db.mycol.find({"likes": {$gt:10}, $or: [{"by": "tt"},
{"title": "MongoDB Overview"}]}).pretty()
{
"_id": ObjectId(7df78ad8902c),
"title": "MongoDB Overview",
"description": "MongoDB is no sql database",
"by": "tt",
"url": "http://www.tt.com",
"tags": ["mongodb", "database", "NoSQL"],
"likes": "100"
}
>
The following example will show the documents that have likes greater than 10 and
whose title is either 'MongoDB Overview' or by is ‘ tt'. Equivalent SQL where clause
is 'where likes>10 AND (by =‘ tt' OR title = 'MongoDB Overview')'
DR.ROOPA R,ISE,BMSCE
48. 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()
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" DR.ROOPA R,ISE,BMSCE
49. Update Documents
Command:
db.<collectionName>.update(SELECTION_CRITERIA, UPDATED_DATA)
db.<collectionName>.save(SELECTION_CRITERIA, NEW_DATA)
Example: db.movies.update({title: ‘Jai Ho’}, {$set: {releaseYear : 2003}})
Remove Documents
Documents can be removed from a collection using remove() method
Command:
db.<collectionName>.remove(DEL_CRITERIA, JUSTONE)
Example:
db.movies.remove({title: ‘Jai Ho’}) -> Removes only the ones that satisfy the
condition.
db.movies.remove({releaseYear: 2016}, 1) -> Remove only one if multiple documents
satisfy the condition.
db.movies.remove({}) -> Removes all documents from the collection. This is the
equivalent of truncate command in SQL.
.
DR.ROOPA R,ISE,BMSCE