Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang MGO - Insert or update not working as expected

Tags:

mongodb

go

upsert

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?

like image 909
Ari Seyhun Avatar asked Apr 07 '17 12:04

Ari Seyhun


1 Answers

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"}},
)
like image 120
Zak Avatar answered Nov 11 '22 06:11

Zak