Assignment s Of Day 5
MongoDB CRUD Operations – Part 1 (Insert)
Assignment 1: Insert a Single Document into the Collection
Problem: Insert a document into the students collection with the following fields:
- name: "Alice"
- age: 22
- email: "alice@example.com"
- isActive: true
Solution:
use myDatabase; // Switch to the database
db.students.insertOne({
name: "Alice",
age: 22,
email: "alice@example.com",
isActive: true
});
Explanation:
- We use the insertOne() method to insert a single document into the students collection. MongoDB will automatically add the _id field.
Assignment 2: Insert Multiple Documents into the Collection
Problem: Insert multiple documents into the courses collection with the following data:
1. { name: "Mathematics", duration: 6, level: "Intermediate" }
2. { name: "Physics", duration: 3, level: "Beginner" }
3. { name: "Chemistry", duration: 4, level: "Intermediate" }
Solution:
use myDatabase;
db.courses.insertMany([
{ name: "Mathematics", duration: 6, level: "Intermediate" },
{ name: "Physics", duration: 3, level: "Beginner" },
{ name: "Chemistry", duration: 4, level: "Intermediate" }
]);
Explanation:
- We use insertMany() to insert multiple documents in a single operation. Each document will be inserted in the courses collection.
Assignment 3: Insert a Document with a Custom _id Field
Problem: Insert a document into the employees collection with the following data and a custom _id:
- _id: 101
- name: "John Doe"
- position: "Software Developer"
- salary: 70000
Solution:
use myDatabase;
db.employees.insertOne({
_id: 101,
name: "John Doe",
position: "Software Developer",
salary: 70000
});
Explanation:
- We manually assign a value to the _id field. MongoDB will use this custom _id instead of auto-generating it.
Assignment 4: Insert Invalid Document with Duplicate _id
Problem: Try inserting two documents into the products collection, both with the same _id of 2001. Observe the error.
Solution:
use myDatabase;
db.products.insertOne({
_id: 2001,
name: "Laptop",
price: 1200,
category: "Electronics"
});
db.products.insertOne({
_id: 2001,
name: "Smartphone",
price: 800,
category: "Electronics"
});
Explanation:
- The second insertion will result in an error because the _id is a unique identifier. MongoDB will reject the second document with the same _id.
Assignment 5: Insert Document and Verify the Insertion
Problem: Insert a document into the users collection and then use the find() method to verify the insertion.
Solution:
use myDatabase;
db.users.insertOne({
name: "Eve",
age: 28,
email: "eve@example.com",
isActive: true
});
// Verify insertion
db.users.find().pretty();
Explanation:
- After inserting the document, we query the users collection with the find() method and use the pretty() function for a readable output.
Assignment 6: Insert Document Without _id and Verify Auto-Generation
Problem: Insert a document into the products collection without providing the _id field. MongoDB should auto-generate it.
Solution:
use myDatabase;
db.products.insertOne({
name: "Tablet",
price: 300,
category: "Electronics"
});
// Verify insertion
db.products.find().pretty();
Explanation:
- Since we don't provide an _id, MongoDB automatically generates a unique _id for the document.
Assignment 7: Insert Document with Date Field
Problem: Insert a document into the orders collection that contains the following fields:
- order_id: 501
- customer_name: "Sam"
- order_date: Current date
- status: "Shipped"
Solution:
use myDatabase;
db.orders.insertOne({
order_id: 501,
customer_name: "Sam",
order_date: new Date(), // Current date
status: "Shipped"
});
Explanation:
- We use the new Date() function to insert the current date and time into the order_date field.
Assignment 8: Insert Multiple Documents with Different Data Types
Problem: Insert multiple documents into the students collection with various data types such as String, Integer, Boolean, and Date.
Solution:
use myDatabase;
db.students.insertMany([
{ name: "Alice", age: 22, isActive: true, enrollmentDate: new Date("2022-01-15") },
{ name: "Bob", age: 20, isActive: false, enrollmentDate: new Date("2023-03-10") },
{ name: "Charlie", age: 25, isActive: true, enrollmentDate: new Date("2021-11-25") }
]);
Explanation:
- This demonstrates how to use various data types in a document: String for name, Integer for age, Boolean for isActive, and Date for enrollmentDate.
Assignment 9: Insert a Document with an Embedded Array
Problem: Insert a document into the employees collection that includes an embedded array of skills.
Solution:
use myDatabase;
db.employees.insertOne({
name: "Jake",
position: "Full-stack Developer",
skills: ["JavaScript", "Node.js", "MongoDB", "React"]
});
Explanation:
- The skills field contains an array of strings. MongoDB supports embedded arrays in documents.
Assignment 10: Insert Document Using Node.js
Problem: Using Node.js, insert a document into the books collection with the following fields:
- title: "MongoDB for Beginners"
- author: "John Smith"
- price: 20
Solution:
1. Install MongoDB Node.js Driver:
npm install mongodb
2. Insert Document using Node.js:
const { MongoClient } = require("mongodb");
async function main() {
const uri = "mongodb://localhost:27017"; // MongoDB server URL
const client = new MongoClient(uri);
try {
await client.connect();
const database = client.db("myDatabase");
const booksCollection = database.collection("books");
const book = {
title: "MongoDB for Beginners",
author: "John Smith",
price: 20
};
// Insert a single document
const result = await booksCollection.insertOne(book);
console.log(`Book inserted with _id: ${result.insertedId}`);
} finally {
await client.close();
}
}
main().catch(console.error);
Explanation:
- The code connects to a MongoDB server running on localhost:27017 and inserts a document into the books collection.
Conclusion
These assignments cover a variety of scenarios for inserting documents into MongoDB collections. Students will have hands-on practice with basic and advanced insert operations, including using custom _id values, embedded arrays, and using MongoDB with Node.js.
