Assignments Of Day 24: MongoDB Administration (Basic)
Assignment: Create a database named library. Create two collections: books and authors. Insert at least three documents into each collection. Query and update documents in both collections. Use the db.stats() and db.<collection_name>.stats() commands to monitor your database and collection statistics.
Solution: MongoDB Administration Assignment
1. Create a database named library
To create a database named library, use the use command. This command switches to the database and automatically creates it when you insert data into it.
js
CopyEdit
use library
2. Create two collections: books and authors
In MongoDB, collections are created automatically when documents are inserted. However, you can explicitly create them as well.
js
CopyEdit
// Switch to 'library' database
use library
// Create collections by inserting documents into them
db.books.insertOne({ title: "The Great Gatsby", authorId: 1, year: 1925 })
db.authors.insertOne({ name: "F. Scott Fitzgerald", dob: "1896-09-24" })
This will create the books and authors collections if they don't already exist.
3. Insert at least three documents into each collection
Next, insert at least three documents into both the books and authors collections.
Inserting Documents into books Collection:
js
CopyEdit
db.books.insertMany([
{ title: "1984", authorId: 2, year: 1949 },
{ title: "Moby-Dick", authorId: 3, year: 1851 },
{ title: "To Kill a Mockingbird", authorId: 4, year: 1960 }
])
Inserting Documents into authors Collection:
js
CopyEdit
db.authors.insertMany([
{ name: "George Orwell", dob: "1903-06-25" },
{ name: "Herman Melville", dob: "1819-08-01" },
{ name: "Harper Lee", dob: "1926-04-28" }
])
Now, the books and authors collections contain three documents each.
4. Query and update documents in both collections
Querying Documents:
- Query all books:
js
CopyEdit
db.books.find()
- Query a specific book (e.g., with title "1984"):
js
CopyEdit
db.books.find({ title: "1984" })
- Query all authors:
js
CopyEdit
db.authors.find()
- Query a specific author (e.g., with name "George Orwell"):
js
CopyEdit
db.authors.find({ name: "George Orwell" })
Updating Documents:
- Update a book's year (e.g., change year of "1984" to 1950):
js
CopyEdit
db.books.updateOne(
{ title: "1984" },
{ $set: { year: 1950 } }
)
- Update an author's date of birth (e.g., change date of birth of "Harper Lee"):
js
CopyEdit
db.authors.updateOne(
{ name: "Harper Lee" },
{ $set: { dob: "1926-05-01" } }
)
5. Use the db.stats() and db.<collection_name>.stats() commands to monitor database and collection statistics
Get Database Stats:
js
CopyEdit
db.stats()
This command will return statistics for the entire library database, including storage size, number of collections, and more.
Get Collection Stats for books Collection:
js
CopyEdit
db.books.stats()
This will return statistics specific to the books collection, such as the number of documents, size of the collection, and more.
Get Collection Stats for authors Collection:
js
CopyEdit
db.authors.stats()
This will return statistics specific to the authors collection.
Summary of Commands Used
1. Database Creation:
js
CopyEdit
use library
2. Create Collections:
js
CopyEdit
db.books.insertOne({ title: "The Great Gatsby", authorId: 1, year: 1925 })
db.authors.insertOne({ name: "F. Scott Fitzgerald", dob: "1896-09-24" })
3. Insert Documents:
js
CopyEdit
db.books.insertMany([{ title: "1984", authorId: 2, year: 1949 }, { title: "Moby-Dick", authorId: 3, year: 1851 }, { title: "To Kill a Mockingbird", authorId: 4, year: 1960 }])
db.authors.insertMany([{ name: "George Orwell", dob: "1903-06-25" }, { name: "Herman Melville", dob: "1819-08-01" }, { name: "Harper Lee", dob: "1926-04-28" }])
4. Query Documents:
js
CopyEdit
db.books.find()
db.books.find({ title: "1984" })
db.authors.find()
db.authors.find({ name: "George Orwell" })
5. Update Documents:
js
CopyEdit
db.books.updateOne({ title: "1984" }, { $set: { year: 1950 } })
db.authors.updateOne({ name: "Harper Lee" }, { $set: { dob: "1926-05-01" } })
6. Monitor Stats:
js
CopyEdit
db.stats()
db.books.stats()
db.authors.stats()
Conclusion
In this assignment, you learned how to perform basic MongoDB administrative tasks such as creating a database, inserting documents into collections, querying and updating documents, and monitoring the database and collection statistics. These are fundamental skills for managing MongoDB databases efficiently.
4o mini
You said:
WRITE 10 ASSIGNMENTS FROM ABOVE CONCEPT WITH STEP BY STEP SOLUTIONS with proper explanation in details
ChatGPT said:
ChatGPT
Here are 10 MongoDB assignments based on the concepts of database and collection management, queries, updates, and monitoring, along with detailed step-by-step solutions.
Assignment 1: Create a Database and Collections
Task:
1. Create a database named store.
2. Create two collections: products and customers.
3. Insert at least 3 documents in each collection.
Solution:
1. Create the store database:
js
CopyEdit
use store
This switches to the store database. If it doesn’t exist, MongoDB will create it when data is inserted.
2. Create products collection:
js
CopyEdit
db.products.insertMany([
{ name: "Laptop", category: "Electronics", price: 1200 },
{ name: "Phone", category: "Electronics", price: 800 },
{ name: "Table", category: "Furniture", price: 200 }
])
3. Create customers collection:
js
CopyEdit
db.customers.insertMany([
{ name: "John Doe", age: 30, email: "john@example.com" },
{ name: "Jane Smith", age: 25, email: "jane@example.com" },
{ name: "Sam Brown", age: 22, email: "sam@example.com" }
])
Now, you have created the database store and added 3 documents in both the products and customers collections.
Assignment 2: Query Data from Collections
Task:
1. Retrieve all documents from the products collection.
2. Retrieve documents from the customers collection where the customer’s age is greater than 25.
Solution:
1. Query all products:
js
CopyEdit
db.products.find()
This returns all documents in the products collection.
2. Query customers older than 25 years:
js
CopyEdit
db.customers.find({ age: { $gt: 25 } })
This will return all customers whose age is greater than 25.
Assignment 3: Update Documents in Collections
Task:
1. Update the price of "Laptop" in the products collection to 1300.
2. Update the age of "Sam Brown" to 23 in the customers collection.
Solution:
1. Update product price:
js
CopyEdit
db.products.updateOne(
{ name: "Laptop" },
{ $set: { price: 1300 } }
)
This command updates the price field of the product "Laptop" to 1300.
2. Update customer age:
js
CopyEdit
db.customers.updateOne(
{ name: "Sam Brown" },
{ $set: { age: 23 } }
)
This command updates Sam Brown’s age to 23.
Assignment 4: Delete Documents from Collections
Task:
1. Delete a product named "Table" from the products collection.
2. Delete a customer named "John Doe" from the customers collection.
Solution:
1. Delete product "Table":
js
CopyEdit
db.products.deleteOne({ name: "Table" })
This removes the document with the name "Table" from the products collection.
2. Delete customer "John Doe":
js
CopyEdit
db.customers.deleteOne({ name: "John Doe" })
This removes the document with the name "John Doe" from the customers collection.
Assignment 5: Use db.stats() and db.<collection_name>.stats()
Task:
1. Get the database statistics for the store database.
2. Get the statistics for the products collection.
Solution:
1. Get database statistics:
js
CopyEdit
db.stats()
This command will provide various statistics about the store database, such as the size, storage size, number of collections, and more.
2. Get collection statistics for products:
js
CopyEdit
db.products.stats()
This will give you statistics specific to the products collection, such as the number of documents, size, and storage usage.
Assignment 6: Perform Aggregation Operations
Task:
1. Use the aggregate() method to find the average price of products in the products collection.
2. Use the $group operator to group customers by their age in the customers collection and count how many customers belong to each age group.
Solution:
1. Find average price of products:
js
CopyEdit
db.products.aggregate([
{ $group: { _id: null, avgPrice: { $avg: "$price" } } }
])
This calculates the average price of all products.
2. Group customers by age and count them:
js
CopyEdit
db.customers.aggregate([
{ $group: { _id: "$age", count: { $sum: 1 } } }
])
This groups customers by their age and counts how many customers belong to each age group.
Assignment 7: Use Indexing for Optimization
Task:
1. Create an index on the name field in the products collection to speed up searches.
2. Create a compound index on name and category in the products collection.
Solution:
1. Create index on name:
js
CopyEdit
db.products.createIndex({ name: 1 })
This creates an ascending index on the name field of the products collection.
2. Create compound index on name and category:
js
CopyEdit
db.products.createIndex({ name: 1, category: 1 })
This creates a compound index on both name and category to optimize queries that filter by both fields.
Assignment 8: Use the findOne() Method
Task:
1. Use the findOne() method to retrieve a single product with the name "Phone" from the products collection.
2. Use the findOne() method to retrieve a single customer named "Sam Brown" from the customers collection.
Solution:
1. Find one product by name:
js
CopyEdit
db.products.findOne({ name: "Phone" })
This retrieves the first document with the name "Phone" from the products collection.
2. Find one customer by name:
js
CopyEdit
db.customers.findOne({ name: "Sam Brown" })
This retrieves the first document with the name "Sam Brown" from the customers collection.
Assignment 9: Use Projection to Limit Fields in Queries
Task:
1. Retrieve the names and prices of all products from the products collection, excluding other fields.
2. Retrieve the names and emails of all customers from the customers collection, excluding other fields.
Solution:
1. Retrieve names and prices of products:
js
CopyEdit
db.products.find({}, { name: 1, price: 1 })
This limits the output to only the name and price fields of all products.
2. Retrieve names and emails of customers:
js
CopyEdit
db.customers.find({}, { name: 1, email: 1 })
This limits the output to only the name and email fields of all customers.
Assignment 10: Create a Reference Between Two Collections
Task:
1. Add a reference to the products collection by adding a productId field in the customers collection.
2. Write a query to join the customers collection with the products collection based on the productId field.
Solution:
1. Add reference to products collection in customers:
js
CopyEdit
db.customers.updateOne(
{ name: "Jane Smith" },
{ $set: { productId: db.products.findOne({ name: "Laptop" })._id } }
)
This adds a reference to the products collection in the customers collection by storing the productId of "Laptop".
2. Join customers and products collections:
MongoDB doesn't directly support joins like SQL, but you can achieve this using aggregation:
js
CopyEdit
db.customers.aggregate([
{
$lookup: {
from: "products",
localField: "productId",
foreignField: "_id",
as: "product_details"
}
}
])
This performs a left join between customers and products based on the productId reference and returns the product details along with customer information.
Conclusion
These assignments cover a wide range of MongoDB operations, from creating databases and collections, querying and updating documents, managing indexes, and performing aggregation. By completing these tasks, students will become proficient in basic MongoDB administration and management.
