Golang MGO-插入或更新无法正常工作 [英] Golang MGO - Insert or update not working as expected

查看:112
本文介绍了Golang MGO-插入或更新无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Go中运行一个网站,并且正在使用 MGO 程序包来连接我的MongoDB数据库

I'm running a website in Go and I'm using the MGO package to connect with my MongoDB database.

我正在处理用户的登录,并且尝试使用功能 Upsert() 以更新数据库中是否存在用户,否则将其插入.

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.

问题是,当我运行 Upsert() (下面的代码),它将替换所有字段,而不是仅更新第二个参数的 bson.M {} 中的当前字段.

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": "someone@gmail.com"}, // Which doucment to upsert
    bson.M{"displayName": "Johhny"}, // What to replace
)


我要解释的直观示例.

现有的数据库文档:

{
    "_id" : ObjectId("58e7589bab64da55ebcf5d25"),
    "email" : "someone@gmail.com",
    "password" : "",
    "age": 69,
    "displayName" : "Someone!"
}

运行后:

db.C("users").Upsert(
    bson.M{"email": "someone@gmail.com"},
    bson.M{"displayName": "My name was updated"},
)

文档变为:

{
    "_id" : ObjectId("58e789feab64da55ebcf691c"),
    "displayName" : "My name was updated"
}

当我希望文档成为:

{
    "_id" : ObjectId("58e7589bab64da55ebcf5d25"),
    "email" : "someone@gmail.com",
    "password" : "",
    "age": 69,
    "displayName" : "My name was updated" // This should be updated, all others should be left untouched
}


最后是我的问题.

如果文档已存在于MongoDB集合中,如何更新它,否则将其插入?

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.

在堆栈溢出时看到此问题

试试:

db.C("users").Upsert(
    bson.M{"email": "someone@gmail.com"},
    bson.M{"$set": bson.M{"displayName": "My name was updated"}},
)

这篇关于Golang MGO-插入或更新无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