16
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: "[email protected]",
admin: true
},
{
_id: 2,
name: "Jane Doe",
email: "[email protected]",
admin: true
},
{
_id: 3,
name: "Billy Bob",
email: "[email protected]",
admin: false
},
{
_id: 4
name: "Steve Stevenson",
email: "[email protected]",
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.
db.users.find()
Will yield:
{
_id: 1,
name: "John Doe",
email: "[email protected]",
admin: true
},
{
_id: 2,
name: "Jane Doe",
email: "[email protected]",
admin: true
},
{
_id: 3,
name: "Billy Bob",
email: "[email protected]",
admin: false
},
{
_id: 4
name: "Steve Stevenson",
email: "[email protected]",
admin: true
},
{
_id: 5
admin: true
}
16