mongodb - Golang MGO - Insert or update not working as expected -
i'm running website in go , i'm using mgo package connect mongodb database.
i handling user's sign in, , trying use func upsert()
update user if exist in database, otherwise insert them.
the issue is, when run upsert()
(the code below), replaces fields rather updating present fields in second argument's bson.m{}
.
db.c("users").upsert( bson.m{"email": "someone@gmail.com"}, // doucment upsert bson.m{"displayname": "johhny"}, // replace )
a visual example of i'm trying explain.
an existing database document:
{ "_id" : objectid("58e7589bab64da55ebcf5d25"), "email" : "someone@gmail.com", "password" : "", "age": 69, "displayname" : "someone!" }
after running:
db.c("users").upsert( bson.m{"email": "someone@gmail.com"}, bson.m{"displayname": "my name updated"}, )
the document becomes:
{ "_id" : objectid("58e789feab64da55ebcf691c"), "displayname" : "my name updated" }
when expected document become:
{ "_id" : objectid("58e7589bab64da55ebcf5d25"), "email" : "someone@gmail.com", "password" : "", "age": 69, "displayname" : "my name updated" // should updated, others should left untouched }
finally question.
how can update document if exists in mongodb collection, otherwise insert it?
if trying update document fields provide , ignore other fields think it's not possible without select first.
see question on stack overflow
edit: try:
db.c("users").upsert( bson.m{"email": "someone@gmail.com"}, bson.m{"$set": bson.m{"displayname": "my name updated"}}, )
Comments
Post a Comment