Replacing Values in MongoDB: Comprehensive Guide

An application keeps on updating the value like updating the age of the user over time, updating the profile, details and many more, that is why updating the value is an essential feature of an application. To update means to replace the existing value with the new one.

Replacing values in MongoDB is done using two popular functions in the mongo shell replaceOne() and findOneAndReplace(). Both functions are used for replacing values in MongoDB and behave more or less the same. However, there are a few differences between them. Both functions replace a single value based on the filters we provide.

This tutorial will teach you MongoDB replace value by using both methods in the Mongo shell with different examples so that you can decide which one to implement for your next project.

Also Read: findOneAndUpdate() and findAndModify() in MongoDB

Replacing Values using replaceOne()

Let’s start with understanding the replaceOne() method.

Syntax of replaceOne() Method

db.collection.replaceOne(
   filter,
   replacement,
   {
     upsert: boolean,
     writeConcern: document,
     collation: document,
     hint: document|string                   // Available starting in 4.2.1
   }
)

Implementation of replaceOne() Method

  • Start up the MongoDB server
  • Pick the database you want to work in, and move into it:
show dbs
use shoeStore
  • Let us first check what are the documents that are available in our collection:
> db.shoes.find({}).pretty()
{
        "_id" : ObjectId("616714c6461c6d31d88b4d90"),
        "name" : "Dmitri Vu's Highs",
        "price" : 5300,
        "size" : 8,
        "style" : "Chelsea Boots",
        "__v" : 0
}
{
        "_id" : ObjectId("616714c6461c6d31d88b4d91"),
        "name" : "Nike Renew Serenity Run",
        "price" : 5450,
        "size" : 7,
        "style" : "Running Shoes",
        "__v" : 0
}
{
        "_id" : ObjectId("616714c6461c6d31d88b4d92"),
        "name" : "Adidas Ultraboost 20 x James Bond Shoes",
        "price" : 6780,
        "size" : 6,
        "style" : "Running Shoes",
        "__v" : 0
}
{
        "_id" : ObjectId("616714c6461c6d31d88b4d93"),
        "name" : "Myrna's D'Orsays",
        "price" : 9760,
        "size" : 7,
        "style" : "D'Orsay",
        "__v" : 0
}
{
        "_id" : ObjectId("616716ad33e9f410d4cdfded"),
        "name" : "Choco-Lita YMX 60",
        "price" : 3400,
        "size" : 9,
        "style" : "Lita",
        "__v" : 0
}
  • Now, use the replaceOne() function for replacing the values of a document in our collection:
> db.shoes.replaceOne({
...         "name" : "Adidas Ultraboost 20 x James Bond Shoes"
... }, {
...         "name" : "Marlo Wood’s Lite Moccasins",
...         "price" : 8880,
...         "size" : 9,
...         "style" : "Moccasins"
... })
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

Here the first argument object contains a key name, the document having a name key with the same value passed here will replace with the new values passed inside the second argument object.

  • Let us look at our documents now:
> db.shoes.find({}).pretty()
{
        "_id" : ObjectId("616714c6461c6d31d88b4d90"),
        "name" : "Dmitri Vu's Highs",
        "price" : 5300,
        "size" : 8,
        "style" : "Chelsea Boots",
        "__v" : 0
}
{
        "_id" : ObjectId("616714c6461c6d31d88b4d91"),
        "name" : "Nike Renew Serenity Run",
        "price" : 5450,
        "size" : 7,
        "style" : "Running Shoes",
        "__v" : 0
}
{
        "_id" : ObjectId("616714c6461c6d31d88b4d92"),
        "name" : "Marlo Wood’s Lite Moccasins",
        "price" : 8880,
        "size" : 9,
        "style" : "Moccasins"
}
{
        "_id" : ObjectId("616714c6461c6d31d88b4d93"),
        "name" : "Myrna's D'Orsays",
        "price" : 9760,
        "size" : 7,
        "style" : "D'Orsay",
        "__v" : 0
}
{
        "_id" : ObjectId("616716ad33e9f410d4cdfded"),
        "name" : "Choco-Lita YMX 60",
        "price" : 3400,
        "size" : 9,
        "style" : "Lita",
        "__v" : 0
}

