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 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序