Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 37 ยท CRUD and Queries

Deleting Documents and Bulk Writes in Mongoose

Remove data with Mongoose deleteOne, deleteMany and findOneAndDelete, add soft deletes and TTL expiry, and batch mixed operations with bulkWrite.

Deleting looks like the simplest CRUD operation, and in Mongoose it is: a few methods, a filter and you are done. The real questions are design questions. Should the data really disappear? Should it disappear later, on its own? And when you have many writes to do, how do you send them efficiently? This lesson answers all of these.

Delete methods

JavaScript
await Product.deleteOne({ sku: 'KB-100' });             // first match
await Product.deleteMany({ inStock: false });           // every match
const gone = await Product.findOneAndDelete({ sku: 'MS-200' }); // returns the deleted doc
const gone2 = await Product.findByIdAndDelete(id);

deleteOne and deleteMany return { acknowledged: true, deletedCount: n }. A deletedCount of 0 means the filter matched nothing; check it when you need to answer a client with "not found". findOneAndDelete returns the removed document (or null), useful when you want to log or return it.

Be extremely careful with deleteMany({}): an empty filter deletes everything. A bug that passes undefined into a filter object can turn a narrow delete into a wide one. Guard filters built from user input, and set sanitizeFilter or validate before calling.

You can also delete a loaded document:

JavaScript
const product = await Product.findById(id);
await product.deleteOne();

Note this runs document middleware (pre('deleteOne', { document: true })), whereas Model.deleteOne() runs query middleware.

Deleting subdocuments

For embedded array items, either load the parent and use pull or use an update operator:

JavaScript
await Post.updateOne({ _id: postId }, { $pull: { comments: { _id: commentId } } });

That is an update, not a delete; the parent stays.

Soft delete

In many applications records must not vanish: orders for accounting, users for audit, content for undo. A soft delete marks the document instead of removing it:

JavaScript
const schema = new mongoose.Schema({
  title: String,
  deletedAt: { type: Date, default: null },
});

schema.pre(/^find/, function () {
  if (!this.getOptions().withDeleted) {
    this.where({ deletedAt: null });
  }
});

await Post.updateOne({ _id: id }, { $set: { deletedAt: new Date() } });      // "delete"
await Post.updateOne({ _id: id }, { $set: { deletedAt: null } });            // restore
await Post.find().setOptions({ withDeleted: true });                          // see all

The query middleware hides deleted documents from every find* call. Remember countDocuments and updateOne have their own hooks; list them if you want the filter everywhere. A unique index on a soft-deleted collection also needs thought, because a deleted record still occupies its unique value. A partial index limited to deletedAt: null solves it.

TTL: let MongoDB expire documents

Sessions, one-time codes and temporary logs should disappear on their own. A TTL index on a date field makes MongoDB delete the documents after a time:

JavaScript
const sessionSchema = new mongoose.Schema({
  userId: mongoose.Schema.Types.ObjectId,
  createdAt: { type: Date, default: Date.now, expires: '1h' },
});

expires is a Mongoose shorthand that creates the TTL index. MongoDB's background task checks about once a minute, so removal is not instantaneous.

Node.js Soft delete and TTL (stand-in, not Mongoose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Bulk operations

Sending a hundred separate updates costs a hundred round trips. Model.bulkWrite() sends many mixed operations in one command:

JavaScript
const result = await Product.bulkWrite([
  { insertOne: { document: { sku: 'N-1', name: 'New item', price: 5 } } },
  { updateOne: { filter: { sku: 'KB-100' }, update: { $inc: { price: 1 } } } },
  { updateMany: { filter: { inStock: false }, update: { $set: { tags: [] } } } },
  { deleteOne: { filter: { sku: 'OLD-1' } } },
  { replaceOne: { filter: { sku: 'X' }, replacement: { sku: 'X', name: 'X', price: 1 } } },
  {
    updateOne: {
      filter: { sku: 'UP-1' },
      update: { $set: { name: 'Upserted', price: 3 } },
      upsert: true,
    },
  },
]);

console.log(result.insertedCount, result.modifiedCount, result.deletedCount, result.upsertedCount);

Facts to remember:

  • Operations run in order by default; the first error stops the batch. Pass { ordered: false } to continue past errors and let MongoDB run them in parallel.
  • Mongoose casts each operation's filter and update to your schema and applies timestamps. It does not run save middleware. Documents in insertOne operations are validated, but update operations are not unless you ask for it, so check your installed version's documentation if validation matters for a bulk update.
  • Use it for imports and syncs; for plain bulk inserts insertMany is simpler.
  • There is a limit on batch size (the driver splits large lists automatically).
Node.js Mixed batch with ordered and unordered modes (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Which delete should you choose?

Situation Choice
Remove data permanently, you have the filter deleteOne / deleteMany
Remove and use the removed document findOneAndDelete
Must be recoverable or auditable soft delete with deletedAt
Temporary data (sessions, codes) TTL index
Wipe a whole collection in tests deleteMany({}) or drop()

Common mistakes

  • deleteMany(filter) where filter accidentally ended up as {}.
  • Treating deletedCount: 0 as success.
  • Soft deleting but forgetting to filter reads, so "deleted" data reappears in lists.
  • Expecting TTL deletion to be immediate or on a field that is not a Date.
  • Using separate writes in a loop for imports instead of bulkWrite or insertMany.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens when you call Model.deleteMany({})?

    An empty filter matches all documents, so guard against accidentally empty filters.
  2. 2. What does a TTL index do?

    A TTL index on a Date field lets MongoDB remove documents automatically, checking roughly once a minute.
  3. 3. How do operations in bulkWrite run by default?

    Ordered is the default. Pass ordered: false to continue past errors.
  4. 4. Which is the best approach when deleted data must be restorable?

    Marking records with a deletedAt date keeps the data and lets you restore it.

Summary

  • deleteOne, deleteMany and findOneAndDelete remove data; check deletedCount and guard against empty filters.
  • Soft delete (a deletedAt field plus a query hook) keeps data recoverable; TTL indexes expire temporary data automatically.
  • bulkWrite batches mixed insert, update, replace and delete operations; they run in order unless ordered: false.
  • Use insertMany for plain bulk inserts and atomic operators for counters.

Next: Pagination and lean queries