Preview:
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);
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter