DATABASE ENIGINEERING
LAB-8
Name- Abhinav Giri
Roll No.- R2142221345
SAP ID- 500110031
Course- B.Tech CSE(FSAI)
Semester- 6
Batch- 3
SCHOOL OF COMPUTER SCIENCE
UPES, DEHRADUN
Lab Exercise 9 - Updating a Document in
MongoDB Using Multiple Methods in mongosh
Console
1. Launch the mongosh Console
Set Up a Database and Collection
Switch to a database:
use updateLabDB
Insert sample data into a collection:
db.products.insertMany([ { name: "Laptop", price: 800, stock: 10, category: "Electronics" },
{ name: "Mouse", price: 20, stock: 50, category: "Accessories" }, { name: "Keyboard", price: 45,
stock: 25, category: "Accessories" }, { name: "Monitor", price: 150, stock: 15, category:
"Electronics" }, { name: "Speaker", price: 70, stock: 30, category: "Electronics" } ])
Update a Single Document
Use updateOne with $set Query: Update the price of the
"Laptop" to $850.
db.products.updateOne( { name: "Laptop" }, { $set: { price: 850 } } )
Use findOneAndUpdate Query:
Update the stock of "Mouse" to 45 and return the original document.
db.products.findOneAndUpdate( { name: "Mouse" }, { $set: { stock: 45 } }, { returnDocument:
"before" } )
Update Multiple Documents
Use updateMany with $inc Query:
Increase the stock of all "Electronics" products by 5.
db.products.updateMany( { category: "Electronics" }, { $inc: { stock: 5 } } )
Use Other Update Operators
Use $rename Query: Rename the field category to productCategory for all documents.
db.products.updateMany( {}, { $rename: { category: "productCategory" }
Use $unset Query:
Remove the stock field from the "Speaker" document.
db.products.updateOne( { name: "Speaker" }, { $unset: { stock: "" } } )
Verify the Updates
View all documents to verify changes:
db.products.find()