Golang MGO - 插入或更新不按预期工作

5
我正在使用Go运行一个网站,并使用MGO包连接我的MongoDB数据库。
我正在处理用户的登录,尝试使用函数Upsert()更新用户(如果他们存在于数据库中),否则插入他们。
问题是,当我运行Upsert()(下面的代码)时,它替换所有字段而不是仅更新第二个参数中存在的字段。
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集合中已经存在一个文档,我该如何更新它,否则就插入它?

1个回答

5

如果您想使用提供的字段更新文档并忽略所有其他字段,则我认为在没有先进行选择的情况下是不可能实现的。

请参考Stack Overflow上的这个问题

编辑:尝试使用以下方法:

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

你是说我需要向MongoDB发起两个查询吗?首先选择,检查错误,然后(如果不存在则更新/存在则插入)这样的操作? - Ari Seyhun
抱歉,我误解了,你需要使用$set操作符,类似这样:bson.M{"$set": bson.M{"displayName": "我的名字已更新"}} - Zak
还有一个快速的问题...在使用Update()时,我需要使用"$set"作为bson键吗? - Ari Seyhun
$set 用给定的值替换字段的值,它允许您仅更新该字段。如果您想要更新文档的一部分而不是整个文档,请尝试使用 $set,如果您想要更新整个文档,请尝试省略它。 - Zak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接