0% found this document useful (0 votes)
4 views47 pages

Module 4

This document covers CRUD operations in MongoDB, detailing methods for creating, reading, updating, and deleting documents. It explains various insert operations, including single and batch inserts, as well as bulk operations and their implications. Additionally, it provides examples of querying documents and modifying data, along with case studies and exercises for practical application.

Uploaded by

user-256473
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views47 pages

Module 4

This document covers CRUD operations in MongoDB, detailing methods for creating, reading, updating, and deleting documents. It explains various insert operations, including single and batch inserts, as well as bulk operations and their implications. Additionally, it provides examples of querying documents and modifying data, along with case studies and exercises for practical application.

Uploaded by

user-256473
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 47

Department of

Artificial Intelligence & Machine Learning

22AML64A
Next-Gen Database Technology using MongoDB
Module 4

CRUD Operations in MongoDB: Data Modification in MongoDB, Batch Insert


in MongoDB, Ordered Bulk Insert, Performing Ordered Bulk Insert, Unordered
Bulk Insert, Inserts: Internals and Implications, Retrieving the documents, $in,
$or , and “AND” Conditions, Regular Expression, $Where Query, Advance query
option, Update Operation, Replacing Existing Document with New Document,
Removing Documents, Case Study: MongoDB using CRUD operations
Reference : https://www.mongodb.com/docs/manual/crud/
Data Modification in MongoDB
• Data Modification Using CRUD Operations
• Create: Adds new entries to the database, effectively increasing the
data set.
• Read: Retrieves and displays data but does not modify it. This
operation is crucial for verifying changes before or after data
modification.
• Update: Alters existing data to reflect new information or correct
errors.
• Delete: Removes data that is no longer needed or is incorrect.
https://www.mongodb.com/docs/manual/crud/
MongoDB CRUD Operations
CRUD operations create, read, update, and delete documents

Create Operations
• Create or insert operations add new documents to a collection. If the
collection does not currently exist, insert operations will create the collection.

• MongoDB provides the following methods to insert documents into a


collection:

• db.collection.insertOne()

• db.collection.insertMany()
Insert Operation : Single document

https://www.mongodb.com/docs/manual/reference/method/db.collection.insertOne/
Insert Operation : Single document
• In MongoDB, insert operations target a single collection. All write operation in
MongoDB are atomic on the level of a single document
• db.collection.insertOne() inserts a single document into a collection.
Ex.
db.inventory.insertOne(
{ item: "canvas",
qty: 100,
tags: ["cotton"],
size: { h: 28, w: 35.5}
})
• To retrieve the document that you just inserted
db.inventory.find( { item: "canvas" } )
Insert Multiple Documents(Batch
Insert)
Syntax
• The insertMany() method has the following syntax:

https://www.mongodb.com/docs/manual/reference/method/db.collection.insertMany/
Insert Multiple Documents

• db.collection.insertMany() can insert multiple documents into a


collection. Pass an array of documents to the method
db.inventory.insertMany([
{ item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21} },
{ item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5 } },
{ item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85} }
])
Additional Methods for Inserts

• The following methods can also add new documents to a collection:


Bulk Insert
• The bulkWrite() method in MongoDB allows for the execution of multiple write operations with a
single command

https://www.mongodb.com/docs/manual/reference/method/db.collection.bulkWrite/#mongodb-method-db.collection.b
ulkWrite
• db.students.bulkWrite([

{ insertOne:
{“document”:{studentId:4, studentName:”GeekD”, studentAge:24}}},

{insertOne:
{“document”:{studentId:4, studentName:”GeekD”, studentAge:24}}}
{ updateOne :
{ "filter" : { "studentId" : 2 },
"update" : { $set : { "studentName" : "GeekyBest" } }
}}
]);
Ordered Bulk Insert
• With an ordered list of operations, MongoDB executes the operations
serially.
• If an error occurs during the processing of one of the write
operations, MongoDB will return without processing any remaining
write operations in the list
• Bulk()
• Bulk operations builder used to construct a list of write operations to perform
in bulk for a single collection. To instantiate an ordered bulk operation use -
db.collection.initializeOrderedBulkOp() method
Performing Ordered Bulk Insert
• With an ordered operations list, MongoDB executes the write
operations in the list serially
• When executing an ordered list of operations, MongoDB groups the
operations by the operation type and contiguity; i.e. contiguous
operations of the same type are grouped together
• For example, if an ordered list has two insert operations followed by an
update operation followed by another insert operation-
• MongoDB groups the operations into three separate groups:
• first group contains the two insert operations,
• second group contains the update operation
• third group contains the last insert operation
Performing Ordered Bulk Insert
Unordered Bulk Insert
• When executing an unordered list of operations, MongoDB groups the
operations.
• With an unordered bulk operation, the operations in the list may be reordered to
increase performance.
• As such, applications should not depend on the ordering when performing
unordered bulk operations.
• Bulk()
• Bulk operations builder used to construct a list of write operations to perform
in bulk for a single collection. To instantiate an ordered bulk operation use -
db.collection.initializeUnorderedBulkOp() method.

