dongli5785 2016-09-08 07:44
浏览 272
已采纳

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

I have the following code to retrieve some data from my 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 is basically MgoSession.DB(Dbname).C(collectionName).Find(query).All(&result) giving me a []map[string]interface{}.

This gives me null, whereas in the mongo console (using the same value as returned by the currentDate variable) -

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

returns me -

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

Why is this issue coming up despite using the correct time format?

  • 写回答

1条回答 默认 最新

  • drwj4061 2016-09-08 09:03
    关注

    mgo driver seems smart enough to correctly convert time.Time to mongo Date so just

    currentDate := time.Now()
    

    should work. Also gopkg.in/mgo.v2/bson has helper to get time with millisecond precision which mongo use

    func Now() time.Time
    

    so

    currentDate := bson.Now()
    

    this helper function has simple source

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

    this way any Go timestamp time.Time can be obtained in millisecond

    someDate := time.Unix(0, time.someTime.UnixNano()/1e6*1e6)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料