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 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积