0% found this document useful (0 votes)
42 views21 pages

Dod Unit3

Uploaded by

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

Dod Unit3

Uploaded by

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

UNIT-3

MongoDB CRUD Operations:

MongoDB allows you to perform basic database operations known as


CRUD, which stands for Create, Read, Update, and Delete. These
operations are fundamental for interacting with any database system,
including MongoDB.

What is a Collection?: A collection in MongoDB is a grouping of MongoDB


documents. It is similar to a table in relational databases but is schema-
less, meaning documents can have different structures.
Create a Collection: Collections are created automatically when you insert
the first document into a collection. However, you can also create a
collection explicitly.
db.createCollection("myCollection")
What is a Capped Collection?: A capped collection is a fixed-size
collection where documents are stored in the insertion order and once
the size is reached, old documents are overwritten by new ones.
 Once the collection reaches its maximum size, new documents
overwrite the oldest ones. This makes capped collections useful for
use cases like logs or caches where only the most recent data is
important.
Use Cases of Capped Collections:
 Logging: Storing logs where only the most recent entries are
relevant.
 Cache Data: Managing cache that is frequently updated but has
limited storage.
db.createCollection("logs", {capped: true, size: 5000})
1. Create (Inserting Data):
 Purpose: This operation is used to add new data (documents) into a
collection.
 MongoDB collections are flexible, meaning you can insert
documents with varying structures (fields).
 Key Features:
o MongoDB automatically creates a collection if it doesn’t exist
when you insert the first document.
o No predefined schema is required, giving flexibility in data
structure.

Insert Documents:
In MongoDB, you can insert data into a collection using the insertOne() or
insertMany() methods. Inserting documents adds records to a collection.
(I). Insert One Document: The insertOne() method is used to insert a
single document into a collection
db.collection_name.insertOne({
field1: value1,
field2: value2,
})
Example: db.students.insertOne({
name: "John Doe",
age: 21,
course: "Computer Science"
})
 Explanation: This command inserts one document into the students
collection with fields like name, age, and course.
(II). Insert Multiple Documents: The insertMany() method is used to
insert multiple documents into a collection at once.
db.collection_name.insertMany([
{ field1: value1, field2: value2, ... },
{ field1: value3, field2: value4, ... },
])

Example:db.students.insertMany([
{ name: "Alice", age: 22, course: "Mathematics" },
{ name: "Bob", age: 20, course: "Physics" },
{ name: "Charlie", age: 23, course: "Engineering" }
])
Explanation: This command inserts three documents into the students
collection in one operation.
Example Scenario: Suppose you want to create a new user in your
database. When you insert this new user's information (e.g., name, age,
email), MongoDB adds it as a new document in the "users" collection.
db.users.insertOne({name: "John", age: 25})
db.users.insertMany([{name: "Jane", age: 30}, {name: "Sam", age: 22}])
Advantages:
 Schema-less nature: You can insert documents with different fields
without needing to follow a fixed schema.
 Automatic collection creation.
2. Read Operations in MongoDB
Read operations in MongoDB allows you to retrieve and query documents
from collections. MongoDB uses a variety of methods to fetch data,
including filtering documents based on specific criteria, sorting results,
limiting the number of documents returned, and more.
Here are the main read operations in MongoDB:
1. find() Method:
The find() method is the primary way to query a collection and retrieve
documents. It returns all documents that match the specified query
criteria.
Syntax:
db.collection_name.find(query, projection)
 query: Defines the criteria to match documents. If no query is
provided, all documents are returned.
 projection: Specifies which fields to include or exclude in the result
(optional).
Example 1: Retrieve All Documents
db.students.find()
 Explanation: Retrieves all documents from the students collection.
Example 2: Query with a Condition
db.students.find({ age: { $gte: 20 } })
 Explanation: Retrieves all students whose age is greater than or
equal to 20.
Example 3: Query with Projection
db.students.find({ age: { $gte: 20 } }, { name: 1, course: 1, _id: 0 })
 Explanation: Retrieves the name and course fields for students aged
20 or more, excluding the _id field.
2. findOne() Method:
The findOne() method retrieves a single document that matches the
query criteria. If multiple documents match, it returns the first document
found.
Syntax:
db.collection_name.findOne(query, projection)
Example:
db.students.findOne({ name: "Alice" })
 Explanation: Retrieves the first document from the students
collection where the name is "Alice".
3. Filtering with Query Operators:
MongoDB provides a variety of query operators to filter documents based
on different criteria, such as comparison, logical operators, and more.
Common Query Operators:
 Comparison Operators:
