Dod Unit3
Dod Unit3
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" } }
)
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" } }
)
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
)