diff --git a/Week-05/Day_05/README.md b/Week-05/Day_05/README.md new file mode 100644 index 0000000..2625dee --- /dev/null +++ b/Week-05/Day_05/README.md @@ -0,0 +1,105 @@ +# MongoDB with Node.js + +## Introduction + +In this task, we connect MongoDB with Node.js to perform database operations using JavaScript. +This allows building dynamic backend applications. + +--- + +## Install Required Package + +```bash +npm init -y +npm install mongodb +``` + +--- + +## Connect to MongoDB + +```js +const { MongoClient } = require('mongodb'); + +const url = 'mongodb://127.0.0.1:27017'; +const client = new MongoClient(url); + +async function connectDB() { + try { + await client.connect(); + console.log("Connected to MongoDB"); + } catch (error) { + console.error(error); + } +} + +connectDB(); +``` + +--- + +## Access Database and Collection + +```js +const db = client.db('studentDB'); +const collection = db.collection('students'); +``` + +--- + +## Insert Data + +```js +await collection.insertOne({ + name: "Rahul", + course: "MCA" +}); +``` + +--- + +## Fetch Data + +```js +const data = await collection.find().toArray(); +console.log(data); +``` + +--- + +## Update Data + +```js +await collection.updateOne( + { name: "Rahul" }, + { $set: { course: "MBA" } } +); +``` + +--- + +## Delete Data + +```js +await collection.deleteOne({ name: "Rahul" }); +``` + +--- + +## Project Structure + +``` +project/ +│ +├── node_modules/ +├── app.js +├── package.json +``` + +--- + +## Run the Application + +```bash +node app.js +``` \ No newline at end of file