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?
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)