doushen1026 2017-04-07 12:52 采纳率: 100%
浏览 138
已采纳

Golang MGO-插入或更新无法正常工作

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

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.

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
)

A visual example of what I'm trying to explain.

An existing database document:

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

After running:

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

The document becomes:

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

When I expected the document to become:

{
    "_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
}

Finally my question.

How can I update a document if it already exists in a MongoDB collection, otherwise insert it?

  • 写回答

1条回答 默认 最新

  • dongzheng7165 2017-04-07 12:58
    关注

    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.

    See this question on stack overflow

    EDIT: Try:

    db.C("users").Upsert(
        bson.M{"email": "someone@gmail.com"},
        bson.M{"$set": bson.M{"displayName": "My name was updated"}},
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