In the above result, you can see that the document having the name key with the value we passed is now replaced with the new specified values.

Replacing Values in MongoDB using replaceOne() that Don’t Exist

Let us use the replaceOne() function for replacing values that do not exist in any document.

The replaceOne() function can create a new document with the specified value if the document to be replaced is not found. For the function to create a new document, we have to pass an optional argument upsert option as true.

Example:

> db.shoes.replaceOne({
...         "name" : "Cara James Red Stilettos (Limited Edition)"
... }, {
...         "name" : "Starvis Thigh Highs Mango Yellow",
...         "price" : 10580,
...         "size" : 8,
...         "style" : "Thigh High Boots"
... }, { upsert: true })
{
        "acknowledged" : true,
        "matchedCount" : 0,
        "modifiedCount" : 0,
        "upsertedId" : ObjectId("61671f63e97d0a62702d57b5")
}
  • Let us check our documents:
> db.shoes.find({}).pretty()
{
        "_id" : ObjectId("616714c6461c6d31d88b4d90"),
        "name" : "Dmitri Vu's Highs",
        "price" : 5300,
        "size" : 8,
        "style" : "Chelsea Boots",
        "__v" : 0
}
{
        "_id" : ObjectId("616714c6461c6d31d88b4d91"),
        "name" : "Nike Renew Serenity Run",
        "price" : 5450,
        "size" : 7,
        "style" : "Running Shoes",
        "__v" : 0
}
{
        "_id" : ObjectId("616714c6461c6d31d88b4d92"),
        "name" : "Marlo Wood’s Lite Moccasins",
        "price" : 8880,
        "size" : 9,
        "style" : "Moccasins"
}
{
        "_id" : ObjectId("616714c6461c6d31d88b4d93"),
        "name" : "Myrna's D'Orsays",
        "price" : 9760,
        "size" : 7,
        "style" : "D'Orsay",
        "__v" : 0
}
{
        "_id" : ObjectId("616716ad33e9f410d4cdfded"),
        "name" : "Choco-Lita YMX 60",
        "price" : 3400,
        "size" : 9,
        "style" : "Lita",
        "__v" : 0
}
{
        "_id" : ObjectId("61671f63e97d0a62702d57b5"),
        "name" : "Starvis Thigh Highs Mango Yellow",
        "price" : 10580,
        "size" : 8,
        "style" : "Thigh High Boots"
}

Here you can see that a new document has been created which we have passed to replace a non-exit document.

Replacing Values in MongoDB using findOneAndReplace()

Let’s now see the way to replace a value in MongoDB using the findOneAndReplace() method.

Syntax of findOneAndReplace() Method

db.collection.findOneAndReplace(
   filter,
   replacement,
   {
     projection: document,
     sort: document,
     maxTimeMS: number,
     upsert: boolean,
     returnNewDocument: boolean,
     collation: document
   }
)

Implementation of findOneAndReplace() Method

Let’s get right into replacing values in a MongoDB database object using the findOneAndReplace() method. Here’s an example of how that works.

> db.shoes.findOneAndReplace({"name" : "Nike Renew Serenity Run"}, {
...         "name" : "Purple Haven Lavender Kittens",
...         "price" : 14610,
...         "size" : 9,
...         "style" : "Kitten Heels"
... })
{
        "_id" : ObjectId("616714c6461c6d31d88b4d91"),
        "name" : "Nike Renew Serenity Run",
        "price" : 5450,
        "size" : 7,
        "style" : "Running Shoes",
        "__v" : 0
}

You can notice that the findOneAndReplace() function also returns the document that was matched.

  • Checking our documents:
