我正在使用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集合中已经存在一个文档,我该如何更新它,否则就插入它?
$set
操作符,类似这样:bson.M{"$set": bson.M{"displayName": "我的名字已更新"}}
。 - ZakUpdate()
时,我需要使用"$set"作为bson键吗? - Ari Seyhun$set
用给定的值替换字段的值,它允许您仅更新该字段。如果您想要更新文档的一部分而不是整个文档,请尝试使用$set
,如果您想要更新整个文档,请尝试省略它。 - Zak