When deleteOne is called, MongoDB uses the filter to search the collection. If an index exists on the filter fields, it uses the index to quickly locate the first matching document. Once found, it locks the document to prevent concurrent changes, deletes it atomically, and updates the collection metadata. The operation returns a result object indicating success and count of deleted documents.
Why designed this way?
deleteOne was designed to provide a safe, precise way to remove a single document without risking multiple deletions. Using indexes speeds up searches, and atomic deletion ensures data integrity. Alternatives like deleteMany exist for bulk deletions, but deleteOne focuses on controlled, minimal impact changes.
βββββββββββββββ
β deleteOne() β
βββββββ¬ββββββββ
β
βΌ
βββββββββββββββ Uses index? βββββββββββββββββ
β Filter docs βββββββββββββββββΆβ Use index to β
β in collectionβ β find first docβ
βββββββ¬ββββββββ βββββββ¬ββββββββββ
β β
βΌ βΌ
βββββββββββββββ βββββββββββββββ
β Lock doc β β Scan docs β
β atomically β β sequentiallyβ
βββββββ¬ββββββββ βββββββ¬ββββββββ
β β
βΌ βΌ
βββββββββββββββ βββββββββββββββ
β Delete doc β β Delete doc β
β and update β β and update β
β metadata β β metadata β
βββββββ¬ββββββββ βββββββ¬ββββββββ
β β
βΌ βΌ
βββββββββββββββ βββββββββββββββ
β Return β β Return β
β result obj β β result obj β
βββββββββββββββ βββββββββββββββ