UE20MC505B_Unit1_Lecturenotes
UE20MC505B_Unit1_Lecturenotes
Lekha A
MongoDB
Unit 1
History
The development of MongoDB began in 2007 by a New York 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 was 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.
Latest version is 3.6.
Introduction
pg. 1
Mongo DB and Basic CRUD Operations | Dr. Lekha A
₪ The document model maps to the objects in your application code, making data easy to work
with, without giving up schema governance controls, data access, complex aggregations, and
rich indexing functionality.
₪ The schema can be dynamically modified without downtime.
Distributed Data Platform
₪ MongoDB can be run within and across geographically distributed data centers and cloud
regions, providing new levels of availability and scalability.
₪ MongoDB scales elastically with no downtime, and without changing the application.
₪ As performance and availability goals evolve, MongoDB lets the developer adapt flexibly,
across data centers, with tunable consistency.
Integrated Feature Set
₪ Analytics and data visualization, text and geospatial search, graph processing, event-driven
streaming data pipelines, in-memory performance and global replication allow to deliver a
wide variety of real-time applications on one technology, reliably and securely.
₪ RDBMS systems require additional, complex technologies demanding separate integration
overhead and expense to do this well.
Lower Total Cost of Ownership
₪ Application development teams are 2x and more productive when they use MongoDB.
₪ The fully managed Atlas cloud service means operations team are as well.
₪ MongoDB runs on commodity hardware, dramatically lowering costs.
₪ MongoDB offers on-demand, pay-as-you-go pricing and affordable annual subscriptions,
including 24x7x365 global support.
₪ Applications can be one tenth the cost to deliver compared to using a relational database.
pg. 2
Mongo DB and Basic CRUD Operations | Dr. Lekha A
₪ Organizations need a database that can be secured, monitored, automated, and integrated
with their existing technology infrastructure, processes, and staff, including operations teams,
DBAs, and data analysts.
Features of architecture
MongoDB’s flexible document data model presents a superset of other database models.
₪ It allows data to be represented as simple key-value pairs and flat, table-like structures,
through to rich documents and objects with deeply nested arrays and sub-documents.
With an expressive query language, documents can be queried in many ways.
₪ Simple lookups
₪ Sophisticated processing pipelines for data analytics and transformations, through to faceted
search, JOINs and graph traversals.
With a flexible storage architecture, application owners can deploy storage engines optimized for
different workload and operational requirements.
Data in MongoDB
pg. 3
Mongo DB and Basic CRUD Operations | Dr. Lekha A
Data in MongoDB is more localized, which dramatically reduces the need to JOIN separate tables.
The result is dramatically higher performance and scalability across commodity hardware as a
single read to the database can retrieve the entire document.
Unlike many NoSQL databases, users don’t need to give up JOINs entirely.
₪ For additional flexibility, MongoDB provides the ability to perform equi and non-equi JOINs that
combine data from multiple collections, typically when executing analytical queries against live,
operational data.
Collection
₪ "_id" : ObjectId("5699348d350ba4219fca39a1")
₪ "_id" : ObjectId("56993492350ba4219fca39a2")
Document
Commands
Connect to mongod
₪ mongo
Clear the screen
₪ cls
Create a new database if it does not exist or returns an existing database
₪ use <database_name>
₪ output
switched to db database_name
After starting the mongo shell, session will use the test database by default.
Check the currently selected database_name
pg. 5
Mongo DB and Basic CRUD Operations | Dr. Lekha A
₪ db
₪ output
database_name
check the databases list
₪ show dbs
₪ Output
table size
To display a database atleast one document should be inserted into it
Drop an existing databse
₪ db.dropDatabase()
₪ Output
if not drop the default test database
Create a collection
₪ db.createCollection(name, options)
name is name of collection to be created.
Options is a document and is used to specify configuration of collection.
Options can be
Capped
It is boolean and optional
If true, enables a capped collection.
Capped collection is a fixed size collection that automatically overwrites its oldest entries
when it reaches its maximum size.
If we specify true, we need to specify size parameter also.
db.createCollection(“MCA", {capped : true, size : 5242880, max : 5000 } )
autoIndexID
It is boolean and optional
If true, automatically create index on _id fields.
Default value is false.
size number
It is optional
Specifies a maximum size in bytes for a capped collection.
If capped is true, then we need to specify this field also.
max number
It is optional
Specifies the maximum number of documents allowed in the capped collection.
pg. 6
Mongo DB and Basic CRUD Operations | Dr. Lekha A
WriteResult({“nInserted”: 1})
₪ During insert mongod will create the _id field and assign it a unique ObjectId value
Insert a document specifying an _id field
₪ db. <collection_name>.insert({_id: num, filed_name: value})
The value of _id must be unique within the collection to avoid duplicate key error.
Insert multiple documents
₪ db. <collection_name>.insert({<Document1>}, {<Document2>,…})
Unordered Insert
₪ db.<collection_name>.insert(
[ {<Document1>}, {<Document2>},….],
{ordered: false})
With unordered inserts, if an error occurs during an insert of one of the documents, MongoDB
continues to insert the remaining documents in the array.
Insert Single Document
₪ db.<collection_name>.insertOne({<Document1>})
Insert a document specifying an _id field
₪ db. <collection_name>.insertOne({_id: num, field_name: value})
The value of _id must be unique within the collection to avoid duplicate key error.
Insert Multiple Documents with Unordered Insert
₪ db.<collection_name>.insertMany(
[ {<document 1>}, {<document 2>}, ...],
{ordered: <boolean>})
Insert a document specifying an _id field
₪ db. <collection_name>.insertMany(
{_id: num, field_name: value},
{_id: num, field_name: value} )
The value of _id must be unique within the collection to avoid duplicate key error.
Update an existing document or insert a new document, depending on its document parameter.
₪ db.<collection_name>.save( {<document>})
₪ db.<collection_name>.save( {<_id: num, field_name: value, ..>})
Modifies an existing document or documents in a collection.
₪ The method can modify specific fields of an existing document or documents or replace an
existing document entirely, depending on the update parameter.
db.<collection_name>.update(
{field_name: existing_value },
{field_name: existing_value, new_field: new_value, existing_field : new_value },
{upsert: true})
Selects documents in a collection or view and returns a pointer to the selected documents.
pg. 7
Mongo DB and Basic CRUD Operations | Dr. Lekha A
₪ db.<collection_name>.find(query, projection)
The query parameter is optional. Specifies selection filter using query operators. To return all
documents in a collection, omit this parameter or pass an empty document ({}).
The projection parameter determines which fields are returned in the matching documents.
The find() method with no parameters returns all documents from a collection and returns all fields
for the documents.
₪ db.<collection_name>.find()
Display only id
₪ db.<collection_name>.find({},{_id:1})
pg. 8
Mongo DB and Basic CRUD Operations | Dr. Lekha A
Returns one document that satisfies the specified query criteria on the collection.
₪ db.<collection_name>.findOne(query, projection)
If multiple documents satisfy the query, this method returns the first document according to
the natural order which reflects the order of documents on the disk.
In capped collections, natural order is the same as insertion order. If no document satisfies
the query, the method returns null.
Returns a single document without any query.
₪ db.<collection_name>.findOne()
pg. 9
Mongo DB and Basic CRUD Operations | Dr. Lekha A
pg. 10
Mongo DB and Basic CRUD Operations | Dr. Lekha A
Name Description
Only updates the field if the specified value is less than the existing field value.
{$min: {<field1>: <value1>, ...}}
If the field does not exist, the $min operator sets the field to the specified value.
$min
For comparisons between values of different types, such as a number and a
null, $min uses the BSON comparison order.
Compute the minimum amount and minimum quantity for each grouping.
pg. 11
Mongo DB and Basic CRUD Operations | Dr. Lekha A
Only updates the field if the specified value is greater than the existing field value.
{$max: {<field1>: <value1>, ...}}
The $max operator updates the value of the field to a specified value if the specified
value is greater than the current value of the field.
The $max operator can compare values of different types, using the BSON comparison
order.
$max Compute the maximum amount and maximum quantity for each grouping.
pg. 12
Mongo DB and Basic CRUD Operations | Dr. Lekha A
Sets the value of a field if an update results in an insert of a document. Has no effect
on update operations that modify existing documents.
{$setOnInsert: {<field1>: <value1>, ...}}
$setOnInsert
Name Description
pg. 13
Mongo DB and Basic CRUD Operations | Dr. Lekha A
The all positional operator $[] indicates that the update operator should modify all
elements in the specified array field.
{<update operator>: {"<array>.$[]" : value } }
To increment all elements in the grades array by 10 for all documents in the collection
$[]
pg. 14
Mongo DB and Basic CRUD Operations | Dr. Lekha A
The filtered positional operator $[<identifier>] identifies the array elements that
match the arrayFilters conditions for an update operation.
{<update operator>:
{"<array>.$[<identifier>]" : value } },
{arrayFilters: [{<identifier>: <condition>}}]}
To increment all elements in the grades array by 10 for all documents in the collection
$[<identifier>]
The $addToSet operator adds a value to an array unless the value is already present,
in which case $addToSet does nothing to that array.
{$addToSet: {<field1>: <value1>, ...}}
Add the element "accessories" to the tags array since "accessories" does not exist in
the array
$addToSet
pg. 15
Mongo DB and Basic CRUD Operations | Dr. Lekha A
$pop
$push
pg. 16
Mongo DB and Basic CRUD Operations | Dr. Lekha A
The $pull operator removes from an existing array all instances of a value or values
that match a specified condition.
{$pull: {<field1>: <value|condition>, <field2>: <value|condition>, ...}}
Remove the arrays that have elements lesser than 95
$pull
The $pullAll operator removes all instances of the specified values from an existing
array.
Unlike the $pull operator that removes elements by specifying a query, $pullAll
removes elements that match the listed values.
{$pullAll: {<field1>: [ <value1>, <value2> ... ], ... }}
Remove the instances of all value 75, 80 from the grades array
$pullAll
pg. 17
Mongo DB and Basic CRUD Operations | Dr. Lekha A
Name Description
The $each modifier is available for use with the $addToSet operator and the $push
operator.
Use with the $addToSet operator to add multiple values to an array <field> if the values
do not exist in the <field>.
{$addToSet: {<field>: {$each: [ <value1>, <value2> ...]}}}
Use with the $push operator to append multiple values to an array <field>.
{$push: {<field>: {$each: [ <value1>, <value2> ...]}}}
Append each element of [90, 92, 85] to the scores array for the document where
the _id field is 1
$each
pg. 18
Mongo DB and Basic CRUD Operations | Dr. Lekha A
The $position modifier specifies the location in the array at which the $push operator inserts
elements.
Without the $position modifier, the $push operator inserts elements to the end of the array.
To use the $position modifier, it must appear with the $each modifier.
$position
Update the grades field to add the elements 50, 60 and 70 to the beginning of the array
Update the grades field to add the elements 90 and 80 at the array index of 2
pg. 19
Mongo DB and Basic CRUD Operations | Dr. Lekha A
The $slice modifier limits the number of array elements during a $push operation.
To use the $slice modifier, it must appear with the $each modifier.
Can pass an empty array [] to the $each modifier such that only the $slice modifier has an
effect.
Add new elements to the grades array and use the $slice modifier to trim the array to the
last five elements.
$slice
Add new elements to the grades array and use the $slice modifier to trim the array from
first three elements.
The $sort modifier orders the elements of an array during a $push operation.
$sort
To use the $sort modifier, it must appear with the $each modifier.
pg. 20
Mongo DB and Basic CRUD Operations | Dr. Lekha A
Push the grades in sorted order and sort the grades in descending order.
pg. 21
Mongo DB and Basic CRUD Operations | Dr. Lekha A
₪ db.<collection_name>.deleteOne( <filter>)
Use a field that is part of a unique index such as _id for precise deletions.
Removes all documents that match the filter from a collection.
₪ db.<collection_name>.deleteMany(<filter>)
Delete the row that contains id=1
Delete a single document based on the filter and sort criteria, returning the deleted document.
₪ db.<collection_name>.findOneAndDelete(filter, options)
Find the first document where name is ‘M. MMM’ and deletes it
pg. 22
Mongo DB and Basic CRUD Operations | Dr. Lekha A
MongoDB Commands
Variations in Insert
pg. 23
Mongo DB and Basic CRUD Operations | Dr. Lekha A
pg. 24