Replacing Values in MongoDB: Comprehensive Guide

Replacing Values In MongoDB Featured Image

This tutorial encompasses the different ways of replacing values in MongoDB using the Mongo shell.

Replacing values in MongoDB is done using two popular functions in the mongo shell. These are replaceOne() and findOneAndReplace() functions in MongoDB.

Both the 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.

We will discuss the differences further in the guide when we dive deeper. This guide shall elucidate replacing values in MongoDB with examples for a better understanding. So, let us get started.

Replacing Values in MongoDB Functions Syntaxes

Let us take a look at what the functions syntaxes look like that help us in replacing values in MongoDB:

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

Replacing Values in MongoDB Using replaceOne() and findOneAndReplace() Methods

Let us get started with replacing values in MongoDB using the two functions: replaceOne() and findOneAndReplace().

Replacing Values Using replaceOne()

  • 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
}
  • I will now use the replaceOne() function for replacing 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 }
  • 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
}

The document is now replaced with the 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. For the function to create a new document, we shall pass the upsert option as true:

> 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"
}

Replacing Values in MongoDB Using findOneAndReplace()

Finally, let’s get right into replacing values in a MongDB 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 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"
}

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

Now that you know how the findOneAndReplace() method works, let’s conditionally replace values with the same method. Here’s an example of how to do that.

> 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.

Conclusion

Learn the ways of replacing values in MongoDB with examples in this guide in the Mongo shell.

Read More: Top 8 MongoDB Hosting for Small Enterprises

References

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

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