由于缺少 'ISODate',Golang + mgo 查询 mongodb 在使用时间时失败

Golang + mgo querying mongodb fails when using time because of missing 'ISODate'

我有以下代码可以从我的 mongodb -

中检索一些数据
currentDate := time.Now().Format(time.RFC3339)
content := database.FindDocuments("content", bson.M{ "$and": []bson.M{ bson.M{"start_date": bson.M{"$lte": currentDate}}, bson.M{"end_date": bson.M{ "$gte": currentDate}}, }})

FindDocuments 基本上是 MgoSession.DB(Dbname).C(collectionName).Find(query).All(&result) 给我 []map[string]interface{}.

这给了我 null,而在 mongo 控制台中(使用与 currentDate 变量返回的相同的值)-

{ "start_date": { $lt: ISODate("2016-09-08T13:05:24+05:30") }, $and: [ { "end_date": { $gt: ISODate("2016-09-08T13:05:24+05:30") } } ] }

returns我-

{ 
    "_id" : ObjectId("57cff2bc32291a1fa0e79e90"), 
    "image_url" : "www.example.com", 
    "title" : "This is a new content", 
    "start_date" : ISODate("2016-09-06T10:58:54.701+0000"), 
    "end_date" : ISODate("2016-09-10T10:59:04.447+0000"), 
    "type" : "content"
}

尽管使用了正确的时间格式,为什么还是会出现这个问题?

mgo 驱动程序似乎足够聪明,可以正确地将 time.Time 转换为 mongo 日期,所以

currentDate := time.Now()

应该可以。 gopkg.in/mgo.v2/bson 也有助手以毫秒精度获取时间,mongo 使用

func Now() time.Time

所以

currentDate := bson.Now()

这个辅助函数的源码很简单

return time.Unix(0, time.Now().UnixNano()/1e6*1e6)

这样可以在毫秒内得到任何Go时间戳time.Time

someDate := time.Unix(0, time.someTime.UnixNano()/1e6*1e6)