You are on page 1of 4

PRACTICAL-10

NAME: - Nidhi Bangar


ROLL NO.: - 22bcm044
COURSE CODE & NAME: - 2CS201 FSWD
AIM: -Demonstrate Node.js using MongoDB to
perform Create, Read, Update, and Delete
operations.
Create.js
const { MongoClient } = require('mongodb');
async function main() {
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);
try {
await client.connect();
const database = client.db('mydatabase');
const collection = database.collection('mycollection');
// const result = await collection.insertOne({ name: 'Nidhi', age: 20, city:
'Bhilwara' });
// const result = await collection.insertOne({ name: 'Maahi', age: 20, city:
'Bhilwara' });
// const result = await collection.insertOne({ name: 'Manoj', age: 36, city:
'Mumbai' });
const result = await collection.insertOne({ name: 'Shraddha', age: 15, city:
'Delhi' });
console.log(`Document inserted with id: ${result.insertedId}`);
} finally {
await client.close();
}
}
main().catch(console.error);
Read.js
const { MongoClient } = require('mongodb');
async function main() {
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);
try {
await client.connect();
const database = client.db('mydatabase');
const collection = database.collection('mycollection');
const documents = await collection.find({}).toArray();
console.log('Documents:');
console.log(documents);
} finally {
await client.close();
}
}

main().catch(console.error);
Update.js
const { MongoClient } = require('mongodb');
async function main() {
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);
try {
await client.connect();
const database = client.db('mydatabase');
const collection = database.collection('mycollection');
const result = await collection.updateMany({ name: 'Nidhi' }, { $set: {
age:19 } });
console.log(`${result.modifiedCount} documents updated.`);
} finally {
await client.close();
}
}
main().catch(console.error);

Delete.js
const { MongoClient } = require('mongodb');
async function main() {
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);
try {
await client.connect();
const database = client.db('mydatabase');
const collection = database.collection('mycollection');
const result = await collection.deleteMany({ name: 'Shraddha' });
console.log(`${result.deletedCount} documents deleted.`);
} finally {
await client.close();
}
}

main().catch(console.error);

You might also like