Core Operations

CRUD Operations

Create, read, update, and delete documents in MongoDB collections.

Insert Documents

  • insertOne() — insert a single document
  • insertMany() — insert multiple documents
  • MongoDB auto-generates _id if not provided

Find Documents

  • findOne() — return first matching document
  • find() — return cursor of all matching documents
  • Chain .sort(), .limit(), .skip() for pagination

Update Documents

  • updateOne() — update first matching document
  • updateMany() — update all matching documents
  • replaceOne() — replace entire document
  • Use update operators: $set, $inc, $push, $pull, etc.

Delete Documents

  • deleteOne() — delete first matching document
  • deleteMany() — delete all matching documents

Example

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

async function demo() {
  const client = new MongoClient('mongodb://localhost:27017');
  await client.connect();
  const db = client.db('myapp');
  const users = db.collection('users');

  // INSERT
  await users.insertOne({
    name: 'Alice',
    email: 'alice@example.com',
    age: 30,
    role: 'admin',
    createdAt: new Date()
  });

  await users.insertMany([
    { name: 'Bob', email: 'bob@example.com', age: 25, role: 'user' },
    { name: 'Carol', email: 'carol@example.com', age: 35, role: 'user' },
  ]);

  // FIND
  const alice = await users.findOne({ email: 'alice@example.com' });
  const allUsers = await users.find({}).toArray();
  const admins = await users.find({ role: 'admin' }).toArray();

  // With projection (select fields)
  const names = await users.find({}, { projection: { name: 1, email: 1, _id: 0 } }).toArray();

  // Sort and limit
  const youngest = await users.find({}).sort({ age: 1 }).limit(5).toArray();

  // UPDATE
  await users.updateOne(
    { email: 'alice@example.com' },
    { $set: { role: 'superadmin', updatedAt: new Date() } }
  );

  await users.updateMany(
    { role: 'user' },
    { $inc: { age: 1 } }  // increment age by 1
  );

  // $push to add to array
  await users.updateOne(
    { email: 'alice@example.com' },
    { $push: { tags: 'verified' } }
  );

  // DELETE
  await users.deleteOne({ email: 'bob@example.com' });
  await users.deleteMany({ role: 'inactive' });

  await client.close();
}

Want to run this code interactively?

Try in Compiler