New to Rust? Grab our free Rust for Beginners eBook Get it free →
FindOneAndUpdate MongoDB vs findAndModify

To choose between MongoDB’s mongosh update helpers, compare findOneAndUpdate() with findAndModify(). Both update one matching document, and by default both return its pre-update version.
This article explains which helper MongoDB recommends for new mongosh updates and shows how to migrate a findAndModify() call with its return behavior accounted for.
TL;DR
For new mongosh updates, choose findOneAndUpdate(). MongoDB marks the shell findAndModify() helper deprecated, while its database command and driver interfaces remain distinct.
- Both shell helpers update one matching document and return its pre-update version by default.
- Use returnDocument: “after” with findOneAndUpdate() to request the updated document. Legacy shell code uses new: true.
- In the Node.js driver, check includeResultMetadata and the driver major version before expecting a value property.
What Do These MongoDB Operations Do?
In mongosh, db.collection.findOneAndUpdate(filter, update, options) accepts a filter, an update document or supported update pipeline, and optional controls for selection and return behavior.
db.orders.findOneAndUpdate(
{ _id: 42, status: "pending" },
{ $set: { status: "processing" } },
{ returnDocument: "after" }
)
findOneAndUpdate and findAndModify Compared
MongoDB marks the mongosh findAndModify() helper deprecated and points readers to focused helpers for updates, replacements, and removals.
| Question | findOneAndUpdate() in mongosh | findAndModify() in mongosh |
|---|---|---|
| Purpose | Update one matching document | Legacy helper for update or removal |
| Status | Preferred focused update helper | Deprecated. Docs point to focused helpers |
| Filter option | First argument, named filter | Inside the options document as query |
| Updated result | returnDocument: “after” | new: true |
| Default returned document | Pre-update document | Pre-update document |
| Delete operation | Use findOneAndDelete() | Can express remove behavior |
In Node.js, the driver returns a document or null by default. Set includeResultMetadata when the caller needs a wrapper with a value field, and check the installed driver version before accessing result.value.
How to Migrate a findAndModify Update
A staged migration gives reviewers a clear boundary for checking the behavior change.
Step 1: Identify the old operation and return contract
Inventory sort, upsert, projection, and return options used by the old call.
db.inventory.findAndModify({
query: { sku: "A-17" },
update: { $inc: { stock: -1 } },
new: true
})
Step 2: Move the query and update into method arguments
Use the old query as the filter, followed by the update and supported options.
db.inventory.findOneAndUpdate(
{ sku: "A-17" },
{ $inc: { stock: -1 } },
{ returnDocument: "after" }
)
Step 3: Carry over sort and upsert deliberately
If multiple records can satisfy the filter, preserve an intentional sort so the selected record follows the same rule. Carry over upsert only when a no-match insertion fits the workflow.
db.jobs.findOneAndUpdate(
{ state: "queued" },
{ $set: { state: "running" } },
{
sort: { createdAt: 1, _id: 1 },
returnDocument: "after"
}
)
Here the sort chooses the earliest queued job and uses _id as a tie-breaker.
Return Values, Upserts, and Other Edge Cases
A successful write and the returned image answer different questions. Check the filter result and return option separately.
| Case | What to expect | What to check |
|---|---|---|
| Matched document, default return option | Pre-update document | Request after image when caller needs changed fields |
| No match, upsert disabled | No document is updated. The documented helper returns null | Inspect filter values, types, and field names |
| No match, upsert enabled | A new document may be inserted | Use a suitable unique index to prevent duplicate upserts from concurrent requests |
| Several documents match | One document is selected | Supply sort when selection order matters |
| Node driver code expects result.value | Return shape depends on driver option and version | Check includeResultMetadata and the installed major version |
For an upsert, use a unique index on logical identity to guard against concurrent duplicate inserts.
A conditional update can encode a state transition in one operation. For example, match both an identifier and a pending status so a stale request no longer qualifies after another worker changes the record.
Projection limits the returned document to selected fields, so include the identifier and every field the next step needs.
Collation controls language-aware string comparison for matching and sorting. If a filter is expected to treat differently cased or accented strings alike, confirm the collection default or specify an operation-level collation where the API supports it. A mismatch between expected and configured comparison rules can look like a filter bug.
Array updates need a deliberate element selection rule. Array filters let an update target array elements that match conditions, while a positional update operator can target an element matched by the query. Read the documentation for the exact update syntax and arrayFilters option for the server and driver version in use.
An update document built from request data should allowlist fields and operators. Passing arbitrary client-provided objects as the update can expose fields the caller should not control, or turn a simple field update into a broader operation. Validate types and construct the intended update on the server side.
When the operation runs inside a transaction, follow the transaction’s session and write-concern rules. MongoDB advises against explicitly setting a write concern on an individual operation in a transaction. Transactions also carry more overhead than a single-document write, so use them to enforce a multi-document invariant rather than to wrap every update by default.
Timeout behavior deserves a separate check from “no match.” An operation-level maxTimeMS can terminate work that exceeds its time limit, which is different from a successful call returning null. Handle operation errors separately from an empty result, and avoid treating a timeout as proof that the update did not reach the server unless the driver’s error semantics establish that.
Write concern controls the acknowledgement expected from the deployment. Use the application’s configured durability requirements rather than copying an example value blindly. In a transaction, set write concern at the transaction level according to the driver documentation.
The update can use an aggregation pipeline for supported transformations, but a pipeline update has different syntax from an operator document. MongoDB documents a limited set of pipeline stages for this method. Validate the stage and expression against the server version instead of passing a full aggregation pipeline unchanged.
Before changing a production call, confirm three things in a test environment: the filter selects the intended record, the requested before-or-after result matches the caller’s contract, and an unmatched filter has the desired upsert behavior. These checks catch query mistakes without relying on a second read that can race with another update.
| Concern | How to check it | Why it matters |
|---|---|---|
| Filter | Compare field names, stored value types, identity, and expected state | A mismatch means no document qualifies, while a broad filter can target an unintended record |
| Update form | Use operators such as $set or $inc for selected fields, while a replacement method for a full document | The update representation determines whether unrelated fields remain |
| Sort | Specify a stable sort when several documents can match, adding a tie-breaker | Selection order then follows an explicit rule |
| Projection | Include every field required by the next application step | Fields omitted from the returned image are unavailable to that caller without another read |
| Upsert | Enable only when insert-on-no-match is desired and protect logical identity with a unique index | Concurrent requests can otherwise create duplicate logical records |
| Request data | Validate types and construct an allowlisted update on the server | Arbitrary client objects can expose fields or operators outside the intended change |
| Array fields | Review positional operators and arrayFilters against the server and driver version | The element-selection rule controls which members change |
| Collation | Check collection defaults or specify supported operation-level comparison rules | Case and accent handling can affect whether string values match |
The database findAndModify command has a response envelope with fields such as value, lastErrorObject, and ok. Do not assume that envelope is the return object from a shell helper or language driver.
For an upsert, a unique index on logical identity helps prevent concurrent requests from inserting duplicate records.
Performance also affects the choice. MongoDB documents additional retryable-write work for findOneAndUpdate because replica-set nodes may copy the full document to a side collection before updating it. For a large document where the application does not need the returned image, compare updateOne with sort on supported MongoDB versions.
The filter answers which record qualifies, while the update describes its change. Keeping those roles separate makes a call straightforward to review. An empty filter can match an arbitrary document, so use it only when that selection is intended.
The update argument accepts operator expressions such as $set and $inc, or a supported aggregation pipeline. It does not accept a replacement document. Use findOneAndReplace() when the task is to replace a whole record.
The new method’s positional arguments move the old query and update into separate places, while options retain controls such as sort and upsert. Sort order matters when the filter describes a queue or priority group rather than a unique identifier. Add a deterministic secondary field when the primary sort key can tie.
Parameters that shape selection, the update, and the response should be reviewed independently.
| Parameter | Role | Review question |
|---|---|---|
| filter | Selects eligible documents | Does it include a stable identity or required state? |
| update | Applies operators or an allowed pipeline | Does it change only intended fields? |
| sort | Chooses among multiple matches | Is the ordering deterministic? |
| projection | Limits returned fields | Can the caller proceed with this subset? |
| upsert | Creates a record when none match | Should a miss insert, and is identity uniquely indexed? |
| returnDocument | Selects before or after image | Does downstream code expect updated fields? |
| maxTimeMS | Sets an operation time limit | Does the caller distinguish timeout from no match? |
| collation | Sets comparison rules for strings | Do case and accent rules match the intended query? |
| arrayFilters | Selects array elements for supported updates | Are the element conditions narrowly scoped? |
| writeConcern | Controls acknowledgement requirements | Does deployment policy define this, especially in a transaction? |
Projection can keep a response small, but it also removes fields from the returned image. Include every field the next step needs. A projection does not change which document the filter selects.
Collation matters when string matching depends on language-aware case or accent rules. The comparison behavior must agree with the collection setting or the collation supplied to that call. Otherwise, a value that looks equivalent to a person may fail to match.
Array updates have a second selection problem: choosing the document does not specify which array members change. Use arrayFilters or a supported positional operator when the update should affect only elements meeting a condition. Keep the element predicate aligned with the intended change.
Examples of common update tasks
A stock adjustment can use $inc, while a state change can use $set with the previous state in the filter. These operators keep the operation focused on the requested field.
db.inventory.findOneAndUpdate(
{ sku: "A-17", stock: { $gte: 1 } },
{ $inc: { stock: -1 } },
{ returnDocument: "after", projection: { sku: 1, stock: 1 } }
)
The stock condition prevents this update from matching a record with no available unit. The projected response contains the SKU and updated stock, plus _id unless the projection excludes it.
A create-or-update workflow needs a deliberate upsert filter. Include the logical key and enforce its uniqueness with an index. Then concurrent requests for the same key cannot silently create multiple logical records, though applications should still handle duplicate-key outcomes where appropriate.
Use maxTimeMS when the application needs a bounded wait, but handle its error separately from the null result for no match. A timeout reports that the operation exceeded its limit, not that the filter safely found nothing.
Update pipelines can transform values from existing fields, but only documented stages are accepted by this helper. A normal update document should contain update operators. For a full replacement, use the replacement helper rather than mixing replacement fields with operators.
Single-document writes are atomic at the document level, which makes a condition in the filter useful for guarded transitions. Match the expected old state as well as the identifier. A separate read followed by a write leaves room for another request to change that state between operations.
That guarantee does not make a multi-document workflow atomic. Use a transaction when several writes must satisfy one invariant, and follow the driver’s session rules. MongoDB advises setting transaction write concern at the transaction level rather than on an individual operation inside it.
Best practice is to make each decision visible: constrain the filter, choose a deterministic sort when needed, select the return image explicitly, and enable upsert only for a genuine insert-on-miss task. Validate external data before constructing the update, and allow only fields the caller may change.
Before shipping a migration, compare behavior for a match, a miss, and an upsert in a test database. Check the returned shape in the exact API used by the application, since mongosh, the database command, the Node driver, and an ODM can expose different wrappers around the same write.
Conclusion
Use a filter that matches the business rule for the update, then choose the focused mongosh helper for that operation.
For new mongosh update code, choose findOneAndUpdate() and make the desired returned image explicit.
For syntax, use the MongoDB findOneAndUpdate reference and mongosh findAndModify reference. Node applications should consult the Node.js driver compound operations guide.
The CodeForGeek MongoDB findOneAndUpdate guide walks through that helper, while its updateMany guide covers multi-document updates.
FAQ
These answers focus on choosing the helper and interpreting its result.
Is findAndModify deprecated in MongoDB?
The mongosh db.collection.findAndModify() helper is deprecated, and MongoDB recommends the focused findOneAndUpdate(), findOneAndDelete(), or findOneAndReplace() helpers. The findAndModify database command is a distinct documented interface.
Does findOneAndUpdate return the updated document?
By default, mongosh returns the original document before the update. Set returnDocument: “after” to return the updated document. Driver behavior should be checked against its own version and options.
Why does my Node.js result have no value property?
The current Node.js driver guide documents includeResultMetadata as false by default, which returns the document or null directly. Set includeResultMetadata: true when the metadata wrapper with value is needed.




