Document not able to fetch from mongodb through golang because of date format issue. Using mgm package for it

40 Views Asked by At

In our document collection, appnt_date is in date type format and to fetch the documents on the basis of the given appnt_date, we need to provide the query in mongo db compass as:

{
  "appnt_date": {
    "$eq": ISODate("2024-01-25T00:00:00.000Z")
  }
}

The above query is fetching the results correctly in Mongo db compass.

Now in order to fetch the document from golang code on the basis of the given appnt_date which is in time.Time type in golang, I am not able to fetch document from mongo on the basis of date.

Need help on this. I tried various methods like:

1)

targetDate := time.Date(2024, 1, 25, 0, 0, 0, 0, time.UTC)
   targetDateTime := primitive.NewDateTimeFromTime(targetDate)
filter := bson.M{
            "appnt_date":  targetDateTime}
  1. targetDate := time.Date(2024, 1, 25, 0, 0, 0, 0, time.UTC)

    formattedDate := targetDate.Format("2006-01-02T15:04:05.000Z")

    filter := bson.M{ "appnt_date": formattedDate}

But none of them worked. appnt_date in mongo is in the format: appnt_date: 2024-01-25T00:00:00.000+00:00

1

There are 1 best solutions below

0
ABDULLOKH MUKHAMMADJONOV On

You can use time.Parse() to convert a string date to golang's time.Time. Example:

// using RFC3339 time layout
targetDateTime, err := time.Parse(time.RFC3339, "2024-01-25T00:00:00.000+00:00")
if err != nil {
  ... handle error
}

...

filter := bson.M{"appnt_date":  targetDateTime}