Ex 9,10,11
Ex 9,10,11
1. Connecting to MongoDB
mongo
2. Show Databases
show dbs
Example output:
admin 0.000GB
local 0.000GB
test 0.000GB
This switches to the myDatabase database (it will be created if it doesn’t exist).
Example output:
users
products
orders
MongoDB creates collections automatically when you insert data, so creating a collection
explicitly is often unnecessary. But you can still use:
db.createCollection("myCollection")
6. Insert Documents
db.products.insertMany([
{ name: "Laptop", price: 1200 },
{ name: "Smartphone", price: 800 }
])
7. Query Documents
Example output:
json
Copy code
{ "_id": ObjectId("60d5c72f8f1b2b56d84a1e9f"), "name": "Alice", "age": 25,
"email": "[email protected]" }
Example output:
8. Update Documents
db.users.updateOne(
{ name: "Alice" },
{ $set: { age: 26 } }
)
db.products.updateMany(
{ price: { $lt: 1000 } },
{ $set: { onSale: true } }
)
9. Delete Documents
db.orders.aggregate([
{ $match: { status: "shipped" } },
{ $group: { _id: "$customerId", totalAmount: { $sum: "$amount" } } },
{ $sort: { totalAmount: -1 } }
])
This example finds orders with status "shipped", groups them by customerId, calculates the
total amount for each customer, and sorts the results in descending order of total amount.
This command drops the current database (be cautious with this as it deletes all data).
Ex 10
1. Connect to MongoDB
mongo
use myDatabase
db.users.insertOne({
"_id": ObjectId("609b2e5d6c73724c5c8bf20e"),
"username": "user123",
"email": "[email protected]",
"password": "hashed_password",
"profile": {
"name": "John Doe",
"bio": "Software Engineer | Blogger | MongoDB Enthusiast",
"avatar_url": "https://example.com/avatar.jpg"
},
"created_at": ISODate("2023-05-01T08:00:00Z")
})
b. Products Collection
db.products.insertOne({
"_id": ObjectId("609b2e5d6c73724c5c8bf20f"),
"name": "Laptop",
"description": "A powerful laptop for all your needs",
"price": 1099.99,
"stock_quantity": 100
})
c. Orders Collection
db.orders.insertOne({
"_id": ObjectId("609b2e5d6c73724c5c8bf210"),
"user_id": ObjectId("609b2e5d6c73724c5c8bf20e"),
"order_date": ISODate("2023-05-14T10:00:00Z"),
"items": [
{
"product_id": ObjectId("609b2e5d6c73724c5c8bf20f"),
"quantity": 2
}
],
"total_amount": 1999.98
})
4. Query Documents
db.orders.aggregate([
{ $unwind: "$items" },
{ $lookup: {
from: "products",
localField: "items.product_id",
foreignField: "_id",
as: "product_details"
}
},
{ $unwind: "$product_details" },
{ $project: {
_id: 1,
order_date: 1,
"items.product_id": 1,
"items.quantity": 1,
"product_details.name": 1,
"product_details.price": 1
}
}
])
5. Update Documents
db.users.updateOne(
{ username: "user123" },
{ $set: { email: "[email protected]" } }
)
db.products.updateOne(
{ name: "Laptop" },
{ $set: { stock_quantity: 90 } }
)
6. Delete Documents
a. Delete a User
b. Delete an Order
1. Projection Stage: This stage selects only the fields genres, imdb, and title from the
documents, excluding the _id field.
2. Unwind Stage: This stage deconstructs the genres array from each document and
outputs a document for each genre in the array.
3. Group Stage: This stage groups the documents by genre and calculates the average
IMDb rating for each genre.
4. Sort Stage: This stage sorts the genres by the average IMDb rating in descending order.
To run this aggregation pipeline in the MongoDB shell, follow these steps:
1. Connect to MongoDB:
mongo
use yourDatabaseName
db.movies.aggregate([
// First Stage: Projection
{ $project: { _id: 0, genres: 1, imdb: 1, title: 1 } },
This indicates:
Example Output
If your movies collection contains documents similar to the example you provided, the output
might look something like:
Ex 11b
Creating an Index
To create an index on a collection, you use the createIndex method. The createIndex method
can take an optional callback function to handle any errors or get the result of the index creation.
Example
Here’s how you can create an index on the name field in descending order (-1):
Output
The output of the createIndex method will typically include details about the created index. For
example:
{
"createdCollectionAutomatically": false,
"numIndexesBefore": 1,
"numIndexesAfter": 2,
"ok": 1
}
numIndexesBefore indicates the number of indexes before the new one was created.
numIndexesAfter indicates the number of indexes after the new one was created.
ok indicates whether the operation was successful.
To view the indexes on a collection, you use the getIndexes method. This will return an array
of index documents describing the indexes.
Example
javascript
Copy code
db.collection.getIndexes()
Example Output
[
{
"v": 2,
"key": { "_id": 1 },
"name": "_id_"
},
{
"v": 2,
"key": { "name": -1 },
"name": "name_-1"
}
]
The first index is on the _id field, which is automatically created by MongoDB.
The second index is on the name field in descending order, with the name name_-1.
Explanation
1. { "_id": 1 }: This is the default index on the _id field, which MongoDB creates
automatically.
2. { "name": -1 }: This is the index you created on the name field in descending order.