Go Mongox轻松实现MongoDB的时间字段自动填充

2025-02-12 05:50

本文主要是介绍Go Mongox轻松实现MongoDB的时间字段自动填充,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《GoMongox轻松实现MongoDB的时间字段自动填充》这篇文章主要为大家详细介绍了Go语言如何使用mongox库,在插入和更新数据时自动填充时间字段,从而提升开发效率并减少重复代码,需要的可以...

前言

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

Go Mongox轻松实现MongoDB的时间字段自动填充

时间字段填充规则

在定义结构体时,如果字段符合以下特性,则可以被自动填充:

字段名称和类型符合规定

结构体字段名为 CreatedAtUpdatedAt 字段,且类型为 time.Timeint/int64。当为 int/int64 时,将会填充当前时间戳秒数。

字段包含特定标签

  • mongox:"autoCreateTime":在插入文档时,如果该字段的值为零值,则会自动设置为当前时间。除了 time.Time 类型,你还可以使用 secondmillinano 三种时间戳精度,使用样例:mongox:"autoCreateTime:milli" 如果不指定 milli,默认是 second
  • mongox:"autoUpdateTime":在插入文档时,如果该字段的值为零值或更新文档时,会自动设置为当前时间。除了 time.Time 类型,你还可以使用 secondmillinano 三种时间戳精度。使用样例: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" mongoxpython:"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"`   // 使用毫秒级时间戳填充字段
 php   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 {
 android       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)  js // true
    fmt.Println(user.UpdateNanoTime != 0)   // true
}

// 示例代码,仅供参考
func newMongoClient() (*mongo.Client, error) {
    client, err := mongo.Connect(options.Client().ApplyURI("mongodb://localhost:27017").SetAuth(optionwww.chinasem.cns.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使用内容请搜索China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程China编程(www.chinasem.cn)!

这篇关于Go Mongox轻松实现MongoDB的时间字段自动填充的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1153410

相关文章

pandas中位数填充空值的实现示例

《pandas中位数填充空值的实现示例》中位数填充是一种简单而有效的方法,用于填充数据集中缺失的值,本文就来介绍一下pandas中位数填充空值的实现,具有一定的参考价值,感兴趣的可以了解一下... 目录什么是中位数填充?为什么选择中位数填充?示例数据结果分析完整代码总结在数据分析和机器学习过程中,处理缺失数

Golang HashMap实现原理解析

《GolangHashMap实现原理解析》HashMap是一种基于哈希表实现的键值对存储结构,它通过哈希函数将键映射到数组的索引位置,支持高效的插入、查找和删除操作,:本文主要介绍GolangH... 目录HashMap是一种基于哈希表实现的键值对存储结构,它通过哈希函数将键映射到数组的索引位置,支持

Pandas使用AdaBoost进行分类的实现

《Pandas使用AdaBoost进行分类的实现》Pandas和AdaBoost分类算法,可以高效地进行数据预处理和分类任务,本文主要介绍了Pandas使用AdaBoost进行分类的实现,具有一定的参... 目录什么是 AdaBoost?使用 AdaBoost 的步骤安装必要的库步骤一:数据准备步骤二:模型

使用Pandas进行均值填充的实现

《使用Pandas进行均值填充的实现》缺失数据(NaN值)是一个常见的问题,我们可以通过多种方法来处理缺失数据,其中一种常用的方法是均值填充,本文主要介绍了使用Pandas进行均值填充的实现,感兴趣的... 目录什么是均值填充?为什么选择均值填充?均值填充的步骤实际代码示例总结在数据分析和处理过程中,缺失数

Java对象转换的实现方式汇总

《Java对象转换的实现方式汇总》:本文主要介绍Java对象转换的多种实现方式,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录Java对象转换的多种实现方式1. 手动映射(Manual Mapping)2. Builder模式3. 工具类辅助映

Go语言开发实现查询IP信息的MCP服务器

《Go语言开发实现查询IP信息的MCP服务器》随着MCP的快速普及和广泛应用,MCP服务器也层出不穷,本文将详细介绍如何在Go语言中使用go-mcp库来开发一个查询IP信息的MCP... 目录前言mcp-ip-geo 服务器目录结构说明查询 IP 信息功能实现工具实现工具管理查询单个 IP 信息工具的实现服

Python的time模块一些常用功能(各种与时间相关的函数)

《Python的time模块一些常用功能(各种与时间相关的函数)》Python的time模块提供了各种与时间相关的函数,包括获取当前时间、处理时间间隔、执行时间测量等,:本文主要介绍Python的... 目录1. 获取当前时间2. 时间格式化3. 延时执行4. 时间戳运算5. 计算代码执行时间6. 转换为指

SpringBoot基于配置实现短信服务策略的动态切换

《SpringBoot基于配置实现短信服务策略的动态切换》这篇文章主要为大家详细介绍了SpringBoot在接入多个短信服务商(如阿里云、腾讯云、华为云)后,如何根据配置或环境切换使用不同的服务商,需... 目录目标功能示例配置(application.yml)配置类绑定短信发送策略接口示例:阿里云 & 腾

关于MongoDB图片URL存储异常问题以及解决

《关于MongoDB图片URL存储异常问题以及解决》:本文主要介绍关于MongoDB图片URL存储异常问题以及解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录MongoDB图片URL存储异常问题项目场景问题描述原因分析解决方案预防措施js总结MongoDB图

Java中字符串转时间与时间转字符串的操作详解

《Java中字符串转时间与时间转字符串的操作详解》Java的java.time包提供了强大的日期和时间处理功能,通过DateTimeFormatter可以轻松地在日期时间对象和字符串之间进行转换,下面... 目录一、字符串转时间(一)使用预定义格式(二)自定义格式二、时间转字符串(一)使用预定义格式(二)自