gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 00:43:32 24 4
gpt4 key购买 nike

我在 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 集合中,我如何更新文档,否则将其插入?

最佳答案

如果您尝试使用您提供的字段更新文档并忽略所有其他字段,那么我认为如果不先进行选择是不可能的。

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"}},
)

关于mongodb - Golang MGO - 插入或更新未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43278696/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com