I'm running a website in Go and I'm using the MGO package to connect with my MongoDB database.
I am handling a user's sign in, and I am trying to use the func Upsert()
to update a user if they exist in the database, otherwise insert them.
The issue is, when I run Upsert()
(the code below), it replaces all fields rather than updating only the present fields in the second argument's bson.M{}
.
db.C("users").Upsert(
bson.M{"email": "[email protected]"}, // Which doucment to upsert
bson.M{"displayName": "Johhny"}, // What to replace
)
A visual example of what I'm trying to explain.
An existing database document:
{
"_id" : ObjectId("58e7589bab64da55ebcf5d25"),
"email" : "[email protected]",
"password" : "",
"age": 69,
"displayName" : "Someone!"
}
After running:
db.C("users").Upsert(
bson.M{"email": "[email protected]"},
bson.M{"displayName": "My name was updated"},
)
The document becomes:
{
"_id" : ObjectId("58e789feab64da55ebcf691c"),
"displayName" : "My name was updated"
}
When I expected the document to become:
{
"_id" : ObjectId("58e7589bab64da55ebcf5d25"),
"email" : "[email protected]",
"password" : "",
"age": 69,
"displayName" : "My name was updated" // This should be updated, all others should be left untouched
}
Finally my question.
How can I update a document if it already exists in a MongoDB collection, otherwise insert it?
If you are trying to update a document with fields that you provide and ignore all other fields then I think it's not possible without a select first.
See this question on stack overflow
EDIT: Try:
db.C("users").Upsert(
bson.M{"email": "[email protected]"},
bson.M{"$set": bson.M{"displayName": "My name was updated"}},
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With