前言
在 mongodb 的集合中,时间字段(如 创建时间 和 更新时间)通常是必不可少的。在使用 go 语言操作 mongodb 时,例如执行插入或更新操作,我们需要手动设置这些时间字段的值。然而,每次手动赋值不仅繁琐,还容易导致代码重复。那么,是否可以在程序层面实现自动填充呢?目前,官方的 mongo-go-driver 并不支持自动填充时间字段,而 mongox 库提供了这一能力。本文将介绍如何使用 mongox 库,在插入和更新数据时自动填充时间字段,从而提升开发效率并减少重复代码。

时间字段填充规则
在定义结构体时,如果字段符合以下特性,则可以被自动填充:
字段名称和类型符合规定
结构体字段名为 createdat 和 updatedat 字段,且类型为 time.time 或 int/int64。当为 int/int64 时,将会填充当前时间戳秒数。
字段包含特定标签
mongox:"autocreatetime":在插入文档时,如果该字段的值为零值,则会自动设置为当前时间。除了time.time类型,你还可以使用second、milli和nano三种时间戳精度,使用样例:mongox:"autocreatetime:milli"如果不指定milli,默认是second。mongox:"autoupdatetime":在插入文档时,如果该字段的值为零值或更新文档时,会自动设置为当前时间。除了time.time类型,你还可以使用second、milli和nano三种时间戳精度。使用样例:mongox:"autoupdatetime:milli"如果不指定milli,默认是second。
mongox 的安装
通过以下命令安装 mongox 库:
go get github.com/chenmingyong0423/go-mongox/v2
使用 mongox 进行插入操作
结构体定义
type user struct {
id bson.objectid `bson:"_id,omitempty" mongox:"autoid"`
name string `bson:"name"`
age int `bson:"age"`
createdat time.time `bson:"created_at"`
updatedat int `bson:"updated_at"` // 使用秒级时间戳填充字段
createsecondtime int64 `bson:"create_second_time" mongox:"autocreatetime"` // 使用秒级时间戳填充字段
updatesecondtime int64 `bson:"update_second_time" mongox:"autoupdatetime:second"` // 使用秒级时间戳填充字段
createmillitime int64 `bson:"create_milli_time" mongox:"autocreatetime:milli"` // 使用毫秒级时间戳填充字段
updatemillitime int64 `bson:"update_milli_time" mongox:"autoupdatetime:milli"` // 使用毫秒级时间戳填充字段
createnanotime int64 `bson:"create_nano_time" mongox:"autocreatetime:nano"` // 使用纳秒级时间戳填充字段
updatenanotime int64 `bson:"update_nano_time" mongox:"autoupdatetime:nano"` // 使用纳秒级时间戳填充字段
}
示例代码
package main
import (
"context"
"fmt"
"time"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
"go.mongodb.org/mongo-driver/v2/mongo/readpref"
"github.com/chenmingyong0423/go-mongox/v2"
)
type user struct {
id bson.objectid `bson:"_id,omitempty" mongox:"autoid"`
name string `bson:"name"`
age int `bson:"age"`
createdat time.time `bson:"created_at"`
updatedat int `bson:"updated_at"` // 使用秒级时间戳填充字段
createsecondtime int64 `bson:"create_second_time" mongox:"autocreatetime"` // 使用秒级时间戳填充字段
updatesecondtime int64 `bson:"update_second_time" mongox:"autoupdatetime:second"` // 使用秒级时间戳填充字段
createmillitime int64 `bson:"create_milli_time" mongox:"autocreatetime:milli"` // 使用毫秒级时间戳填充字段
updatemillitime int64 `bson:"update_milli_time" mongox:"autoupdatetime:milli"` // 使用毫秒级时间戳填充字段
createnanotime int64 `bson:"create_nano_time" mongox:"autocreatetime:nano"` // 使用纳秒级时间戳填充字段
updatenanotime int64 `bson:"update_nano_time" mongox:"autoupdatetime:nano"` // 使用纳秒级时间戳填充字段
}
func main() {
mongoclient, err := newmongoclient()
if err != nil {
panic(err)
}
client := mongox.newclient(mongoclient, &mongox.config{})
database := client.newdatabase("db-test")
usercoll := mongox.newcollection[user](database, "users")
user := &user{
name: "陈明勇",
age: 18,
}
_, err = usercoll.creator().insertone(context.background(), user)
if err != nil {
panic(err)
}
fmt.println(!user.createdat.iszero()) // true
fmt.println(user.updatedat != 0) // true
fmt.println(user.createsecondtime != 0) // true
fmt.println(user.updatesecondtime != 0) // true
fmt.println(user.createmillitime != 0) // true
fmt.println(user.updatemillitime != 0) // true
fmt.println(user.createnanotime != 0) // true
fmt.println(user.updatenanotime != 0) // true
}
// 示例代码,仅供参考
func newmongoclient() (*mongo.client, error) {
client, err := mongo.connect(options.client().applyuri("mongodb://localhost:27017").setauth(options.credential{
username: "test",
password: "test",
authsource: "db-test",
}))
if err != nil {
return nil, err
}
err = client.ping(context.background(), readpref.primary())
if err != nil {
panic(err)
}
return client, nil
}插入数据后,通过零值比较判断字段值是否被填充。fmt.println 语句都输出 true,说明所有时间字段的值都被填充。
使用 mongox 进行更新操作
更新操作
package main
import (
"context"
"fmt"
"time"
"github.com/chenmingyong0423/go-mongox/v2/builder/query"
"github.com/chenmingyong0423/go-mongox/v2/builder/update"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
"go.mongodb.org/mongo-driver/v2/mongo/readpref"
"github.com/chenmingyong0423/go-mongox/v2"
)
type user struct {
id bson.objectid `bson:"_id,omitempty" mongox:"autoid"`
name string `bson:"name"`
age int `bson:"age"`
createdat time.time `bson:"created_at"`
updatedat int `bson:"updated_at"` // 使用秒级时间戳填充字段
createsecondtime int64 `bson:"create_second_time" mongox:"autocreatetime"` // 使用秒级时间戳填充字段
updatesecondtime int64 `bson:"update_second_time" mongox:"autoupdatetime:second"` // 使用秒级时间戳填充字段
createmillitime int64 `bson:"create_milli_time" mongox:"autocreatetime:milli"` // 使用毫秒级时间戳填充字段
updatemillitime int64 `bson:"update_milli_time" mongox:"autoupdatetime:milli"` // 使用毫秒级时间戳填充字段
createnanotime int64 `bson:"create_nano_time" mongox:"autocreatetime:nano"` // 使用纳秒级时间戳填充字段
updatenanotime int64 `bson:"update_nano_time" mongox:"autoupdatetime:nano"` // 使用纳秒级时间戳填充字段
}
func main() {
mongoclient, err := newmongoclient()
if err != nil {
panic(err)
}
client := mongox.newclient(mongoclient, &mongox.config{})
database := client.newdatabase("db-test")
usercoll := mongox.newcollection[user](database, "users")
// 用于比较后面的时间字段是否更新
now := time.now()
_, err = usercoll.updater().
filter(query.eq("name", "陈明勇")).
updates(update.set("age", 26)).
updateone(context.background())
if err != nil {
panic(err)
}
user, err := usercoll.finder().
filter(query.eq("name", "陈明勇")).
findone(context.background())
if err != nil {
panic(err)
}
fmt.println(user.updatedat > int(now.unix())) // true
fmt.println(user.updatesecondtime > now.unix()) // true
fmt.println(user.updatemillitime > now.unix()) // true
fmt.println(user.updatenanotime > now.unix()) // true
}
// 示例代码,仅供参考
func newmongoclient() (*mongo.client, error) {
client, err := mongo.connect(options.client().applyuri("mongodb://localhost:27017").setauth(options.credential{
username: "test",
password: "test",
authsource: "db-test",
}))
if err != nil {
return nil, err
}
err = client.ping(context.background(), readpref.primary())
if err != nil {
panic(err)
}
return client, nil
}updates 参数无需指定时间字段,也能自动填充。更新数据后,通过与 now 进行比较判断字段值是否被填充。fmt.println 语句都输出 true,说明更新时间字段的值都已更新。
upsert 操作
package main
import (
"context"
"fmt"
"time"
"github.com/chenmingyong0423/go-mongox/v2/builder/query"
"github.com/chenmingyong0423/go-mongox/v2/builder/update"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
"go.mongodb.org/mongo-driver/v2/mongo/readpref"
"github.com/chenmingyong0423/go-mongox/v2"
)
type user struct {
id bson.objectid `bson:"_id,omitempty" mongox:"autoid"`
name string `bson:"name"`
age int `bson:"age"`
createdat time.time `bson:"created_at"`
updatedat int `bson:"updated_at"` // 使用秒级时间戳填充字段
createsecondtime int64 `bson:"create_second_time" mongox:"autocreatetime"` // 使用秒级时间戳填充字段
updatesecondtime int64 `bson:"update_second_time" mongox:"autoupdatetime:second"` // 使用秒级时间戳填充字段
createmillitime int64 `bson:"create_milli_time" mongox:"autocreatetime:milli"` // 使用毫秒级时间戳填充字段
updatemillitime int64 `bson:"update_milli_time" mongox:"autoupdatetime:milli"` // 使用毫秒级时间戳填充字段
createnanotime int64 `bson:"create_nano_time" mongox:"autocreatetime:nano"` // 使用纳秒级时间戳填充字段
updatenanotime int64 `bson:"update_nano_time" mongox:"autoupdatetime:nano"` // 使用纳秒级时间戳填充字段
}
func main() {
mongoclient, err := newmongoclient()
if err != nil {
panic(err)
}
client := mongox.newclient(mongoclient, &mongox.config{})
database := client.newdatabase("db-test")
usercoll := mongox.newcollection[user](database, "users")
_, err = usercoll.updater().
filter(query.eq("name", "mingyong chen")).
updates(update.set("age", 18)).
upsert(context.background())
if err != nil {
panic(err)
}
user, err := usercoll.finder().
filter(query.eq("name", "mingyong chen")).
findone(context.background())
if err != nil {
panic(err)
}
fmt.println(!user.createdat.iszero()) // true
fmt.println(user.updatedat != 0) // true
fmt.println(user.createsecondtime != 0) // true
fmt.println(user.updatesecondtime != 0) // true
fmt.println(user.createmillitime != 0) // true
fmt.println(user.updatemillitime != 0) // true
fmt.println(user.createnanotime != 0) // true
fmt.println(user.updatenanotime != 0) // true
}
// 示例代码,仅供参考
func newmongoclient() (*mongo.client, error) {
client, err := mongo.connect(options.client().applyuri("mongodb://localhost:27017").setauth(options.credential{
username: "test",
password: "test",
authsource: "db-test",
}))
if err != nil {
return nil, err
}
err = client.ping(context.background(), readpref.primary())
if err != nil {
panic(err)
}
return client, nil
}当触发 upsert 操作时,无需指定字段,创建时间和更新时间字段都会被填充。fmt.println 语句都输出 true,说明所有时间字段的值都被填充。
小结
本文详细介绍了如何使用 mongox 库,在插入和更新数据时自动填充时间字段。在定义结构体时,只要满足 字段名称和类型符合规定 和 字段包含特定标签,mongox 将会自动填充时间字段的值。
到此这篇关于go mongox轻松实现mongodb的时间字段自动填充的文章就介绍到这了,更多相关go mongox使用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论