duangou6446 2015-03-09 15:51
浏览 42
已采纳

在MGO驱动程序中更新查询,可与bson.M一起使用,但不适用于自定义结构

Mgo and golang question.

I run into problem again. I try to update record in the database, but running simple command visitors.UpdateId(v.Id, bson.M{"$set": zscore}); where zscore is a variable of type Zscore, does not work. However if I manually convert zscore to bson.M structure, everything works fine.

Does anybody know how to update the record in mongodb using mgo, without manually dumping structure values into bson.M?

Example:

type Zscore struct {
    a float64 `bson:"a,omitempty" json:"a"`
    b float64 `bson:"b,omitempty" json:"b"`
    c float64 `bson:"c,omitempty" json:"c"`
}

v := Visitor{}
zscore := Zscore{}

visitors := updater.C("visitors")

for result.Next(&v) {
    zscore.a = 1
    zscore.b = 2
    zscore.c = 0

    //does not work
    if err := visitors.UpdateId(v.Id, bson.M{"$set": zscore}); err != nil    {
            log.Printf("Got error while updating visitor: %v
", err)
    }

    //works
    set := bson.M{
        "zscore.a": zscore.a,
        "zscore.b": zscore.b,
        "zscore.c": zscore.c,
    }

    if err := visitors.UpdateId(v.Id, bson.M{"$set": set}); err != nil {
        log.Printf("Got error while updating visitor: %v
", err)
    }
}
  • 写回答

1条回答 默认 最新

  • duanaoreng9355 2015-03-09 17:15
    关注

    All Go marshaling packages I'm aware of, including the bson package, will not marshal fields that are private (start with a lowercase letter). To fix the issue, just export the relevant fields by uppercasing the first letter of their name.

    Also note that, besides the issue mentioned above, the first part of your example will not marshal in an equivalent way to the second part. bson.M{"$set": zscore} is equivalent to bson.M{"$set": bson.M{"a": ... etc ...}}.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?