Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

Unit-1 Concepts of NoSQL: MongoDB

1.1 Concepts of NoSQL. Advantages and features.

• NoSQL Database is used to refer a non-SQL or non-relational database.


• It provides a mechanism for storage and retrieval of data other than tabular
relations model used in relational databases. NoSQL database doesn't use tables
for storing data. It is generally used to store big data and real-time web
applications.

History behind the creation of NoSQL Databases

• In the early 1970, Flat File Systems are used. Data were stored in flat files and the
biggest problems with flat files are each company implement their own flat files
and there are no standards. It is very difficult to store data in the files, retrieve
data from files because there is no standard way to store data.
• Then the relational database was created by E.F. Codd and these databases
answered the question of having no standard way to store data. But later
relational database also gets a problem that it could not handle big data, due to
this problem there was a need of database which can handle every types of
problems then NoSQL database was developed.

Advantages of NoSQL

o It supports query language.


o It provides fast performance.
o It provides horizontal scalability.

MongoDB

• 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

• MongoDB is schema less. It is a document database in which one collection holds


different documents.
• There may be difference between number of fields, content and size of the
document from one to other.
• Structure of a single object is clear in MongoDB.
Unit-1 Concepts of NoSQL: 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.

1.1.1 MongoDB Datatypes (String, Integer, Boolean, Double, Arrays, Objects)


Unit-1 Concepts of NoSQL: MongoDB

Data Description
Types

String String is the most commonly used datatype. It is used to store data. A string
must be UTF 8 valid in mongodb.

Integer Integer is used to store the numeric value. It can be 32 bit or 64 bit
depending on the server you are using.

Boolean This datatype is used to store boolean values. It just shows YES/NO values.

Double Double datatype stores floating point values.

Min/Max This datatype compare a value against the lowest and highest bson
Keys elements.

Arrays This datatype is used to store a list or multiple values into a single key.

Object Object datatype is used for embedded documents.

Null It is used to store null values.

Symbol It is generally used for languages that use a specific type.

Date This datatype stores the current date or time in unix time format. It makes
you possible to specify your own date time by creating object of date and
pass the value of date, month, year into it.

1.1.2 Database creation and dropping database

Create a Database

1. Click the Create Database button.

From the Databases tab, click the Create Database button to bring up the Create Database
dialog.

2. Enter database and first collection information.

• In the dialog, enter the name of the database to create and its first collection. Both
the database name and the collection name are required.
• If you want to create a capped collection, select the Capped Collection checkbox and
enter the maximum bytes.
• If you want to use custom collation on the newly created collection, select the Use
Custom Collation checkbox and select the desired collation settings.
Unit-1 Concepts of NoSQL: MongoDB

3. Click Create Database to create the database and its first collection.

Drop a Database

1. Click the trash can icon for the database.

From the Databases tab, to delete a database, click on the trash can icon for that database. A
confirmation dialog appears.

2. Confirm the database to delete.

In the dialog, enter the name of the database to delete.

3. Click Drop Database to delete the database.

1.2 create and Drop collections

• A collection is a grouping of MongoDB documents.


• Documents within a collection can have different fields.
• A collection is the equivalent of a table in a relational database system.
• A collection exists within a single database

Collections Screen
• The Collections screen lists the existing collections and views in the selected
database.
• Each list item includes the name and other general information for the collection or
view.
• To access the Collections screen for a database, from the Databases screen either:
✓ Click a Database Name in the main Databases view, or
✓ Click a database in the left navigation.
Unit-1 Concepts of NoSQL: MongoDB

Collection Information

The Collections screen displays the following information for each collection in the selected
database:
• Collection name
• Number of documents in the collection
• Average size of documents in the collection
• Total size of all documents in the collection
• Number of indexes on the collection
• Total size of all indexes on the collection
• Collation properties for the collection. Hover over a Collation banner to view the
properties for that collection.

Create a Collection
You can create new collections in an existing database.

1. Click the Create Collection button.


From the Collections screen, click the Create Collection button.

2. Enter the collection information.


In the Create Collection dialog, enter the name of the collection to create.

✓ If you want to create a capped collection, select the Capped Collection checkbox and
enter the maximum bytes.
✓ If you want to use custom collation on the collection, select the Use Custom
Collation checkbox and select the desired collation settings.

3. Click Create Collection to create the collection.

Drop a Collection
1. Click the trash can icon to delete a collection.
From the Collections screen, click on the trash can for the collection to delete. A
confirmation dialog appears.

2. Confirm the collection to delete.


In the dialog, enter the name of the collection to delete.

3. Click Drop Collection to drop the collection.

Show all the database

show dbs

Create new or switch database


Unit-1 Concepts of NoSQL: MongoDB

use databasename

To show current database

db

To delete database

Db.dropDatabase() // To delete current database

To view all collections

Show collections

To create collections

db.createCollection(‘collectionName’)

To delete collections

db.<collectionname>.drop()

1.3 CRUD operations (Insert, update, delete, find, Query and Projection

operators)

Insert

The create or insert operations are used to insert or add new documents in the collection. If
a collection does not exist, then it will create a new collection in the database. You can
perform, create operations using the following methods provided by the MongoDB:

Method Description

db.collection.insertOne() It is used to insert a single document in the collection.

db.collection.insertMany() It is used to insert multiple documents in the collection.

Example: 1
Unit-1 Concepts of NoSQL: MongoDB

In this example, we are inserting details of a single student in the form of document in the
student collection using db.collection.insertOne() method.

Example 2:
In this example, we are inserting details of the multiple students in the form of documents
in the student collection using db.collection.insertMany() method.
Unit-1 Concepts of NoSQL: MongoDB

Update

