Golang/mgo:如何在mongodb中存储日期(而不是ISODate)?
如果我这样存储当前时间:Golang/mgo:如何在mongodb中存储日期(而不是ISODate)?,mongodb,go,mgo,isodate,Mongodb,Go,Mgo,Isodate,如果我这样存储当前时间: type Test struct { Id string `bson:"id" json:"id,omitempty"` TestTime time.Time `bson:"testTime" json:"testTime,omitempty"` } ... t := Test { Id : "TEST0001", TestTime : time.Now(), } ... c.Insert(t) 然后我使用mongochef搜索它:
type Test struct {
Id string `bson:"id" json:"id,omitempty"`
TestTime time.Time `bson:"testTime" json:"testTime,omitempty"`
}
...
t := Test {
Id : "TEST0001",
TestTime : time.Now(),
}
...
c.Insert(t)
然后我使用mongochef搜索它:
{
"_id" : ObjectId("576bc7a48114a14b47920d60"),
"id" : "TEST0001",
"testTime" : ISODate("2016-06-23T11:27:30.447+0000")
}
因此,mgo默认存储ISODate,如何存储日期而不是ISODate?mgo自动将
time.time
转换为Mongo内部日期数据类型(,实际上它只是一个没有时区信息的时间戳,并且总是更正为UTC)。任何其他功能都必须由您手动实现
通过实现包中的和接口,您可以强制mgo正确(反)序列化您的类型。
mgo/bson
认为这是非常低级的,所以要小心。您应该定义一个自定义结构,以保存时区
您可以定义一个自定义解组
,用于更改加载日期的位置
func (t *TimeWithTimezone) Unmarshal(in []byte, out interface{}) (err error) {
type decode TimeWithTimezone
var d decode
if err := bson.NewDecoder(in).Decode(&d); err != nil {
return err
}
loc, err := FixedZone(d.Timezone, d.Timezone)
if err != nil {
return fmt.Errorf("Invalid Timezone: %s", d.Timezone)
}
t.Time = d.Time.In(loc)
t.Timezone = d.Timezone
return nil
}
像这样的东西应该可以做到,它不是经过测试的,只是给你一个想法