由于日期格式问题,无法通过 golang 从 mongodb 获取文档。使用 mgm 包

问题描述 投票:0回答:1

在我们的文档集合中,appnt_date 是日期类型格式,要根据给定的 appnt_date 获取文档,我们需要在 mongo db compass 中提供查询,如下所示:

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

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

现在,为了根据给定的 appnt_date 从 golang 代码中获取文档(golang 中的 time.Time 类型),我无法根据日期从 mongo 中获取文档。

需要帮助。我尝试了各种方法,例如:

1)

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

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

    过滤器 := bson.M{ “appnt_date”:格式化日期}

但它们都不起作用。 mongo 中的 appnt_date 格式为:

appnt_date: 2024-01-25T00:00:00.000+00:00

mongodb go mongodb-query go-fiber
1个回答
0
投票

您可以使用

time.Parse()
将字符串日期转换为 golang 的
time.Time
。示例:

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}
© www.soinside.com 2019 - 2024. All rights reserved.