Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 35

MongoDB

Convert your data to JSON


MongoDB Create Collection
• db.createCollection(‘Student’);
• This is optional
• Collection can be created on fly
• When you insert the very first document
MongoDB Insert
• If the collection does not exist, then the
insert() method will create the collection.
• Insert the document : • MongoDb Insert
• db.student.insert({
"sID": 123,
"sName": "Amy",
"GPA": 3.9,
"sizeHS": 1000

• SQL Statement for insert


})

• insert into Student values (123, 'Amy', 3.9,


1000);
_id Field
• If the document does not specify an _id field,
• then MongoDB will add the _id field and
• assign a unique ObjectId for the document before inserting.
• If the document contains an _id field,
• the _id value must be unique within the collection to avoid duplicate
key error.
Insert a Document without
Specifying an _id Field
• The document passed to the insert() method does not contain the _id field:

• db.products.insert( { item: "card", qty: 15 } )

• During the insert, mongod will create the _id field and assign it a unique ObjectId
value, as verified by the inserted document:

• { "_id" : ObjectId("5063114bd386d8fadbd6b004"), "item" : "card", "qty" : 15 }

• The ObjectId values are specific to the machine and time when the operation is
run.
• As such, your values may differ from those in the example.
Insert a Document Specifying an _id
Field
• In the following example, the document passed to the
insert() method includes the _id field.
• The value of _id must be unique within the collection to
avoid duplicate key error.
• db.products.insert( { _id: 10, item: "box", qty: 20 } )
• The operation inserts the following document in the
products collection:
• { "_id" : 10, "item" : "box", "qty" : 20 }
Insert Multiple Documents
• The following example performs a bulk insert of three
documents by passing an array of documents to the insert()
method.
• By default, MongoDB performs an ordered insert.
• With ordered inserts,
• if an error occurs during an insert of one of the documents,
• MongoDB returns on error without processing
The documents the do
in the array remaining
not need to have the
documents in the array.
db.products.insert(
same fields.
[
For instance, the first document in the array has
{ _id: 11, item: "pencil", qty: 50, type: "no.2" },
an _id field and a type field.
{ item: "pen", qty: 20 },
Because the second and third documents do not
{ item: "eraser", qty: 25 }
contain an _id field, 
]
mongod will create the _id field for the second and
)
third documents during the insert
Output
• The operation inserted the following three
documents:
{ "_id" : 11, "item" : "pencil", "qty" : 50, "type" : "no.2" }
{ "_id" : ObjectId("51e0373c6f35bd826f47e9a0"), "item" : "pen", "qty" : 20 }
{ "_id" : ObjectId("51e0373c6f35bd826f47e9a1"), "item" : "eraser", "qty" : 25 }
Perform an Unordered Insert

• The following example performs an unordered insert of


three documents.
• 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.
db.products.insert(
[
{ _id: 20, item: "lamp", qty: 50, type: "desk" },
{ _id: 21, item: "lamp", qty: 20, type: "floor" },
{ _id: 22, item: "bulk", qty: 100 }
],
{ ordered: false }
)
db.collection.insertOne()
• Inserts a document into a collection.
• Insert a Document without Specifying an _id Field
• db.products.insertOne( { item: "card", qty: 15 } );
• Insert a Document Specifying an _id Field
• db.products.insertOne( { _id: 10, item: "box", qty: 20 } );
• Inserting an duplicate value for any key that is part of a unique
index, such as _id, throws an exception
WriteError({
"index" : 0,
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: inventory.products index: _id_ dup key: { : 10.0 }",
"op" : { "_id" : 10, "item" : "packing peanuts", "qty" : 200 }
})
db.collection.insertMany()
• Inserts multiple documents into a collection.
db.products.insertMany( [ db.products.insertMany( [
{ item: "card", qty: 15 }, { _id: 10, item: "large box", qty: 20 },
{ item: "envelope", qty: 20 }, { _id: 11, item: "small box", qty: 55 },
{ item: "stamps" , qty: 30 } { _id: 12, item: "medium box", qty: 30 }
] ); ] );
db.products.insertMany( [
While the document with
{ _id: 10, item: "large box", qty: 20 },
• item: "medium box" and
{ _id: 11, item: "small box", qty: 55 },
• item: "tape"
{ _id: 11, item: "medium box", qty: 30 },
failed to insert due to duplicate _id values,
{ _id: 12, item: "envelope", qty: 100},
nInserted shows that the remaining 5
{ _id: 13, item: "stamps", qty: 125 },
documents were inserted.
{ _id: 13, item: "tape", qty: 20},
{ _id: 14, item: "bubble wrap", qty: 30}
], { ordered: false } );
db.products.find().pretty();
Insert Methods
• MongoDB provides the following methods for
inserting documents into a collection:
• db.collection.insertOne()
• Inserts a single document into a collection.
• db.collection.insertMany()
• inserts multiple documents into a collection.
• db.collection.insert()
• inserts a single document or multiple documents into a collection.
Update Methods

•update()
•updateOne()
•updateMany()
•replaceOne()
Update Operators

