Notes-Lecture 14 - MongoDB with NodeJS - II-3447
Notes-Lecture 14 - MongoDB with NodeJS - II-3447
Example:
db.collection.updateOne(
{ _id: ObjectId("your_document_id") },
{ $pull: { arrayField: { $in: ["value1", "value2"] } } }
);
In this example, elements matching "value1" and "value2" will be removed from the
arrayField.
Indexes in MongoDB
Introduction to Indexes
Note: The number 1 indicates ascending order. Use -1 for descending order.
Compound Indexes
Compound indexes involve multiple fields. They can significantly enhance query
performance for complex queries that involve multiple fields. Let's create a
compound index for our “products” collection:
● Filtering by Category and Price Range: If users often search for products
within a specific category and price range, the compound index will speed up
these queries.
Comparison Operators
Comparison operators help you compare values and retrieve documents that match
specific conditions. Here are some common comparison operators:
● $eq: Equals
● $ne: Not Equals
● $gt: Greater Than
● $lt: Less Than
● $gte: Greater Than or Equal
● $lte: Less Than or Equal
Use Case:
Imagine you have an e-commerce database with a ‘products’ collection. You want to
find products with prices between $50 and $100.
Logical Operators
Logical operators allow you to combine multiple conditions in your queries. Here are
some common logical operators:
Use Case:
Suppose you want to find products that are either premium products (price > $200)
or products on discount (price < $50).
db.products.find({
$or: [
{ price: { $gt: 200 } }, // Premium products
{ price: { $lt: 50 } } // Discounted products
]
});
You can combine comparison and logical operators to create more complex queries.
Use Case:
Premium Products with High Ratings
To find premium products (price > $200) with a high rating (rating > 4):
db.products.find({
$and: [
{ price: { $gt: 200 } }, // Premium products
{ rating: { $gt: 4 } } // High rating
]
});
Projection operators are powerful tools in MongoDB that allow you to control which
fields to include or exclude in query results. They provide flexibility in shaping query
outputs to match your specific needs. Let's delve into how projection operators work
and explore real-world use cases.
Basic Projection
The basic projection involves specifying which fields you want to retrieve from the
documents in your query results. Here are the key projection operators:
Imagine you have a ‘users’ collection with various fields, but you only need the
username and email of each user.
Conditional Projection
Projection operators can be combined with query conditions to project fields
conditionally.
Suppose you have a subscribers collection and want to display email addresses only
for users with premium subscriptions.
Aggregation operators are a versatile toolset in MongoDB that allows you to process
and transform data to gain insights and perform complex operations. They enable
you to manipulate, reshape, and summarize data within your collections. Let's
explore how aggregation operators work and delve into practical scenarios.
Basic Aggregation
The basic aggregation operation involves stages that process documents in
sequence. Here's an overview of some key aggregation stages:
● $match: Filters documents based on specified criteria.
● $group: Groups documents by specific fields and performs aggregate
calculations.
● $project: Shapes the output documents by including or excluding fields.
● $sort: Sorts documents based on specified fields.
Consider a ‘products’ collection with name, category, and rating fields. You want to
calculate the average rating for each category.
db.products.aggregate([
{
$group: {
_id: "$category",
avgRating: { $avg: "$rating" }
}
}
]);
You can chain multiple aggregation stages to perform more complex operations.
Given the same products collection, you want to find the top categories with the
highest average price.
db.products.aggregate([
{
$group: {
_id: "$category",
avgPrice: { $avg: "$price" }
}
},
{
$sort: { avgPrice: -1 }
},
{
$limit: 5
}
]);
Aggregation Expressions
Assuming you have an ‘orders’ collection with quantity and price fields, you want to
calculate the total revenue.
db.orders.aggregate([
{
$project: {
totalRevenue: { $multiply: ["$quantity", "$price"] }
}
},
{
$group: {
_id: null,
total: { $sum: "$totalRevenue" }
}
}
]);
Imagine you're processing an order, which involves deducting the product quantity
and updating the order status. A session ensures these operations succeed together.
Starting a Transaction
Transactions are used to group multiple operations as a single atomic unit. You start
a transaction using the startTransaction method within a session.
Suppose you're transferring money between accounts. You want to deduct from one
account and credit to another, ensuring that both actions are completed or none at
all.
session.startTransaction();
Committing a Transaction
To make the changes within a transaction permanent, you commit the transaction
using the commitTransaction method.
In a reservation system, you're booking seats for a concert. The reservation is only
confirmed when payment is successful and the transaction is committed.
session.commitTransaction();
Aborting a Transaction
If a transaction encounters an issue, you can abort it to discard any changes using
the abortTransaction method.
Use Case: Online Store Checkout
During checkout, if a user's payment fails, you'd want to abort the transaction to
prevent changes to the order and inventory.
session.abortTransaction();
Ending a Session
Once you've completed all necessary operations, you can end the session using the
endSession method.
After a user registers, you might have multiple operations like sending emails,
creating profiles, and more. An ended session ensures these operations conclude.
session.endSession();
client.close();
// Connection URL
const uri = "mongodb://localhost:27017";
// Start a session
const session = client.startSession();
// Start a transaction
session.startTransaction();
try {
// Insert a document
await collection.insertOne({ name: "Transaction 1" });
console.log("Document inserted");
Explanation:
● Define the main function where all the MongoDB operations take place.
● Inside the main function, we start by connecting to the MongoDB server using
await client.connect().
● Define the database and collection you want to work with using
client.db("mydb") and database.collection("transactions").
● After all the transaction handling, we close the MongoDB client connection
using await client.close().