dongmu1951 2012-08-18 00:01
浏览 81
已采纳

Golang / mgo:无法从MongoDB文档中检索int字段的值

I am querying a collection that includes an integer value among it's values, and loading resulting documents into this struct:

type Subscription struct {
    Id bson.ObjectId "_id,omitempty"
    Listen string
    Job string
    TimeoutSeconds int
    Data string
}


var subscription Subscription

subscriptions := subscriptionsCol.Find(bson.M{"listen": "example_channel"}).Iter()
for subscriptions.Next(&subscription) {
    log("Pending job: %s?%s (timeout: %d)
",
            subscription.Job, 
            subscription.Data, 
            subscription.TimeoutSeconds)
}

This is what phpMoAdmin shows me:

[_id] => MongoId Object (
    [$id] => 502ed8d84eaead30a1351ea7
)
[job] => partus_test_job_a
[TimeoutSeconds] => 30
[listen] => partus.test
[data] => a=1&b=9

It puzzles me that subscription.TimeoutSeconds contains always 0, when I'm positive I have 30 in the document I inserted in the collection.

All other values are retrieved OK.

What's wrong with the int type?

  • 写回答

2条回答 默认 最新

  • douwang4374 2012-08-18 01:25
    关注

    Have you tried setting the "key" value for that field?

    Unmarshal

    The lowercased field name is used as the key for each exported field, but this behavior may be changed using the respective field tag.

    type Subscription struct {
        Id              bson.ObjectId    "_id,omitempty"
        Listen          string
        Job             string
        TimeoutSeconds  int     "TimeoutSeconds"
        Data            string
    }
    

    The other fields are working fine because their lowercase value matches your Mongo fields in the collection, whereas TimeoutSeconds is using the TitleCase. What is happening is the int field is being left at its zero value, since the Unmarshal can't map a field to it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!