•$set •$currentDate
•$unset •$pop
•$rename •$addToSet
•$inc
•$mul
Update method syntax
update() updateOne() updateMany()

db.<collection>.method(<query>, <update>, <options>)
$set
• Update the GPA of sID 123 to 4.2
• db.student.update(
{"sID":123}, //Query
{$set:{ //update
"GPA":4.2
}
},
{} //update options (Optional)
)
$set
• $set could also be used to add new fields and well as update
multiple fileds
• db.student.update(
{"sID":123},
{$set:{
"sizeHS":1001, "GPA":4.0, "placed":"yes"
}
}
)
$set
• $set use to update a document
• Update the grade od sID 123 in Big Data to D+
• db.student.update(
{sID:123, "marks.sub":"Big Data"},
{$set:
{"marks.$.grade":"D+“
}
}
)
$addToSet
• Add an email id amy123@gla.ac.in of sID 123
• db.student.update(
{sID:123},
{$addToSet:
{"email":"amy123@gla.ac.in"}
}
)
$addToSet
• Add an email id amy123@yahoo.com and amy.cse@fb.com of
sID 123
• db.student.update(
{sID:123},
{$addToSet:
{"email":"amy123@gla.ac.in"}
}
)
$unset
• $unset use to delete a particular field
• db.student.update(
{"sID":123},
{$unset:{
"placed":""
}
}
)
Query Documents
• Select All Documents in a Collection
• To select all documents in the collection, pass an empty document
as the query filter parameter to the find method. The query filter
parameter determines the select criteria:
• db.inventory.find( {} )

• This operation corresponds to the following SQL statement:


• SELECT * FROM inventory
Specify Equality Condition
• To specify equality conditions, use <field>:<value>
expressions in the query filter document:
• { <field1>: <value1>, ... }
• The following example selects from the inventory collection
all documents where the status equals "D":
• db.inventory.find( { status: "D" } )
• This operation corresponds to the following SQL statement:
• SELECT * FROM inventory WHERE status = "D"
Specify Conditions Using Query
Operators
• A query filter document can use the query operators to
specify conditions in the following form:
• { <field1>: { <operator1>: <value1> }, ... }
• The following example retrieves all documents from the
inventory collection where status equals either "A" or "D":
• db.inventory.find( { status: { $in: [ "A", "D" ] } } )
• The operation corresponds to the following SQL statement:
• SELECT * FROM inventory WHERE status in ("A", "D")
Specify AND Conditions
• A compound query can specify conditions for more than one
field in the collection’s documents.
• Implicitly, a logical AND conjunction connects the clauses of
a compound query so that the query selects the documents
in the collection that match all the conditions.
Specify AND Conditions
• The following example retrieves all documents in the
inventory collection where the status equals "A" and qty is
less than ($lt) 30:

• db.inventory.find( { status: "A", qty: { $lt: 30 } } )

• The operation corresponds to the following SQL statement:


• SELECT * FROM inventory WHERE status = "A" AND qty < 30
Specify OR Conditions
• Using the $or operator, you can specify a compound query
that joins each clause with a logical OR conjunction so that
the query selects the documents in the collection that
match at least one condition.
• The following example retrieves all documents in the
collection where the status equals "A" or qty is less than
($lt) 30:
• db.inventory.find( { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] } )
• The operation corresponds to the following SQL statement:
• SELECT * FROM inventory WHERE status = "A" OR qty < 30
Specify AND as well as OR Conditions
• In the following example, the compound query document
selects all documents in the collection where
• the status equals "A" and
• either qty is less than ($lt) 30 or item starts with the character p:
• db.inventory.find( {
• status: "A",
• $or: [ { qty: { $lt: 30 } }, { item: /^p/ } ]
• })
• The operation corresponds to the following SQL statement:
• SELECT * FROM inventory WHERE status = "A" AND ( qty < 30 OR
item LIKE "p%")
Query on Embedded/Nested
Documents

db.inventory.insertMany( [
{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }
]);
Match an Embedded/Nested Document
• the following query selects all documents where the field
size equals the document { h: 14, w: 21, uom: "cm" }
• db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } } )
• Equality matches on the whole embedded document require
an exact match of the specified <value> document, including
the field order.
• For example, the following query does not match any
documents in the inventory collection:
• db.inventory.find( { size: { w: 21, h: 14, uom: "cm" } } )
Specify Equality Match on a Nested
Field
• The following example selects all documents where the field
uom nested in the size field equals "in":
• db.inventory.find( { "size.uom": "in" } )
• To specify a query condition on fields in an embedded /
nested document,
• use dot notation ("field.nestedField").
Specify Match using Query Operator
• A query filter document can use the query operators to
specify conditions in the following form:
• { <field1>: { <operator1>: <value1> }, ... }
• The following query uses the less than operator ($lt) on the
field h embedded in the size field:
• db.inventory.find( { "size.h": { $lt: 15 } } )
Specify AND Condition
• The following query selects all documents where the nested
field h is less than 15, the nested field uom equals "in", and
the status field equals "D":
• db.inventory.find( {
• "size.h": { $lt: 15 },
• "size.uom": "in",
• status: "D"
• })

You might also like