S

Loading…

Deletes+

Writing Data

Deletes

Delete one or many

await users.deleteOne({ email: "kage@example.com" });

const result = await sessions.deleteMany({ expiresAt: { $lt: new Date() } });
result.deletedCount; // how many were removed

deleteOne removes the first document that matches. deleteMany removes every match. Both return a DeleteResult. Deleting when nothing matches is not an error: deletedCount is 0.

To delete one specific document, filter by its _id:

await users.deleteOne({ _id: user._id });

Empty a collection

An empty filter matches every document:

await logs.deleteMany({});

The collection itself stays, empty, along with its indexes. You can't drop a collection or a database yet.

Atomicity

A deleteMany removes every matching document or none, never part of them. Separate commands aren't grouped into transactions, so another client can write between two of your deletes.

Getting space back

Deleted documents are gone from queries right away. Disk space comes back gradually, as the server takes new checkpoints and removes log files it no longer needs. It keeps the two newest snapshots, so this takes more than one checkpoint. See storage.md for the details.