> db.shoes.find({}).pretty()
{
        "_id" : ObjectId("616714c6461c6d31d88b4d90"),
        "name" : "Dmitri Vu's Highs",
        "price" : 5300,
        "size" : 8,
        "style" : "Chelsea Boots",
        "__v" : 0
}
{
        "_id" : ObjectId("616714c6461c6d31d88b4d91"),
        "name" : "Purple Haven Lavender Kittens",
        "price" : 14610,
        "size" : 9,
        "style" : "Kitten Heels"
}
{
        "_id" : ObjectId("616714c6461c6d31d88b4d92"),
        "name" : "Marlo Wood’s Lite Moccasins",
        "price" : 8880,
        "size" : 9,
        "style" : "Moccasins"
}
{
        "_id" : ObjectId("616714c6461c6d31d88b4d93"),
        "name" : "Myrna's D'Orsays",
        "price" : 9760,
        "size" : 7,
        "style" : "D'Orsay",
        "__v" : 0
}
{
        "_id" : ObjectId("616716ad33e9f410d4cdfded"),
        "name" : "Choco-Lita YMX 60",
        "price" : 3400,
        "size" : 9,
        "style" : "Lita",
        "__v" : 0
}
{
        "_id" : ObjectId("61671f63e97d0a62702d57b5"),
        "name" : "Starvis Thigh Highs Mango Yellow",
        "price" : 10580,
        "size" : 8,
        "style" : "Thigh High Boots"
}

Here you can see that the specified document has been replaced by the document we passed.

Replacing Values in MongoDB using findOneAndReplace() that Don’t Exist

Now that you know how the findOneAndReplace() method works, let’s try to replace values that don’t exist using this method. Here’s an example of how to do that.

Example:

> db.shoes.findOneAndReplace({ "name" : "Cara James Red Stilettos (Limited Edition)" }, {
...         "name" : "Fiona Dewy Pink-White Espadrilles",
...         "price" : 6940,
...         "size" : 6,
...         "style" : "Espadrilles"
... })

null

We receive a null value when replacing values in MongoDB that don’t exist using findOneAndReplace().

  • Checking our documents:
> db.shoes.find({}).pretty()
{
        "_id" : ObjectId("616714c6461c6d31d88b4d90"),
        "name" : "Dmitri Vu's Highs",
        "price" : 5300,
        "size" : 8,
        "style" : "Chelsea Boots",
        "__v" : 0
}
{
        "_id" : ObjectId("616714c6461c6d31d88b4d91"),
        "name" : "Purple Haven Lavender Kittens",
        "price" : 14610,
        "size" : 9,
        "style" : "Kitten Heels"
}
{
        "_id" : ObjectId("616714c6461c6d31d88b4d92"),
        "name" : "Marlo Wood’s Lite Moccasins",
        "price" : 8880,
        "size" : 9,
        "style" : "Moccasins"
}
{
        "_id" : ObjectId("616714c6461c6d31d88b4d93"),
        "name" : "Myrna's D'Orsays",
        "price" : 9760,
        "size" : 7,
        "style" : "D'Orsay",
        "__v" : 0
}
{
        "_id" : ObjectId("616716ad33e9f410d4cdfded"),
        "name" : "Choco-Lita YMX 60",
        "price" : 3400,
        "size" : 9,
        "style" : "Lita",
        "__v" : 0
}
{
        "_id" : ObjectId("61671f63e97d0a62702d57b5"),
        "name" : "Starvis Thigh Highs Mango Yellow",
        "price" : 10580,
        "size" : 8,
        "style" : "Thigh High Boots"
}

Since the function couldn’t find any matching values, it did not change any values.

Read More: Top 8 MongoDB Hosting for Small Enterprises

Conclusion

In this tutorial we have learned two functions replaceOne() and findOneAndReplace() to replace the value in MongoDB, both functions are the same but when trying to replace a non-existing value replaceOne() creates it if it’s not found while the function findOneAndReplace() simply return NULL.

References

https://docs.mongodb.com/manual/reference/method/db.collection.replaceOne/#examples

https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndReplace/

Aneesha S
Aneesha S
Articles: 171