o $eq: Equal to
o $ne: Not equal to
o $gt: Greater than
o $lt: Less than
o $gte: Greater than or equal to
o $lte: Less than or equal to
Example:
db.students.find({ age: { $gte: 20, $lte: 25 } })
 Explanation: Retrieves students whose age is between 20 and 25,
inclusive.
 Logical Operators:
o $and: Match all specified conditions
o $or: Match any of the specified conditions
o $not: Inverts the query expression
o $nor: Matches documents that fail all conditions
Example:
db.students.find({ $or: [{ course: "Mathematics" }, { course: "Physics" }] })
 Explanation: Retrieves students who are enrolled in either
"Mathematics" or "Physics".
db.students.find({ $and: [ { age: { $gt: 20 } }, { course: "Mathematics" } ] })
 Explanation: This retrieves all students who are older than 20 and
enrolled in the "Mathematics" course.
4.Pagination with limit() and skip()
You can combine limit() and skip() to implement pagination, allowing you
to fetch documents in smaller, manageable chunks.
Example:
db.students.find().skip(10).limit(5)
 Explanation: Skips the first 10 documents and retrieves the next 5
documents. This can be useful for paginated data retrieval (e.g.,
showing data in pages).
5.Sorting Documents with sort():
The sort() method is used to arrange documents based on one or more
fields, either in ascending (1) or descending (-1) order.
Syntax:
db.collection_name.find(query).sort({ field: 1 })
Example:
db.students.find().sort({ age: -1 })
 Explanation: Retrieves all students sorted by age in descending
order.
6.Counting Documents with countDocuments():
The countDocuments() method returns the number of documents that
match the specified query criteria.
Syntax:
db.collection_name.countDocuments(query)
Example:
db.students.countDocuments({ course: "Computer Science" })
 Explanation: Returns the count of students who are enrolled in the
"Computer Science" course.
3. Update (Modifying Data)
MongoDB offers multiple ways to modify or update documents in a
collection. These operations allow users to make changes to specific
fields, add new fields, or even replace an entire document.Below are the
key update operations in MongoDB along with examples and
explanations:
1. updateOne()
The updateOne() method is used to update a single document that
matches a query condition. If there are multiple matches, only the first
document found is updated.
Syntax:
db.collection_name.updateOne(query, update, options)
 query: The criteria used to find the document to update.
 update: The changes to apply to the matched document. This often
uses update operators like $set or $inc.
 options: Optional parameters like upsert to insert a new document
if none matches.
Example:
db.students.updateOne(
{ name: "Alice" }, // Find the document where name is "Alice"
{ $set: { age: 23 } } // Set the age field to 23
)
 Explanation: This updates the first document where the name is
"Alice" by setting the age to 23. Other fields in the document
remain unchanged.
2. updateMany()
The updateMany() method is used to update all documents that match a
specified query. This is useful when you want to apply changes to multiple
documents at once.
Syntax: db.collection_name.updateMany(query, update, options)
Example:
db.students.updateMany(
{ course: "Computer Science" }, // Find all students in the
"Computer
Science" course
{ $set: { credits: 4 } } // Set the credits field to
4 for all matches
)
 Explanation: This updates the credits field to 4 for all students
enrolled in "Computer Science".
3. replaceOne()
The replaceOne() method replaces an entire document with a new one.
Unlike updateOne(), this replaces all fields in the document rather than
updating specific fields.
Syntax:
db.collection_name.replaceOne(query, replacement, options)
Example:
db.students.replaceOne(
{ name: "Bob" }, // Find the document where name is "Bob"
{ name: "Bob", age: 25, course: "Math" } // Replace the
) entire document
 Explanation: This completely replaces the document where name is
"Bob" with a new document containing name, age, and course. Any
previous fields not mentioned in the new document will be lost.

