Files
Web-Development/Week-05/Day_05/README.md
2026-03-25 11:35:13 +05:30

105 lines
1.3 KiB
Markdown

# 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
```