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

相关文章

C语言实现两个变量值交换的三种方式

《C语言实现两个变量值交换的三种方式》两个变量值的交换是编程中最常见的问题之一,以下将介绍三种变量的交换方式,其中第一种方式是最常用也是最实用的,后两种方式一般只在特殊限制下使用,需要的朋友可以参考下... 目录1.使用临时变量(推荐)2.相加和相减的方式(值较大时可能丢失数据)3.按位异或运算1.使用临时

java streamfilter list 过滤的实现

《javastreamfilterlist过滤的实现》JavaStreamAPI中的filter方法是过滤List集合中元素的一个强大工具,可以轻松地根据自定义条件筛选出符合要求的元素,本文就来... 目录1. 创建一个示例List2. 使用Stream的filter方法进行过滤3. 自定义过滤条件1. 定

使用C语言实现交换整数的奇数位和偶数位

《使用C语言实现交换整数的奇数位和偶数位》在C语言中,要交换一个整数的二进制位中的奇数位和偶数位,重点需要理解位操作,当我们谈论二进制位的奇数位和偶数位时,我们是指从右到左数的位置,本文给大家介绍了使... 目录一、问题描述二、解决思路三、函数实现四、宏实现五、总结一、问题描述使用C语言代码实现:将一个整

如何使用Python实现一个简单的window任务管理器

《如何使用Python实现一个简单的window任务管理器》这篇文章主要为大家详细介绍了如何使用Python实现一个简单的window任务管理器,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起... 任务管理器效果图完整代码import tkinter as tkfrom tkinter i

redis+lua实现分布式限流的示例

《redis+lua实现分布式限流的示例》本文主要介绍了redis+lua实现分布式限流的示例,可以实现复杂的限流逻辑,如滑动窗口限流,并且避免了多步操作导致的并发问题,具有一定的参考价值,感兴趣的可... 目录为什么使用Redis+Lua实现分布式限流使用ZSET也可以实现限流,为什么选择lua的方式实现

使用PyTorch实现手写数字识别功能

《使用PyTorch实现手写数字识别功能》在人工智能的世界里,计算机视觉是最具魅力的领域之一,通过PyTorch这一强大的深度学习框架,我们将在经典的MNIST数据集上,见证一个神经网络从零开始学会识... 目录当计算机学会“看”数字搭建开发环境MNIST数据集解析1. 认识手写数字数据库2. 数据预处理的

Redis中管道操作pipeline的实现

《Redis中管道操作pipeline的实现》RedisPipeline是一种优化客户端与服务器通信的技术,通过批量发送和接收命令减少网络往返次数,提高命令执行效率,本文就来介绍一下Redis中管道操... 目录什么是pipeline场景一:我要向Redis新增大批量的数据分批处理事务( MULTI/EXE

Python实现常用文本内容提取

《Python实现常用文本内容提取》在日常工作和学习中,我们经常需要从PDF、Word文档中提取文本,本文将介绍如何使用Python编写一个文本内容提取工具,有需要的小伙伴可以参考下... 目录一、引言二、文本内容提取的原理三、文本内容提取的设计四、文本内容提取的实现五、完整代码示例一、引言在日常工作和学

Python实战之屏幕录制功能的实现

《Python实战之屏幕录制功能的实现》屏幕录制,即屏幕捕获,是指将计算机屏幕上的活动记录下来,生成视频文件,本文主要为大家介绍了如何使用Python实现这一功能,希望对大家有所帮助... 目录屏幕录制原理图像捕获音频捕获编码压缩输出保存完整的屏幕录制工具高级功能实时预览增加水印多平台支持屏幕录制原理屏幕

SpringBoot3使用Jasypt实现加密配置文件

《SpringBoot3使用Jasypt实现加密配置文件》这篇文章主要为大家详细介绍了SpringBoot3如何使用Jasypt实现加密配置文件功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编... 目录一. 使用步骤1. 添加依赖2.配置加密密码3. 加密敏感信息4. 将加密信息存储到配置文件中5