4. findOneAndUpdate()
The findOneAndUpdate() method finds a document, updates it, and can
return either the original or the updated document, depending on your
preference.
Syntax:
db.collection_name.findOneAndUpdate(query, update, options
 options: You can use returnNewDocument: true to return the
updated document.
Example:
db.students.findOneAndUpdate(
{ name: "Eve" }, // Find the document where name is "Eve"
{ $set: { course: "Physics" } },// Update the course to "Physics"
{ returnNewDocument: true } // Return the updated document
)
 Explanation: This updates Eve's course to "Physics" and returns the
updated document.
5. Update Operators in MongoDB
MongoDB provides various update operators to help you modify
documents more flexibly. Below are some common operators with
examples.
a. $set Operator
The $set operator sets the value of a specific field. If the field doesn't
exist, it creates it.
Example:
db.students.updateOne(
{ name: "John" },
{ $set: { age: 22, course: "Engineering" } }
)

 Explanation: This sets John's age to 22 and course to "Engineering".


If these fields don’t exist, they will be created.

b. $inc Operator
The $inc operator increments or decrements the value of a numeric field.
Example:
db.students.updateOne(
{ name: "Alice" },
{ $inc: { age: 1 } }
)
 Explanation: This increments Alice's age by 1.

c. $unset Operator
The $unset operator removes a field from a document.
Example:
db.students.updateOne(
{ name: "John" },
{ $unset: { age: "" } }
)
 Explanation: This removes the age field from the document where
name is "John".

d. $push Operator
The $push operator adds an element to an array in the document.
Example:
db.students.updateOne(
{ name: "Alice" },
{ $push: { subjects: "Math" } }
)

 Explanation: This adds "Math" to Alice's subjects array.

e. $addToSet Operator
The $addToSet operator adds an element to an array, but only if it does
not already exist.
Example:
db.students.updateOne(
{ name: "Alice" },
{ $addToSet: { subjects: "Math" } }
)
 Explanation: This adds "Math" to Alice's subjects array only if it isn’t
already present.

f. $pull Operator
The $pull operator removes all instances of a value from an array.
Example:
db.students.updateOne(
{ name: "John" },
{ $pull: { subjects: "Chemistry" } }
)
 Explanation: This removes "Chemistry" from John's subjects array.

g. $rename Operator
The $rename operator is used to rename a field in a document.
Example:
db.students.updateOne(
{ name: "Alice" },
{ $rename: { "course": "major" } }
)
 Explanation: This renames the course field to major in the
document where name is "Alice".

6. Upsert Option
The upsert option allows MongoDB to insert a new document if no
document matches the query during an update operation. This combines
the functionality of an update and insert.
Example:
db.students.updateOne(
{ name: "Eve" }, // Query to find the document where name is "Eve"
{ $set: { age: 24, course: "Biology" } }, // If no
document is found, insert this
{ upsert: true } // Use the upsert option
)

 Explanation: If no document with name "Eve" is found, a new


document with the specified values (age and course) will be
inserted.
Delete Operations in MongoDB:
In MongoDB, delete operations are used to remove documents from a
collection. You can perform delete operations using two main methods:
1. deleteOne(): Deletes a single document that matches the specified
criteria.
2. deleteMany(): Deletes all documents that match the specified
criteria.
Here’s a detailed breakdown:
1. deleteOne()
 Purpose: This command removes the first document that matches
the specified filter criteria. It only deletes one document, even if
multiple documents match the criteria.
 Syntax:
db.collection.deleteOne(<filter>)
 Example: Suppose you have a collection called customers and you
want to delete a document where the field name is "John":
db.customers.deleteOne({ name: "John" })
 Result: Only the first document with the name "John" will be
deleted from the customers collection.
2. deleteMany()
 Purpose: This command removes all documents that match the
specified filter criteria.
 Syntax:
db.collection.deleteMany(<filter>)
 Example: If you want to delete all documents where the field status
is "inactive":
db.customers.deleteMany({ status: "inactive" })
 Result: Every document in the customers collection where status
equals "inactive" will be deleted.
3. Dropping a Collection
If you want to delete all documents in a collection, you can simply drop
the entire collection.
 Syntax:
db.collection.drop()
 Example: To drop the entire customers collection:
db.customers.drop()
 Result: The customers collection will be completely removed from
the database, along with all its documents.
Examples for Each Command:
Example 1: Using deleteOne() to delete a single document
db.employees.deleteOne({ employeeID: "EMP001" })
This will delete the first document that has the employeeID "EMP001".
Example 2: Using deleteMany() to delete multiple documents
db.products.deleteMany({ category: "Electronics" })
This will delete all documents from the products collection where the
category is "Electronics".
Example 3: Dropping an entire collection
db.orders.drop()
This will delete the entire orders collection, removing all its documents
and indexes.

Important Points to Note:


1. Careful with deleteMany(): Deleting multiple documents using
deleteMany() is irreversible, so be cautious when specifying the
filter criteria.
2. Dropping a collection is final: When a collection is dropped, all
documents and indexes associated with the collection are
permanently deleted.
3. No Undo: MongoDB doesn’t have a rollback feature for delete
operations. Once a document or collection is deleted, the data
cannot be recovered unless you have a backup.

Working with Arrays in MongoDB:


MongoDB provides robust support for working with arrays, allowing you
to store and manipulate multiple values in a single field. Arrays can hold
various types of data such as strings, numbers, objects (documents), or
even other arrays.
Key Array Operations in MongoDB:
1. Inserting Arrays
2. Querying Arrays
3. Updating Arrays
4. Removing Elements from Arrays
Let’s break down each of these operations with examples.
1. Inserting Arrays
When you insert a document into a MongoDB collection, an array can be
one of the fields in that document.
 Syntax:
db.collection.insertOne({
fieldName: [ value1, value2, value3, ... ]
})
 Example: Suppose we are working with a students collection, where
each document contains a field grades that stores an array of
grades:
db.students.insertOne({
name: "Alice",
grades: [85, 90, 78]
})
Here, the document for Alice contains an array of three grades.
2. Querying Arrays
MongoDB allows you to query arrays in several ways, including finding
documents where an array contains a specific value or set of values.
a) Querying for an Exact Match
You can query for documents where a specific array field contains exactly
a specific value.
 Example: Find all students who have the grade 90 in their grades
