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

相关文章

Spring Shell 命令行实现交互式Shell应用开发

《SpringShell命令行实现交互式Shell应用开发》本文主要介绍了SpringShell命令行实现交互式Shell应用开发,能够帮助开发者快速构建功能丰富的命令行应用程序,具有一定的参考价... 目录引言一、Spring Shell概述二、创建命令类三、命令参数处理四、命令分组与帮助系统五、自定义S

SpringBatch数据写入实现

《SpringBatch数据写入实现》SpringBatch通过ItemWriter接口及其丰富的实现,提供了强大的数据写入能力,本文主要介绍了SpringBatch数据写入实现,具有一定的参考价值,... 目录python引言一、ItemWriter核心概念二、数据库写入实现三、文件写入实现四、多目标写入

Android Studio 配置国内镜像源的实现步骤

《AndroidStudio配置国内镜像源的实现步骤》本文主要介绍了AndroidStudio配置国内镜像源的实现步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,... 目录一、修改 hosts,解决 SDK 下载失败的问题二、修改 gradle 地址,解决 gradle

SpringSecurity JWT基于令牌的无状态认证实现

《SpringSecurityJWT基于令牌的无状态认证实现》SpringSecurity中实现基于JWT的无状态认证是一种常见的做法,本文就来介绍一下SpringSecurityJWT基于令牌的无... 目录引言一、JWT基本原理与结构二、Spring Security JWT依赖配置三、JWT令牌生成与

Java中Date、LocalDate、LocalDateTime、LocalTime、时间戳之间的相互转换代码

《Java中Date、LocalDate、LocalDateTime、LocalTime、时间戳之间的相互转换代码》:本文主要介绍Java中日期时间转换的多种方法,包括将Date转换为LocalD... 目录一、Date转LocalDateTime二、Date转LocalDate三、LocalDateTim

Go 语言中的select语句详解及工作原理

《Go语言中的select语句详解及工作原理》在Go语言中,select语句是用于处理多个通道(channel)操作的一种控制结构,它类似于switch语句,本文给大家介绍Go语言中的select语... 目录Go 语言中的 select 是做什么的基本功能语法工作原理示例示例 1:监听多个通道示例 2:带

SpringBoot实现微信小程序支付功能

《SpringBoot实现微信小程序支付功能》小程序支付功能已成为众多应用的核心需求之一,本文主要介绍了SpringBoot实现微信小程序支付功能,文中通过示例代码介绍的非常详细,对大家的学习或者工作... 目录一、引言二、准备工作(一)微信支付商户平台配置(二)Spring Boot项目搭建(三)配置文件

基于Python实现高效PPT转图片工具

《基于Python实现高效PPT转图片工具》在日常工作中,PPT是我们常用的演示工具,但有时候我们需要将PPT的内容提取为图片格式以便于展示或保存,所以本文将用Python实现PPT转PNG工具,希望... 目录1. 概述2. 功能使用2.1 安装依赖2.2 使用步骤2.3 代码实现2.4 GUI界面3.效

MySQL更新某个字段拼接固定字符串的实现

《MySQL更新某个字段拼接固定字符串的实现》在MySQL中,我们经常需要对数据库中的某个字段进行更新操作,本文就来介绍一下MySQL更新某个字段拼接固定字符串的实现,感兴趣的可以了解一下... 目录1. 查看字段当前值2. 更新字段拼接固定字符串3. 验证更新结果mysql更新某个字段拼接固定字符串 -

java实现延迟/超时/定时问题

《java实现延迟/超时/定时问题》:本文主要介绍java实现延迟/超时/定时问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java实现延迟/超时/定时java 每间隔5秒执行一次,一共执行5次然后结束scheduleAtFixedRate 和 schedu