登录
首页 >  Golang >  Go问答

在 MongoDB 中如何使用 Golang 插入日期?

来源:stackoverflow

时间:2024-02-23 14:45:20 250浏览 收藏

一分耕耘,一分收获!既然打开了这篇文章《在 MongoDB 中如何使用 Golang 插入日期?》,就坚持看下去吧!文中内容包含等等知识点...希望你能在阅读本文后,能真真实实学到知识或者帮你解决心中的疑惑,也欢迎大佬或者新人朋友们多留言评论,多给建议!谢谢!

问题内容

我有一个具有以下格式的结构。我正在尝试将 invdt 作为日期插入 mongodb 中。我的日期格式为 2020-09-25

type statement struct {
  invdt string `bson:"invoice_date,omitempty" json:"invoice_date,omitempty"`
}

插入代码写为:

interfaceStmts := []interface{}{}
for _, s := range stmts {
    interfaceStmts = append(interfaceStmts, s)
}
testCollection.InsertMany(ctx, interfaceStmts)

当前正在作为字符串插入。如何将其作为日期插入?


解决方案


实现方法是首先将 string 转换为 time.time 类型,然后使用 primitive 库中的转换器将其转换为 datetime 对象。

import (
    "time"
    "go.mongodb.org/mongo-driver/bson/primitive"
)

type Statement struct {
  InvDt primitive.DateTime `bson:"invoice_date,omitempty" json:"invoice_date,omitempty"`
}

func main() {
    const shortForm =  "2006-01-02"
    dt, _ := time.Parse(shortForm, "2020-09-29")
    stmt.InvDt = primitive.NewDateTimeFromTime(dt)
}

到这里,我们也就讲完了《在 MongoDB 中如何使用 Golang 插入日期?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>