array:
db.students.find({ grades: 90 })
This query returns all students where one of the elements in the grades
array is 90.
b) Querying for All Elements in an Array
To query for documents where the array matches a specific set of
elements, you can use the $all operator.
 Example: Find students who have both 85 and 90 in their grades:
db.students.find({ grades: { $all: [85, 90] } })
This returns students where the grades array contains both 85 and 90.
c) Querying for Specific Array Elements by Index
You can query for array elements at a specific index using dot notation.
 Example: Find students whose first grade is 85:
db.students.find({ "grades.0": 85 })
This query looks at the element at index 0 of the grades array and
matches those that equal 85.
d) Querying for Array Size
You can also query for the size of an array using the $size operator.
 Example: Find students with exactly three grades:
db.students.find({ grades: { $size: 3 } })
3. Updating Arrays
MongoDB provides operators to update individual elements within arrays.
a) Updating an Array Element by Index
You can update a specific element in an array using the positional
operator $.
 Example: Update the second grade (index 1) of a student named
Alice to 95:
db.students.updateOne(
{ name: "Alice" },
{ $set: { "grades.1": 95 } }
)
Here, the second element in the grades array is updated to 95.
b) Adding Elements to an Array
You can add elements to an array using the $push operator.
 Example: Add the grade 88 to Alice’s grades array:
db.students.updateOne(
{ name: "Alice" },
{ $push: { grades: 88 } }
)
This adds the value 88 to the end of the grades array.
c) Adding Multiple Elements to an Array
To add multiple elements to an array, use the $each modifier along with
$push.
 Example: Add 87 and 92 to Alice’s grades array:
db.students.updateOne(
{ name: "Alice" },
{ $push: { grades: { $each: [87, 92] } } }
)
d) Adding Unique Elements to an Array
The $addToSet operator only adds elements to an array if they don’t
already exist in the array.
 Example: Add 90 to Alice’s grades, but only if it’s not already
present:
db.students.updateOne(
{ name: "Alice" },
{ $addToSet: { grades: 90 } }
)
4. Removing Elements from Arrays
MongoDB provides options to remove elements from an array.
a) Removing an Element from an Array
You can use the $pull operator to remove specific elements from an array.
 Example: Remove all grades equal to 78 from Alice’s grades array:
db.students.updateOne(
{ name: "Alice" },
{ $pull: { grades: 78 } }
)
This removes the value 78 from the grades array.
b) Removing Multiple Elements
You can remove multiple elements based on a condition using $pull.
 Example: Remove all grades less than 80 from the grades array:
db.students.updateOne(
{ name: "Alice" },
{ $pull: { grades: { $lt: 80 } } }
)
c) Removing the Last or First Element of an Array
You can use $pop to remove the last or first element of an array.
 Example: Remove the last grade in Alice’s grades array:
db.students.updateOne(
{ name: "Alice" },
{ $pop: { grades: 1 } }
)
 Example: Remove the first grade in Alice’s grades array:
db.students.updateOne(
{ name: "Alice" },
{ $pop: { grades: -1 } }
)

Summary of Key Operators:


Operator Description
$push Adds an element to an array
$each Adds multiple elements to an array
$addToSet Adds unique elements to an array
$pull Removes elements from an array
$pop Removes the first or last element
$size Queries based on array size
Queries based on array containing all
$all
elements
By using MongoDB’s array operators, you can store, query, update, and
manipulate array data efficiently, giving you a lot of flexibility when
working with complex data structures.

You might also like