go操作mongodb

go操作mongodb

依赖

go get go.mongodb.org/mongo-driver/mongo

实例

package daily

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var (
	MongoClient *mongo.Client
)


/*
*
go mongodb
1. 下载依赖:go get go.mongodb.org/mongo-driver/mongo
2. 参考文档: https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo
*/
func initMongoDB() error {
	var err error
	uri := "mongodb://localhost:27017"
	//uri := "mongodb://username:password@localhost:27017"
	clientOptions := options.Client().ApplyURI(uri)             // 客户端配置
	client, err := mongo.Connect(context.TODO(), clientOptions) // 建立连接
	if err != nil {
		return err
	}
	if err = client.Ping(context.TODO(), nil); err != nil { // 连接是否可用
		return err
	}
	MongoClient = client
	return err
}

func MongodbOp() {
	/**
	mongodb操作
	1. 下载依赖: go get go.mongodb.org/mongo-driver/mongo
	PS:
		context上下文扩展阅读
		https://juejin.cn/post/7233981178101186619
	*/
	type myUser struct {
		Name string `bson:"Name"`
		Age  uint   `bson:"Age"`
    } // 字段需要大写(重要)
	// 1. 初始化
	err := initMongoDB()
	if err != nil {
		fmt.Println("mongoDB连接失败=" + err.Error())
		return
	} else {
		fmt.Println("mongoDB连接成功")
	}

	// 2.1 单个新增
	collection := MongoClient.Database("go_db").Collection("user")
	ms := myUser{Name: "xyz", Age: 10}
	one, err := collection.InsertOne(context.TODO(), ms)
	//one, err := collection.InsertOne(context.TODO(), bson.M{"a": 1})
	if err != nil {
		fmt.Println("单个新增失败=" + err.Error())
		return
	}
	fmt.Println("单个新增成功id=", one.InsertedID)

	// 2. 批量新增
	msl := []interface{}{
		myUser{Name: "x1", Age: 11},
		myUser{Name: "x2", Age: 12},
	}
	many, err := collection.InsertMany(context.TODO(), msl)
	if err != nil {
		fmt.Println("批量插入失败=", err.Error())
		return
	}
	fmt.Println("批量插入成功=", many.InsertedIDs, len(many.InsertedIDs))

	// 3. 查询
	//var u myUser
	//findOne := collection.FindOne(context.TODO(), bson.D{}).Decode(&u) // 查询一个
	findOptions := options.Find()
	findOptions.SetLimit(2) // 可选-只输出2个
	cur, err := collection.Find(context.TODO(), bson.D{}, findOptions)
	if err != nil {
		fmt.Println("查询异常-获取游标失败=" + err.Error())
		return
	}
	defer cur.Close(context.TODO())
	defer MongoClient.Disconnect(context.TODO())
	for cur.Next(context.TODO()) {
		var result bson.D
		if err := cur.Decode(&result); err != nil {
			fmt.Println("cur.Decode异常=" + err.Error())
			return
		}
		fmt.Println("查询结果=", result)
	}
	// 4. 更新
	updateOne, err := collection.UpdateOne(context.TODO(), bson.D{{"Name", "x1"}}, bson.D{{"$inc", bson.D{{"Age", 1}}}})
	if err != nil {
		fmt.Println("单个更新失败=" + err.Error())
		return
	}
	fmt.Println("单个更新成功=", updateOne.MatchedCount, updateOne.ModifiedCount)
	updateMany, err := collection.UpdateMany(context.TODO(), bson.D{{"Name", "x2"}}, bson.D{{"$set", bson.D{{"Age", uint(31)}}}}) // 修改多个  age加1
	if err != nil {
		fmt.Println("批量更新失败=" + err.Error())
		return
	}
	fmt.Println("批量更新成功=", updateMany.MatchedCount, updateMany.ModifiedCount)
	// 5.删除
	//err = collection.Drop(context.TODO()) // 删除整个集合(数据表)
	//if err != nil{
	//	fmt.Println("删除整个集合失败=" + err.Error())
	//	return
	//}else {
	//	fmt.Println("删除整个集合成功")
	//}
	deleteOne, err := collection.DeleteOne(context.TODO(), bson.D{{"Name", "x2"}})
	if err != nil {
		fmt.Println("单条删除失败=" + err.Error())
		return
	} else {
		fmt.Println("单条删除成功=", deleteOne.DeletedCount)
	}
	deleteMany, err := collection.DeleteMany(context.TODO(), bson.D{{"Name", "x2"}})
	if err != nil {
		fmt.Println("批量删除失败=" + err.Error())
		return
	} else {
		fmt.Println("批量删除成功=", deleteMany.DeletedCount)
	}
}


posted @   爱编程_喵  阅读(100)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下
jQuery火箭图标返回顶部代码

jQuery火箭图标返回顶部代码

滚动滑动条后,查看右下角查看效果。很炫哦!!

适用浏览器:IE8、360、FireFox、Chrome、Safari、Opera、傲游、搜狗、世界之窗.

点击右上角即可分享
微信分享提示