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
},
])
If the following command is used:
db.users.updateOne({_id: 5}, {$set: {admin: true}})
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 }
)
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()
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
}
Did you find this information useful? If so, consider heading over to my donation page and drop me some support.
Want to ask a question or just chat? Contact me here