Golang MGO - 插入或更新未按预期工作
Golang MGO - Insert or update not working as expected
我正在使用 Go 运行创建一个网站,我正在使用 MGO 包连接我的 MongoDB 数据库。
我正在处理用户的登录,我正在尝试使用函数 Upsert()
更新用户(如果数据库中存在),否则将其插入。
问题是,当我 运行 Upsert()
(下面的代码)时,它会替换所有字段,而不是仅更新第二个参数 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 集合中,我如何更新文档,否则将其插入?
如果您尝试使用您提供的字段更新文档并忽略所有其他字段,那么我认为没有先 select 是不可能的。
See this question on stack overflow
编辑:
尝试:
db.C("users").Upsert(
bson.M{"email": "someone@gmail.com"},
bson.M{"$set": bson.M{"displayName": "My name was updated"}},
)
我正在使用 Go 运行创建一个网站,我正在使用 MGO 包连接我的 MongoDB 数据库。
我正在处理用户的登录,我正在尝试使用函数 Upsert()
更新用户(如果数据库中存在),否则将其插入。
问题是,当我 运行 Upsert()
(下面的代码)时,它会替换所有字段,而不是仅更新第二个参数 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 集合中,我如何更新文档,否则将其插入?
如果您尝试使用您提供的字段更新文档并忽略所有其他字段,那么我认为没有先 select 是不可能的。
See this question on stack overflow
编辑: 尝试:
db.C("users").Upsert(
bson.M{"email": "someone@gmail.com"},
bson.M{"$set": bson.M{"displayName": "My name was updated"}},
)