【问题标题】:Golang + mgo querying mongodb fails when using time because of missing 'ISODate'由于缺少“ISODate”,Golang + mgo 在使用时间时查询 mongodb 失败
【发布时间】:2017-01-16 01:14:19
【问题描述】:

我有以下代码可以从我的 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") } } ] }

返回我 -

{ 
    "_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"
}

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

【问题讨论】:

  • 我也有同样的问题...

标签: mongodb go time mgo gorilla


【解决方案1】:

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

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)

【讨论】:

  • 嗨!这与没有正确获取日期无关。在 mongo 控制台查询中,我刚刚复制粘贴了从我的程序控制台看到的 currentDate 返回的值。使用这个的时候,返回的时间值是1473326105000,响应还是null。
  • 是否 { "start_date": { $lt: 1473326105000 }, $and: [ { "end_date": { $gt: 1473326105000 } } ] } 在控制台中工作?也许 mongo 文档的毫秒数不正确。 currentDate := time.Now().Unix() 或在控制台中怎么样 { "start_date": { $lt: 1473326105 }, $and: [ { "end_date": { $gt: 1473326105 } } ] }
  • 这两个都在 mongo 控制台上返回 null :(
  • @GauravOjha 经过深入调查完全重写答案。很抱歉给您带来不便。
  • 谢谢!我发现只有 Time.Now() 有效!是不是很神奇又令人沮丧?!
猜你喜欢
  • 2016-02-09
  • 1970-01-01
  • 1970-01-01
  • 2016-02-13
  • 2023-02-01
  • 1970-01-01
  • 2017-02-06
  • 2020-11-28
  • 1970-01-01
相关资源
最近更新 更多