The update operations are used to update or modify the existing document in the collection.
You can perform update operations using the following methods provided by the MongoDB:
Method Description

It is used to update a single document in the collection


db.collection.updateOne() that satisfy the given criteria.

It is used to update multiple documents in the collection


db.collection.updateMany() that satisfy the given criteria.

It is used to replace single document in the collection that


db.collection.replaceOne() satisfy the given criteria.
Unit-1 Concepts of NoSQL: MongoDB

Example 1:
In this example, we are updating the age of Sumit in the student collection
using db.collection.updateOne() method. method.

Example 2:
In this example, we are updating the year of course in all the documents in the student
collection using db.collection.updateMany() method.
Unit-1 Concepts of NoSQL: MongoDB

Delete

The delete operation are used to delete or remove the documents from a collection. You
can perform delete operations using the following methods provided by the MongoDB:
Method Description

It is used to delete a single document from the collection


db.collection.deleteOne() that satisfy the given criteria.

It is used to delete multiple documents from the collection


db.collection.deleteMany() that satisfy the given criteria.
Unit-1 Concepts of NoSQL: MongoDB

Example 1:
In this example, we are deleting a document from the student collection
using db.collection.deleteOne() method.

Find

The Read operations are used to retrieve documents from the collection, or in other words,
read operations are used to query a collection for a document. You can perform read
operation using the following method provided by the MongoDB:
Unit-1 Concepts of NoSQL: MongoDB

Method Description

db.collection.find() It is used to retrieve documents from the collection.

Example 1:

In this example, we are retrieving the details of students from the student collection
using db.collection.find() method.

Query and Projection

Parameter Type Description

query document Optional. Specifies selection filter using query operators. To return
all documents in a collection, omit this parameter or pass an empty
document ({}).

projection document Optional. Specifies the fields to return in the documents that match
the query filter. To return all fields in the matching documents, omit
this parameter.
Unit-1 Concepts of NoSQL: MongoDB

1.3 Operators (Projection, update, limit (), sort ()) and Aggregation

Name Description

$eq Matches values that are equal to a specified value.

$gt Matches values that are greater than a specified value.

$gte Matches values that are greater than or equal to a specified value.

$in Matches any of the values specified in an array.

$lt Matches values that are less than a specified value.

$lte Matches values that are less than or equal to a specified value.

$ne Matches all values that are not equal to a specified value.

$nin Matches none of the values specified in an array.

Example

db.collection.find( { qty: { $gt: 4 } } )

Logical

Name Description

$and Joins query clauses with a logical AND returns all documents that match the conditions of
both clauses.

$not Inverts the effect of a query expression and returns documents that do not match the
query expression.

$nor Joins query clauses with a logical NOR returns all documents that fail to match both
clauses.
Unit-1 Concepts of NoSQL: MongoDB

Name Description

$or Joins query clauses with a logical OR returns all documents that match the conditions of
either clause.

Array

Name Description

$all Matches arrays that contain all elements specified in the query.

$elemMatch Selects documents if element in the array field matches all the
specified $elemMatch conditions.

$size Selects documents if the array field is a specified size.

Projection Operators

Name Description

$ Projects the first element in an array that matches the query condition.

$elemMatch Projects the first element in an array that matches the


specified $elemMatch condition.

$meta Projects the document's score assigned during $text operation.

$slice Limits the number of elements projected from an array. Supports skip
and limit slices.

limit ()
Unit-1 Concepts of NoSQL: MongoDB

• MongoDB allows you to specify the maximum number of documents to return by


making use of the limit() method which will return only the number of documents you
need.
• And as soon as you prepare a MongoDB query for the collection with the help
of db.collection.find() method, you can add on the limit() method for specifying the
limit.
• Example:

db.writers.find().pretty().limit(2)

Skip()

• It is also possible to skip some documents from a MongoDB database.


• You can perform such operations using the skip() method of MongoDB.
• In other words, it can be said that users have the power to manage or regulate where
MongoDB begins returning the query results.
• Example:

db.writers.find().pretty().skip(1)

sort ()

• For sorting your MongoDB documents, you need to make use of the sort() method.
• This method will accept a document that has a list of fields and the order for sorting.
• For indicating the sorting order, you have to set the value 1 or -1 with the specific
entity based on which the ordering will be set and displayed.
• One indicates organizing data in ascending order while -1 indicates organizing in
descending order.
• Db.test.find.sort({age:1})

Aggregation commands

• MongoDB's aggregate function will cluster out the records in the form of a collection
which can be then employed for providing operations like total number(sum), mean,
minimum and maximum, etc. from the aggregated group of data extracted.
• For performing such an aggregate function, the aggregate() method is used. The
syntax of this method looks something like this:
db.collection_name.aggregate(aggregate_operation)
Expression Description
$sum adds up the definite values of every documentUnit-1
of a Concepts
collection.
of NoSQL: MongoDB

$avg computes the average values of every document of a collection.

$min finds and returns the minimum of all values from within a collection.

$max finds and returns the maximum of all values from within a collection.

$first fetches out the first document.

$last fetches out the last document.

$addToSet feeds in the values to an array without duplication

Example:
• db.test.aggregate([
... { $group: {_id: "$age", count:{$sum:1}}}])

• db.test.aggregate( [ {$group: { _id:"age", max:{ $max:"$age"}}} ])


• db.test.aggregate( [ {$group: { _id:"age", min:{ $min:"$age"}}} ])
• db.test.aggregate( [ {$group: { _id:"age", avg:{ $avg:"$age"}}} ])
• db.test.aggregate( [ {$group: { _id:"age", first:{ $first:"$age"}}} ])
• db.test.aggregate( [ {$group: { _id:"age", last:{ $last:"$age"}}} ])

You might also like