package main import ( "fmt" "go.mongodb.org/mongo-driver/mongo" "context" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/bson/primitive" "time" ) // 任务的执行时间点 type TimePoint struct { StartTime int64 `bson:"startTime"` EndTime int64 `bson:"endTime"` } // 一条日志 type LogRecord struct { JobName string `bson:"jobName"` // 任务名 Command string `bson:"command"` // shell命令 Err string `bson:"err"` // 脚本错误 Content string `bson:"content"`// 脚本输出 TimePoint TimePoint `bson:"timePoint"`// 执行时间点 } func main(){ var ( client *mongo.Client err error result *mongo.InsertOneResult ) // 建立mongodb连接 clientOptions := options.Client().ApplyURI("mongodb://ichunt:huntmon6699@192.168.1.237:27017/ichunt?authMechanism=SCRAM-SHA-1") if client, err = mongo.Connect( context.TODO(),clientOptions); err != nil { return } // 2, 选择数据库my_db database := client.Database("ichunt") // 3, 选择表my_collection collection := database.Collection("cron_log") // 4, 插入记录(bson) record := &LogRecord{ JobName: "job10", Command: "echo hello", Err: "", Content: "hello", TimePoint: TimePoint{StartTime: time.Now().Unix(), EndTime: time.Now().Unix() + 10}, } if result, err = collection.InsertOne(context.TODO(), record); err != nil { fmt.Println(err) return } fmt.Println(result) //// _id: 默认生成一个全局唯一ID, ObjectID:12字节的二进制 docId := result.InsertedID.(primitive.ObjectID) fmt.Println("自增ID:", docId.Hex()) }
返回:
&{ObjectID("5e158ad09a14bfe14880829b")} 自增ID: 5e158ad09a14bfe14880829b
本文来自博客园,作者:孙龙-程序员,转载请注明原文链接:https://www.cnblogs.com/sunlong88/p/12167094.html
分类:
golang
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示