DEV Community

Cover image for This is how to do upserting in MongoDB
Donald Feury
Donald Feury

Posted on • Originally published at donaldfeury.xyz on

This is how to do upserting in MongoDB

This is how to do upserting in MongoDB

For a full overview of MongoDB and all my posts on it, check out my overview.

Upserting is a database concept that combines inserting and updating that MongoDB supports. To perform an upsert during an update operation, you must pass an additional argument to the update, updateOne, or updateMany methods.

With the given data inserted in a collection called users:

db.users.insertMany([
    {
        _id: 1,
        name: "John Doe",
        email: "doe@doe.com",
        admin: true
    },
    {
        _id: 2,
        name: "Jane Doe",
        email: "jane@doe.com",
        admin: true
    },
    {
        _id: 3,
        name: "Billy Bob",
        email: "billy@bob.com",
        admin: false
    },
    {
        _id: 4
        name: "Steve Stevenson",
        email: "steve@test.com",
        admin: true
    },
])

Enter fullscreen mode Exit fullscreen mode

If the following command is used:

db.users.updateOne({_id: 5}, {$set: {admin: true}})

Enter fullscreen mode Exit fullscreen mode

It won't do anything as there is no document matching the query of _id = 5.

If upserting is enabled:

db.users.updateOne(
    {_id: 5},
    { $set: { admin: true } },
    { upsert: true }
)

Enter fullscreen mode Exit fullscreen mode

Since there is no document matching the query, a new document is inserting using the given _id and the result of the update operators.

Use the find method to read data back out of MongoDB to check the collection:

db.users.find()

Enter fullscreen mode Exit fullscreen mode

Will yield:

{
    _id: 1,
    name: "John Doe",
    email: "doe@doe.com",
    admin: true
},
{
    _id: 2,
    name: "Jane Doe",
    email: "jane@doe.com",
    admin: true
},
{
    _id: 3,
    name: "Billy Bob",
    email: "billy@bob.com",
    admin: false
},
{
    _id: 4
    name: "Steve Stevenson",
    email: "steve@test.com",
    admin: true
},
{
    _id: 5
    admin: true
}

Enter fullscreen mode Exit fullscreen mode

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more