KEMBAR78
Mongo Nosql CRUD Operations | PPTX
MongoDB
NOSQL BASED OPERATIONS PREPARED BY:- ANUJ KUMAR
SISL INFOTECH -(SENIOR DBA)
Overview
 In one day:
 24 million transactions processed by Walmart
 100 TB of data uploaded to Facebook
 175 million tweets on Twitter
 ……….
How to store, query and process these data efficiently?
Overview
 The problems with Relational Database:
 Overhead for complex select, update, delete operations
o Select: Joining too many tables to create a huge size table.
o Update: Each update affects many other tables.
o Delete: Must guarantee the consistency of data.
 Not well-supported the mix of unstructured data.
 Not well-scaling with very large size of data.
NoSQL is a good solution to deal with these problems.
Overview
 What is NoSQL:
 NoSQL = Non SQL or Not only SQL
 Wikipedia’s definition:
 A NoSQL database provides a mechanism for storage and retrieval of data that is modeled
in means other than the tabular relations used in relational databases.
MongoDB Overview
 Features of MongoDB
• An open source and document-oriented database.
• Data is stored in JSON-like documents.
• interoperates nicely with applications (JSON)
• offers load balancing (multiple servers)
• Dynamic schemas.
MongoDB to SQL Terminology
MongoDB SQL
Database or schema database
collection table
Document (JSON) record (row)
field column
linking/embedded documents join
primary key (_id field) primary key (user designated)
index index
Reference Foreign Key
Shard Partition
Document
 MongoDB store record/data in the form of documents, which is a
data structure composed of field and value pairs.
 MongoDB documents are similar to JSON objects.
 The value of a field can be any of the BSON data types, including
other documents, arrays, and arrays of documents.
 Field name are String.
.
Document Structure
{
field1: value1,
field2: value2,
...
fieldN: valueN
}
Collection
 MongoDB stores all documents in collections.
 A collection is a group of related documents.
 Collections are analogous to a table in relational databases.
_id and ObjectIds
 Every document has a special key, "_id", that is unique within a collection.
 ObjectId is the default type for "_id".
 Unique _id field that acts as a primary key
 ObjectIds use 12 bytes of storage, which gives them a string representation that is 24
hexadecimal digits: 2 digits for each byte.
Data Storage Mechanism
Data Storage Mechanism Contd..
MongoDB CRUD Operations
 CRUD stands for Create Read Update and Delete operation.
 Read operation(Find operation)
 Write operation(Create ,Update and Delete operation)
Read Operation:
 Read operations, or queries, retrieve data stored in the database.
 In MongoDB, queries select documents from a single collection.
 Queries specify criteria, or conditions, that identify the documents that MongoDB
returns to the clients.
 A query may include a projection that specifies the fields from the matching documents
to return.
Read Operation Contd..
 Query Interface
 For query operations, MongoDB provide a method
db.collection.find() or db.collection.findone()
 The method accepts both the query criteria and projections and returns
a cursor to the matching documents.
Fig: Component of Find Operation
Read Operation Contd..
 MongoDB queries exhibit the following behavior:
 The order of documents returned by a query is not defined unless you specify
a sort().
Read Operation Contd..
 Find method with skip()
db.userdetails.find().skip(2)
 To display output in structure format
db.userdetails.find().skip(2).pretty()
 Using both limit and skip with find
db.userdetails.find().skip(1).limit(2).pretty()
• Using sort operation for ordering data
db.userdetails.find.sort({“Joining_date” : -1})
Read Operation :Projection Examples
1. Exclude One Field From a Result Set:
db.user_packages.find({"user_id" : {$gt : 3}},{"code_id" : 0})
{"_id":ObjectId("5abc8801973e6055582c89d3"),"user_id":22,"package_id“:"35963264570976522d8071a7
3", "flag" : 0, "assoc_date" : "2018/03/29", "updated_at" : ISODate("2018-03-29T06:30:25Z"), "created_at"
: ISODate("2018-03-29T06:30:25Z") }
2. Return Two fields and the _id Field:
db.user_packages.find({"user_id" : {$gt : 3}},{"package_id" :1,"code_id" : 1})
{ "_id" : ObjectId("5abc8801973e6055582c89d3"), "code_id" : "28e95d6ebb58da6115b038dbcd33726c",
"package_id" : "35963264570976522d8071a73" }
3. Return Two Fields and Exclude _id:
db.user_packages.find({"user_id" : {$gt : 3}},{,"_id" : 0, "package_id" :1,"code_id" : 1})
{"code_id" : "28e95d6ebb58da6115b038dbcd33726c", "package_id" : "35963264570976522d8071a73" }
Write Operation:
 Write operation is any operation that creates or modifies data in the MongoDB
