I am new to mongodb-go-driver and i am stuck.
I have a date inside a struct like:
type Email struct {
Date string `json:"date"`
}
the Dates on my mongoDB and mapped in my struct have the values like "02/10/2018 11:55:20".
I want to find on my DB the elements that Date are after an other date, i'm trying this but the response is always null.
initDate, _ := time.Parse("02012006", initialDate)
cursor, err := emails.Find(context.Background(), bson.NewDocument(bson.EC.SubDocumentFromElements("date", bson.EC.DateTime("$gt", initDate.Unix()))))
what am i doing wrong?
There are a number of ways you could do. The first, as mentioned on the comment, is to convert the
stringdate into an actual date format. See also MongoDB Date. Storing date values in the proper date format is the recommended way for performance.If you have a document:
Using mongo-go-driver (current v1.2.x) you can do as below to find and compare using date:
Please note the layout value in the example above for
time.Parse(). It needs to match the string layout/format.An alternative way, without converting the value is to use MongoDB Aggregation Pipeline. You can use $dateFromString operator to convert the
stringdate into date then use $match stage to filter by date.For example, given documents:
You can try: