Upsert in MongoDB

Shihab Sikder Apr 28, 2022
  1. the upsert Query in MongoDB
  2. Use the upsert Query With the update() Method
  3. Use the upsert Query With the findAndModify() Method
  4. Other Methods Supporting upsert
Upsert in MongoDB

In MongoDB, upsert combines the commands update and insert. It can be used in the update() and findAndModify() operation.

the upsert Query in MongoDB

upsert takes a single boolean parameter. If it is set to TRUE and a query document is found, it will update the document; if not found, it will insert a new document in the collection.

Syntax:

upsert: <boolean>

Use the upsert Query With the update() Method

Suppose you have the following document for the employee. To see the documents, you will type the following command in the Mongosh or MongoCLI (after successfully connecting to the database):

> db.employee.find().pretty()
{"_id":1,   "name":"Alice"}
{"_id":2,   "name":"Bob"}

Here, find() is used for searching documents or objects. We also can pass parameters to it.

For example, if you write find({"_id":1}), it will return only the object with an id of 1. pretty() is for printing the output in a nice format.

Now, if you try to update like the following:

> db.employee.update({_id:5},{name: "Jhon"})
WriteResult({"nMatched": 0,  "nUpserted": 0, "nModified": 0})

As we can see from the WriteResult, no document got updated. Now, try the upsert option with the TRUE value.

Let’s say you want to search for a name and update it. For example, you want to update all the names Sam to Samuel using the upsert option.

The query will be like the following:

> db.employee.update({name:"Sam"},{name: "Samuel"})
WriteResult({
    "nMatched": 0,  
    "nUpserted": 1, 
    "nModified": 0,
    "_id": ObjectId("67874504aed8aee9986")
})
>

Here, you can see that the upserted value is 1. Because there’s no match for the name Sam, it created an entity with a unique _id for it.

Now, if you want to view all entities under employee, you can run the following query:

> db.employee.find().pretty()
{"_id":1,   "name":"Alice"}
{"_id":2,   "name":"Bob"}
{"_id":ObjectId("67874504aed8aee9986"),   "name":"Samuel"}
>

Use the upsert Query With the findAndModify() Method

This method works the same as the update() method, but the findAndModify will only update the first matched object, whereas the update modifies all the matched entities.

Suppose we want to add a new field where the id equals to 3. We will write the following:

db.employee.findAndModify({query: {_id:3}, update:{$inc: {salary: 1500}}, upsert: true})
null
>

It returns null because it never existed.

If we view all entities, we can see a new object is added to the documents as the upsert was set to TRUE. It added a new entity with an id of 3 and a salary of 1500.

> db.employee.find().pretty()
{"_id":1,   "name":"Alice"}
{"_id":2,   "name":"Bob"}
{"_id":ObjectId("67874504aed8aee9986"),   "name":"Samuel"}
{"_id":5,   "salary":"1500"}

Other Methods Supporting upsert

We can use the upsert option in the following methods as well:

  1. updateOne()
  2. replaceOne()

You may visit this blog to know more. Also, here’s the official documentation from MongoDB.

Shihab Sikder avatar Shihab Sikder avatar

I'm Shihab Sikder, a professional Backend Developer with experience in problem-solving and content writing. Building secure, scalable, and reliable backend architecture is my motive. I'm working with two companies as a part-time backend engineer.

LinkedIn Website