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 ...}}.

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

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分