Cycle 04
Lab Cycle 4 — NoSQL Database Operations with MongoDB
MongoDB Document Insertion, Selection, and Filtering
Problem Statement
Write MongoDB shell (mongosh) commands to: 1. Create a collection 'suppliers' and insert single document using insertOne() and multiple documents using insertMany(). 2. Select and display all documents in collection. 3. Find count of all suppliers. 4. Find all records that have city = 'Delhi'. 5. Retrieve all documents that have color equal to 'red' or 'green' using $in / $or. 6. Retrieve all documents where part_name is 'P1' or price is less than 200.
// 1. Insert single document using insertOne()
db.suppliers.insertOne({
SID: 1001,
sname: "Vandana",
branch: "global",
city: "Delhi",
phone: "9811001122"
});
// Insert multiple documents using insertMany()
db.suppliers.insertMany([
{ SID: 1002, sname: "Rajesh", branch: "local", city: "Delhi", phone: "9822002233" },
{ SID: 1003, sname: "Mike", branch: "main", city: "Mumbai", phone: "9833003344" },
{ SID: 1004, sname: "Geeta", branch: "global", city: "Delhi", phone: "9844004455" },
{ SID: 1005, sname: "Alok", branch: "local", city: "Bangalore", phone: "9855005566" }
]);
// Insert parts documents for querying
db.parts.insertMany([
{ PID: 201, part_name: "P1", color: "yellow", price: 180 },
{ PID: 202, part_name: "NUT", color: "silver", price: 250 },
{ PID: 203, part_name: "WASHER", color: "red", price: 400 },
{ PID: 204, part_name: "BEARING", color: "green", price: 500 },
{ PID: 205, part_name: "PISTON", color: "silver", price: 5500 }
]);
// 2. Select and display all documents
db.suppliers.find();
// 3. Find count of all suppliers
db.suppliers.countDocuments({});
// 4. Find all records where city = 'Delhi'
db.suppliers.find({ city: "Delhi" });
// 5. Retrieve all documents having color 'red' or 'green'
db.parts.find({ color: { $in: ["red", "green"] } });
// 6. Retrieve all documents where part_name is 'P1' or price < 200
db.parts.find({
$or: [
{ part_name: "P1" },
{ price: { $lt: 200 } }
]
});
Question 1 of 2