在 MongoDB 中如何使用 Golang 插入日期?
时间:2024-02-23
浏览: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学习网公众号,带你了解更多关于的知识点!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.29
11.29
11.29
11.29
11.29
11.29
11.29
热门专题
