MongoDB findOneAndReplace() Method (original) (raw)

Last Updated : 5 May, 2026

In MongoDB, findOneAndReplace() replaces the first matching document (including embedded documents) and returns the original document by default, or the new one using options.

Syntax

db.collection.findOneAndReplace(filter, replacement, options)

Return Value of findOneAndReplace()

Examples of MongoDB findOneAndReplace() Method

In the following examples, we are working with:

Screenshot-2026-02-07-122446

Example 1: Replace first matching document and returns replaced document

Finds the first document where age is 18 and replaces it with a new document. It returns the original document before replacement.

**Query:

db.student.findOneAndReplace({age:18},{name:"Maria", age:17})

**Before replacement:

Screenshot-2026-02-07-123139

**After replacement:

Screenshot-2026-02-07-123241

Example 2: Replace the first matched document and returns a new document

Replaces a document where age is 25 and ensures that the updated document is returned instead of the original.

**Query:

db.student.findOneAndReplace({age:25}, {name:"Sophia", age:45}, {returnDocument: "after"})

**Output:

Screenshot-2026-02-07-123545

Important Points

Here are some important points to remember: