英文:
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") } } ] }
返回了 -
{
"_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"
}
为什么尽管使用了正确的时间格式,这个问题还会出现?
英文:
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
得分: 2
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)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论