Introduction to MongoDB collection.replaceOne() Method

replaceOne() is an update operation in MongoDB that replaces a document that matches a specified filter. This article introduces the syntax, usage scenarios, examples, and conclusions of this method.

Syntax

The syntax of replaceOne() method is as follows:

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

Here, db.collection represents the collection to update, filter is the filter criteria, replacement is the replacement document, and options is an optional parameter that specifies some options for the update operation, such as whether to insert a new document when no matching document exists in the collection.

Usage Scenarios

replaceOne() method is typically used to replace a single document. It can be used to update data in a collection or to create a new document. For example, if you want to replace an existing document with a new one, you can use this method.

Example

Here’s an example of using replaceOne() method to replace a document:

Assume we have a collection named users, which contains the following three documents:

{ "_id": 1, "name": "Alice", "age": 20 }
{ "_id": 2, "name": "Bob", "age": 25 }
{ "_id": 3, "name": "Charlie", "age": 30 }

Now we want to replace the document with name equals to "Alice" with a new document that has the following content:

{ "_id": 1, "name": "Eve", "age": 22 }

We can achieve this with the following code:

db.users.replaceOne({ name: "Alice" }, { _id: 1, name: "Eve", age: 22 })

After executing the above code, the data in the users collection will become:

{ "_id": 1, "name": "Eve", "age": 22 }
{ "_id": 2, "name": "Bob", "age": 25 }
{ "_id": 3, "name": "Charlie", "age": 30 }

Conclusion

replaceOne() method is an update operation in MongoDB that replaces a document that matches a specified filter. When using this method, you need to specify the collection to update, the filter criteria, and the replacement document. In addition, you can specify some options for the update operation through the options parameter.