如何防止将 mgo 解组为 float64 类型的 int 值

huangapple go评论72阅读模式
英文:

How to prevent mgo to unmarshal int to float64

问题

我在mongodb中存储了未知的json结构数据。它们有用于表示Unix时间的字段,格式如下:

"date": 1424803567,

我正在使用mgo将它们加载到bson.M中。

var result bson.M
iter := c.Find(q).Iter()
for iter.Next(&result) {

这些Unix时间字段已经转换为float64而不是int。

"date": 1.424728798e+09,

那么,在上述情况下如何防止这种情况发生?谢谢!

英文:

I have unknown json structure data stored in mongodb. They have the fields to present the unix time like this:

"date": 1424803567,

I am using mgo to load them to the bson.M.

var result bson.M
iter := c.Find(q).Iter()
for iter.Next(&result) {

Those unix time fields have turned to the fload64 instead of the int.

 "date": 1.424728798e+09,

So, how to prevent that happens in the case above? thanks!

答案1

得分: 1

Mgo在目标值没有明确声明为浮点数的情况下,不会将整数解组为浮点数。在这里,Mgo返回一个浮点数值,因为数据库中存储的值是浮点数。

你可以通过在结构体中指定类型来将浮点数值解组为整数:

var result struct {
  Date int64 `bson:"date"`
}
for iter.Next(&result) {
  ...
}
英文:

Mgo does not unmarshal an integer to a float unless destination value is explicitly typed as a float by the application. Mgo is returning a float value here because the value stored in the database is a float.

You can unmarshal the float value to an integer by specifying the type using a struct:

var result struct {
  Date int64 `bson:"date"`
}
for iter.Next(&result) {
  ...
}

huangapple
  • 本文由 发表于 2015年2月25日 03:12:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/28704236.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定