Go 操作mongodb
前言
参考地址:https://juejin.cn/post/6908063164726771719
最近学习在go中操作mongodb,了解到主要有第三方mgo和官方mongo-driver两个库使用最多。mgo已经停止维护了,因此选择了mongo-driver。本文记录一些常用的代码操作笔记,以备随时查阅。
安装
# 初始化go模块,取名为mongo-notes mkdir goMongo && cd goMongo go mod init mongo-notes # 获取go mongo模块依赖 go get go.mongodb.org/mongo-driver/mongo
项目结构
package gmongo // go mongo 文档 https://juejin.cn/post/6908063164726771719 import ( "context" "fmt" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "log" ) var client *mongo.Client var collection *mongo.Collection var ctx = context.TODO() func Connect() *mongo.Client { clientOptions := options.Client().ApplyURI("mongodb://localhost:27017") client, err := mongo.Connect(ctx, clientOptions) if err != nil { log.Fatal(err) } err = client.Ping(ctx, nil) if err != nil { log.Fatal(err) } fmt.Println("Connected to MongoDB!") return client }