How to Find and compare Dates on Official MongoDB Go Driver?

6.3k Views Asked by At

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?

2

There are 2 best solutions below

0
On

The unstable bsonx package in mongodb-go-driver has a DateTime Type. You can add the field in your struct like this:

type Email struct {
    Date bsonx.Val
}

To declare the struct use bsonx.DateTime(millis int64):

Email{
    Date: bsonx.DateTime(time.Now().UnixNano()/1e6)
}

*time.Now().UnixNano()/1e6 basically gets the unix millis.

And you can convert it to time.Time with email.Date.Time()

0
On

the Dates on my mongoDB and mapped in my struct have the values like "02/10/2018 11:55:20".

There are a number of ways you could do. The first, as mentioned on the comment, is to convert the string date 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:

{ "a": 1, "b": ISODate("2018-10-02T11:55:20Z") }

Using mongo-go-driver (current v1.2.x) you can do as below to find and compare using date:

initDate, err := time.Parse("02/01/2006 15:04:05", "01/10/2018 11:55:20")
filter := bson.D{
    {"b", bson.D{
        {"$gt", initDate},
    }},
}
cursor, err := collection.Find(context.Background(), filter)

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 string date into date then use $match stage to filter by date.

For example, given documents:

{ "a": 1, "b": "02/10/2018 11:55:20" }
{ "a": 2, "b": "04/10/2018 10:37:19" }

You can try:

// Add a new field called 'newdate' to store the converted date value
addFieldsStage := bson.D{
    {"$addFields", bson.D{
        {"newdate", bson.D{
            {"$dateFromString", bson.D{
                {"dateString", "$b"}, 
                {"format", "%d/%m/%Y %H:%M:%S"},
            }},
        }},
    }},
}

initDate, err := time.Parse("02/01/2006 15:04:05", "02/10/2018 11:55:20")

// Filter the newly added field with the date
matchStage := bson.D{
    {"$match", bson.D{
        {"newdate", bson.D{
            {"$gt", initDate},
        }},
    }},
}
pipeline := mongo.Pipeline{addFieldsStage, matchStage}

cursor, err := collection.Aggregate(context.Background(), pipeline)