instance.
 There are three classes of write operations in MongoDB:
Insert (Create) , Update, and Remove (Delete)
 For the update and remove operations, you can specify criteria, or conditions,
that identify the documents to update or remove.
Write Operation- Create:
 Create operations add new documents to a collection.
 In MongoDB, the db.collection.insert() method perform create operations.
Write Operation- Update:
 Update operations modify existing documents in a collection.
Write Operation- Delete:
 Delete operations remove documents from a collection.
 In MongoDB, db.collection.remove() method performs delete operations.
Example of
CRUD Operations
1.Insert a Document with insert() Method:
 The following statement inserts a document with three fields into the collection inventory:
db.inventory.insert( {
_id: 10,
type: "misc",
item: "card",
qty: 15
}
)
 In the example, the document has a user-specified _id field value of 10. The value must be
unique within the inventory collection.
Modify Document
There are 2 ways to update document:
1. Modify Multiple Documents with update() Method
2. Modify a Document with save() Method
1.Modify Multiple Documents with
update() Method:
 By default, the update() method updates a single document that matches
its selection criteria.
 Call the method with the multi option set to true to update multiple
documents.
 The following example finds all documents with type equal to “item_id" and modifies their qty field by
10. The example uses $inc, which is one of the update operators available.
{ "_id" : 1, "item_id" : "I001", "comp_id" : "C001", "qty" : 25, "prate" : 30, "srate" : 35, "mrp" : 40 }
db.items.update( { item_id: "I001" },{ $inc: { qty: 10 }},{“multi”: true});
condition item_id is I001 have been updated and the qty became 35 from 25.
2.Modify a Document with save() Method:
 The save() method can replace an existing document. To replace a
document with the save() method, pass the method a document with an
_id field that matches an existing document.
 The following example completely replaces the document with the _id equal to 10 in the inventory
collection:
db.inventory.save(
{ _id: 10,
type: "misc",
item: "playcard"
} )
Remove Document
1. Remove All Document:
 To remove all documents from a collection, pass an empty query document {} to the remove() method.
db.inventory.remove({})
2. Remove Documents that Match a Condition:
 To remove the documents that match a deletion criteria, call the remove() method with the <query>
parameter.
db.inventory.remove( { type : "food" } )
3. Remove a Single Document that Matches a Condition:
 To remove a single document, call the remove() method with the just One parameter set to true or 1.
db.inventory.remove( { type : "food" }, 1 )
Query Document- Specify Conditions Using
Query Operators
 A query document can use the query operators to specify
conditions in a MongoDB query.
 The following example selects all documents in the inventory collection
where the value of the type field is either ’food’ or ’snacks’:
db.inventory.find( { type: { $in: [ 'food', 'snacks' ] } } )
Query Document- Specify Comparison
operator
AND Conditions
In the following example, the query document
specifies an equality match on the field
food and a less than ($lt) comparison match
on the field price:
db.inventory.find( { $and:[
type: 'food',
price: { $lt: 9.95 } ]
} )
 This query selects all documents where the
type field has the value ’food’ and the value
of the price field is less than 9.95.
OR Conditions
db.inventory.find( { $or: [
{ qty: { $gt: 100 } },
{ price: { $lt: 9.95 } }
] } )
 In the above example, the query document
selects all documents in the collection where
the field qty has a value greater than ($gt) 100
or the value of the price field is less than ($lt)
9.95.
Specify AND as well as OR Conditions:
db.inventory.find( {
$and : [
{ $or : [ { price : 0.99 }, { price : 1.99 } ] },
{ $or : [ { sale : true }, { qty : { $lt : 20 } } ] }
]
} )
MongoDB Embedded Document
MongoDB Embedded Document ..
Reference documents or linking documents
Thanking for attention !! 

Mongo Nosql CRUD Operations

  • 1.
    MongoDB NOSQL BASED OPERATIONSPREPARED BY:- ANUJ KUMAR SISL INFOTECH -(SENIOR DBA)
  • 2.
    Overview  In oneday:  24 million transactions processed by Walmart  100 TB of data uploaded to Facebook  175 million tweets on Twitter  ………. How to store, query and process these data efficiently?
  • 3.
    Overview  The problemswith Relational Database:  Overhead for complex select, update, delete operations o Select: Joining too many tables to create a huge size table. o Update: Each update affects many other tables. o Delete: Must guarantee the consistency of data.  Not well-supported the mix of unstructured data.  Not well-scaling with very large size of data. NoSQL is a good solution to deal with these problems.
  • 4.
    Overview  What isNoSQL:  NoSQL = Non SQL or Not only SQL  Wikipedia’s definition:  A NoSQL database provides a mechanism for storage and retrieval of data that is modeled in means other than the tabular relations used in relational databases.
  • 5.
    MongoDB Overview  Featuresof MongoDB • An open source and document-oriented database. • Data is stored in JSON-like documents. • interoperates nicely with applications (JSON) • offers load balancing (multiple servers) • Dynamic schemas.
  • 6.
    MongoDB to SQLTerminology MongoDB SQL Database or schema database collection table Document (JSON) record (row) field column linking/embedded documents join primary key (_id field) primary key (user designated) index index Reference Foreign Key Shard Partition
  • 7.
    Document  MongoDB storerecord/data in the form of documents, which is a data structure composed of field and value pairs.  MongoDB documents are similar to JSON objects.  The value of a field can be any of the BSON data types, including other documents, arrays, and arrays of documents.  Field name are String. . Document Structure { field1: value1, field2: value2, ... fieldN: valueN }
  • 8.
    Collection  MongoDB storesall documents in collections.  A collection is a group of related documents.  Collections are analogous to a table in relational databases.
  • 9.
    _id and ObjectIds Every document has a special key, "_id", that is unique within a collection.  ObjectId is the default type for "_id".  Unique _id field that acts as a primary key  ObjectIds use 12 bytes of storage, which gives them a string representation that is 24 hexadecimal digits: 2 digits for each byte.
  • 10.
  • 11.
  • 12.
    MongoDB CRUD Operations CRUD stands for Create Read Update and Delete operation.  Read operation(Find operation)  Write operation(Create ,Update and Delete operation)
  • 13.
    Read Operation:  Readoperations, or queries, retrieve data stored in the database.  In MongoDB, queries select documents from a single collection.  Queries specify criteria, or conditions, that identify the documents that MongoDB returns to the clients.  A query may include a projection that specifies the fields from the matching documents to return.
  • 14.
    Read Operation Contd.. Query Interface  For query operations, MongoDB provide a method db.collection.find() or db.collection.findone()  The method accepts both the query criteria and projections and returns a cursor to the matching documents. Fig: Component of Find Operation
  • 15.
    Read Operation Contd.. MongoDB queries exhibit the following behavior:  The order of documents returned by a query is not defined unless you specify a sort().
  • 16.
    Read Operation Contd.. Find method with skip() db.userdetails.find().skip(2)  To display output in structure format db.userdetails.find().skip(2).pretty()  Using both limit and skip with find db.userdetails.find().skip(1).limit(2).pretty() • Using sort operation for ordering data db.userdetails.find.sort({“Joining_date” : -1})
  • 17.
    Read Operation :ProjectionExamples 1. Exclude One Field From a Result Set: db.user_packages.find({"user_id" : {$gt : 3}},{"code_id" : 0}) {"_id":ObjectId("5abc8801973e6055582c89d3"),"user_id":22,"package_id“:"35963264570976522d8071a7 3", "flag" : 0, "assoc_date" : "2018/03/29", "updated_at" : ISODate("2018-03-29T06:30:25Z"), "created_at" : ISODate("2018-03-29T06:30:25Z") } 2. Return Two fields and the _id Field: db.user_packages.find({"user_id" : {$gt : 3}},{"package_id" :1,"code_id" : 1}) { "_id" : ObjectId("5abc8801973e6055582c89d3"), "code_id" : "28e95d6ebb58da6115b038dbcd33726c", "package_id" : "35963264570976522d8071a73" } 3. Return Two Fields and Exclude _id: db.user_packages.find({"user_id" : {$gt : 3}},{,"_id" : 0, "package_id" :1,"code_id" : 1}) {"code_id" : "28e95d6ebb58da6115b038dbcd33726c", "package_id" : "35963264570976522d8071a73" }
  • 18.
    Write Operation:  Writeoperation is any operation that creates or modifies data in the MongoDB instance.  There are three classes of write operations in MongoDB: Insert (Create) , Update, and Remove (Delete)  For the update and remove operations, you can specify criteria, or conditions, that identify the documents to update or remove.
  • 19.
    Write Operation- Create: Create operations add new documents to a collection.  In MongoDB, the db.collection.insert() method perform create operations.
  • 20.
    Write Operation- Update: Update operations modify existing documents in a collection.
  • 21.
    Write Operation- Delete: Delete operations remove documents from a collection.  In MongoDB, db.collection.remove() method performs delete operations.
  • 22.
  • 23.
    1.Insert a Documentwith insert() Method:  The following statement inserts a document with three fields into the collection inventory: db.inventory.insert( { _id: 10, type: "misc", item: "card", qty: 15 } )  In the example, the document has a user-specified _id field value of 10. The value must be unique within the inventory collection.
  • 24.
    Modify Document There are2 ways to update document: 1. Modify Multiple Documents with update() Method 2. Modify a Document with save() Method
  • 25.
    1.Modify Multiple Documentswith update() Method:  By default, the update() method updates a single document that matches its selection criteria.  Call the method with the multi option set to true to update multiple documents.  The following example finds all documents with type equal to “item_id" and modifies their qty field by 10. The example uses $inc, which is one of the update operators available. { "_id" : 1, "item_id" : "I001", "comp_id" : "C001", "qty" : 25, "prate" : 30, "srate" : 35, "mrp" : 40 } db.items.update( { item_id: "I001" },{ $inc: { qty: 10 }},{“multi”: true}); condition item_id is I001 have been updated and the qty became 35 from 25.
  • 26.
    2.Modify a Documentwith save() Method:  The save() method can replace an existing document. To replace a document with the save() method, pass the method a document with an _id field that matches an existing document.  The following example completely replaces the document with the _id equal to 10 in the inventory collection: db.inventory.save( { _id: 10, type: "misc", item: "playcard" } )
  • 27.
    Remove Document 1. RemoveAll Document:  To remove all documents from a collection, pass an empty query document {} to the remove() method. db.inventory.remove({}) 2. Remove Documents that Match a Condition:  To remove the documents that match a deletion criteria, call the remove() method with the <query> parameter. db.inventory.remove( { type : "food" } ) 3. Remove a Single Document that Matches a Condition:  To remove a single document, call the remove() method with the just One parameter set to true or 1. db.inventory.remove( { type : "food" }, 1 )
  • 28.
    Query Document- SpecifyConditions Using Query Operators  A query document can use the query operators to specify conditions in a MongoDB query.  The following example selects all documents in the inventory collection where the value of the type field is either ’food’ or ’snacks’: db.inventory.find( { type: { $in: [ 'food', 'snacks' ] } } )
  • 29.
    Query Document- SpecifyComparison operator AND Conditions In the following example, the query document specifies an equality match on the field food and a less than ($lt) comparison match on the field price: db.inventory.find( { $and:[ type: 'food', price: { $lt: 9.95 } ] } )  This query selects all documents where the type field has the value ’food’ and the value of the price field is less than 9.95. OR Conditions db.inventory.find( { $or: [ { qty: { $gt: 100 } }, { price: { $lt: 9.95 } } ] } )  In the above example, the query document selects all documents in the collection where the field qty has a value greater than ($gt) 100 or the value of the price field is less than ($lt) 9.95.
  • 30.
    Specify AND aswell as OR Conditions: db.inventory.find( { $and : [ { $or : [ { price : 0.99 }, { price : 1.99 } ] }, { $or : [ { sale : true }, { qty : { $lt : 20 } } ] } ] } )
  • 31.
  • 32.
    MongoDB Embedded Document.. Reference documents or linking documents
  • 33.