https://www.mongodb.com/docs/manual/reference/method/db.collection.initializeUnorderedBulkOp/
Unordered Bulk Insert
Retrieving the documents
• db.collection.find() retrieves the documents of a collection
Exercise -1 : Student Database
Create database, Create collection, insert data, find, limit, sort, skip, distinct.
Create a student database with the fields: (USN, Sname, Sem, Branch, CGPA)
Solve the following queries –
• Display all the documents
• Display all the students in AIML
• Display all the students in ascending order
• Display first 5 students
• List the degree of student “XYZ"
• Display students details of 5,6,7 in descending order of percentage
• Display the number of students in CSE
• Display all the distinct degrees
• Display all the ISE students with CGPA greater than 6, but less than 7.5
• Display all the students in AIDS and in 6th Sem
Create a MongoDB database and collection to store student information (USN, Sname, Sem, Branch, CGPA). Perform the below
data manipulation and analysis tasks using MongoDB queries
a. Demonstrate insertion of multiple documents 2M
Solution:
db.students.insertMany([
{ USN: "USN001", Sname: "Alice", Sem: 5, Branch: "CSE", CGPA: 8.2 },
{ USN: "USN002", Sname: "Bob", Sem: 3, Branch: "AIML", CGPA: 7.5 },
{ USN: "USN003", Sname: "Charlie", Sem: 4, Branch: "ISE", CGPA: 6.8 },
{ USN: "USN004", Sname: "David", Sem: 6, Branch: "CSE", CGPA: 9.1 },
{ USN: "USN005", Sname: "Eva", Sem: 2, Branch: "AIML", CGPA: 7.0 }]);

b. Display all the documents 2M


Solution:
db.students.find().pretty()
c. Display all the students in AIML 2M
Solution:
db.students.find({ Branch: "AIML" }).pretty()
d. Display the number of students in CSE 2M
Solution:
db.students.countDocuments({ Branch: "CSE" })
e. Display all the ISE students with CGPA greater than 6, but less than 7.5 2M
Solution:
db.students.find({ Branch: "ISE", CGPA: { $gt: 6, $lt: 7.5 } }).pretty()
$in
The $in operator selects the documents where the value of a field
equals any value in the specified array

https://www.mongodb.com/docs/manual/reference/operator/query/in/
$or
The $or operator performs a logical OR operation on an array of one or more
<expressions> and selects the documents that satisfy at least one of the
<expressions>

This query will select all documents in the inventory collection where either the quantity field value is less
than 20 or the price field value equals 10.
https://www.mongodb.com/docs/manual/reference/operator/query/or/
$or
$and
$and performs a logical AND operation on an array of one or more
expressions (<expression1>, <expression2>, and so on) and selects the
documents that satisfy all the expressions.

The following query, which contains multiple expressions supplied to


$and, may produce an error if there is any document where $x is 0:

https://www.mongodb.com/docs/manual/reference/operator/query/and/
$and
Regular Expression
$regex
• Provides regular expression capabilities for pattern
matching strings in queries.

• In MongoDB, you can also use regular expression objects (i.e.


/pattern/) to specify regular expressions:

https://www.mongodb.com/docs/manual/reference/operator/query/regex/
$Where Query
• Use the $where operator to pass either a string containing a
JavaScript expression or a full JavaScript function to the query system.
• The $where provides greater flexibility, but requires that the database
processes the JavaScript expression or function for each document in
the collection.
• Reference the document in the JavaScript expression or function
using either this or obj
$Where Query -Example
json javascript
{ db.products.find({
"_id": 1, $where: function() {
"name": "Product A",
return this.price * this.quantity > 3000;
"price": 50,
"quantity": 100
}
} })
{
"_id": 2, In this example:
"name": "Product B", • this refers to the current document being
"price": 70, evaluated.
"quantity": 20 • The JavaScript function checks if the product's
} total value (price * quantity) exceeds 3000.
Advance query option
• Array query operators – https://www.mongodb.com/docs/manual/reference/operator/query-array/
• Projection query operators - https://www.mongodb.com/docs/manual/reference/operator/projection/
• Bitwise query operators – https://www.mongodb.com/docs/manual/reference/operator/query-bitwise/
• Geospatial query operators - https://www.mongodb.com/docs/manual/reference/operator/query-geospatial/
Update Operation
• update operations are used to modify existing documents in a
collection
• mongosh leverages the following methods for update operations –
Update Operators – Field Update Operators
• MongoDB provides several update operators to perform specific operations on fields:

For examples on the given operators : https://www.mongodb.com/docs/manual/reference/operator/update-field/


Update Operators – Array Update Operators

For examples on the given operators : https://www.mongodb.com/docs/manual/reference/operator/update-array/


Update Operators – Bitwise Update Operator

For examples on the given operators : https://www.mongodb.com/docs/manual/reference/operator/update-bitwise/


Replacing Existing Document with New
Document
• To replace the entire content of a document except for the _id field, pass an
entirely new document as the second argument to db.collection.replaceOne().

• When replacing a document, the replacement document must consist of only


field/value pairs; i.e. do not include update operators expressions.
• Ex.
db.inventory.replaceOne(
{ item: "paper" },
{ item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 40 } ] }
)
Removing Documents
• You can delete documents in MongoDB using the
following mongosh methods:
• db.collection.deleteMany()
• db.collection.deleteOne()
• Delete All Documents :
• Delete All Documents that Match a Condition :
Removing Documents
Case Study: MongoDB using CRUD
operations
Exercise -1 :
• Create an employee database with the fields: {eid, ename, dept, desig,
salary, yoj, address{dno, street, locality, city}}
• Demonstrate Update modifiers ($set, $unset, $inc, $push, $pushAll,
$pull, $pullAll, $addToSet)
Exercise -2 :
• Create a book Data Base with the fields: (isbn, bname, author[], year,
publisher, price)
• Create database, Create collection, insert data, find, sort, limit, $all, $in.
Case Study: MongoDB using CRUD
operations
Exercise-3
• Create a database with suitable example using MongoDB and
implement
• Inserting and saving document (batch insert, insertvalidation)
• Removingdocument
• Updating document (document replacement, using modifiers,
upserts,updating multiple documents, returning updateddocuments)

You might also like