a) Create a collection called "Users" in MongoDB that contains fields such as Name, doj, salary and department. Demonstrate the CRUD operations by performing on it.

PHOTO EMBED

Mon Apr 07 2025 23:52:48 GMT+0000 (Coordinated Universal Time)

Saved by @p9876543

const { MongoClient } = require('mongodb');

const url = 'mongodb://127.0.0.1:27017';
const dbName = 'company';
const client = new MongoClient(url);

async function run() {
  try {
    await client.connect();
    console.log("Connected to MongoDB");

    const db = client.db(dbName);
    const users = db.collection('Users');

    await users.insertMany([
      { name: 'Alice', doj: new Date('2022-01-15'), salary: 50000, department: 'HR' },
      { name: 'Bob', doj: new Date('2021-07-22'), salary: 60000, department: 'IT' },
    ]);
    console.log("Users inserted.");

    const allUsers = await users.find({}).toArray();
    console.log("All Users:", allUsers);

    await users.updateOne({ name: 'Alice' }, { $set: { salary: 55000 } });
    console.log("Updated Alice's salary.");

    await users.deleteOne({ name: 'Bob' });
    console.log("Bob removed from Users.");

  } finally {
    await client.close();
    console.log("MongoDB connection closed.");
  }
}

run().catch(console.dir);
content_copyCOPY