0% found this document useful (0 votes)
21 views

Ex 9,10,11

Uploaded by

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

Ex 9,10,11

Uploaded by

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

Ex 9

1. Connecting to MongoDB
mongo

This connects you to the local MongoDB instance.

2. Show Databases
show dbs

Example output:

admin 0.000GB
local 0.000GB
test 0.000GB

3. Create or Switch to a Database


use myDatabase

This switches to the myDatabase database (it will be created if it doesn’t exist).

4. Show Collections in a Database


show collections

Example output:

users
products
orders

5. Create or Switch to a Collection

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

Insert One Document:


db.users.insertOne({ name: "Alice", age: 25, email: "[email protected]" })

Insert Multiple Documents:

db.products.insertMany([
{ name: "Laptop", price: 1200 },
{ name: "Smartphone", price: 800 }
])

7. Query Documents

Find One Document:

db.users.findOne({ name: "Alice" })

Example output:

json
Copy code
{ "_id": ObjectId("60d5c72f8f1b2b56d84a1e9f"), "name": "Alice", "age": 25,
"email": "[email protected]" }

Find Multiple Documents:

db.products.find({ price: { $gt: 500 } })

Example output:

{ "_id": ObjectId("60d5c72f8f1b2b56d84a1e9g"), "name": "Laptop", "price":


1200 }
{ "_id": ObjectId("60d5c72f8f1b2b56d84a1e9h"), "name": "Smartphone", "price":
800 }

8. Update Documents

Update One Document:

db.users.updateOne(
{ name: "Alice" },
{ $set: { age: 26 } }
)

Update Multiple Documents:

db.products.updateMany(
{ price: { $lt: 1000 } },
{ $set: { onSale: true } }
)
9. Delete Documents

Delete One Document:

db.users.deleteOne({ name: "Alice" })

Delete Multiple Documents:

db.products.deleteMany({ price: { $lt: 500 } })

10. Aggregate Data

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.

11. Drop a Collection


db.users.drop()

12. Drop a Database


db.dropDatabase()

This command drops the current database (be cautious with this as it deletes all data).

Ex 10

1. Connect to MongoDB
mongo

2. Use the Database

If you have not created a database yet, switch to or create one:

use myDatabase

3. Create Collections and Insert Documents


a. Users Collection

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

a. Find a User by Username

db.users.findOne({ username: "user123" })

b. Find a Product by Name

db.products.findOne({ name: "Laptop" })

c. Find Orders by User


db.orders.find({ user_id: ObjectId("609b2e5d6c73724c5c8bf20e") })

d. Find Products in Orders

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

a. Update User’s Email

db.users.updateOne(
{ username: "user123" },
{ $set: { email: "[email protected]" } }
)

b. Update Product Stock Quantity

db.products.updateOne(
{ name: "Laptop" },
{ $set: { stock_quantity: 90 } }
)

6. Delete Documents

a. Delete a User

db.users.deleteOne({ username: "user123" })

b. Delete an Order

db.orders.deleteOne({ _id: ObjectId("609b2e5d6c73724c5c8bf210") })


ex 11 a

Aggregation Pipeline Stages

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.

MongoDB Shell Command

To run this aggregation pipeline in the MongoDB shell, follow these steps:

1. Connect to MongoDB:

mongo

2. Switch to your database (if necessary):

use yourDatabaseName

3. Run the Aggregation Pipeline:

db.movies.aggregate([
// First Stage: Projection
{ $project: { _id: 0, genres: 1, imdb: 1, title: 1 } },

// Second Stage: Unwind genres


{ $unwind: "$genres" },

// Third Stage: Group by genre and calculate average rating


{ $group: {
_id: "$genres",
averageGenreRating: { $avg: "$imdb.rating" }
}
},

// Fourth Stage: Sort by average rating in descending order


{ $sort: { averageGenreRating: -1 } }
])

Explanation of the Output

Given the sample output:


{
"_id": "Sci-Fi",
"averageGenreRating": 8.2
}

This indicates:

 The genre is Sci-Fi.


 The average IMDb rating for movies in the Sci-Fi genre is 8.2.

Example Output

If your movies collection contains documents similar to the example you provided, the output
might look something like:

{ "_id": "Sci-Fi", "averageGenreRating": 8.2 }


{ "_id": "Thriller", "averageGenreRating": 7.5 }

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):

db.collection.createIndex({ name: -1 }, function(err, result) {


if (err) {
print("Error creating index:", err);
} else {
print("Index created:", result);
}
});

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.

Viewing Existing Indexes

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

Here’s an example of what the output might look like:

[
{
"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.

You might also like