MongoDB: replaceOne

Update() in MongoDB

In MongoDB previously, there was an update() that was used to replace the entire document that satisfies the parameter, with the new values passed. However, the function is now deprecated and not supported by the new versions.

replaceOne

replaceOne in MongoDB

1) The update() is now replaced by replaceOne() in MongoDB.

2) replaceOne() in MongoDB is used to replace the entire document with the given set of values, the condition being, the document must fulfill the filter criteria.

3) replaceOne() in MongoDB have 3 parameter:

  • filter- It acts as a filter to what document will be selected. Therefore, it can be said that this parameter sets the criteria for the document to be selected.  
  • replacement- This contains all the sets of values that need to be replaced in place of original values.
  • options- Also, there are various other options that we are going to discuss later.

Syntax

replaceOne (filter, replacement, options)

Example

There are some documents present inside edatabase collection as shown below:

replaceOne

Moving ahead you need to replace first document with the Name as Shreya, with the given sets of values :
Name: 'Charu' 
Department: 'Marketing'

Follow the code given below to perform the same task:

 db.edatabase.replaceOne({Name:'Shreya'},{Name:'Charu',Department:'Marketing'})

Output

replaceOne

Also, the check the final values in the edatabase collection, refer to the image below:

replaceOne