【Golang】Mongo数据库增删改查操作

本文通过详细的代码示例,展示了如何使用Go语言和MongoDB官方驱动进行数据的插入、查询、更新和删除操作,适用于初学者理解和实践NoSQL数据库操作。
摘要由CSDN通过智能技术生成

 本文将通过一个简单的 Go 语言示例,介绍如何使用 MongoDB 进行基本的数据操作,包括插入、查询、更新和删除操作。我们将使用 MongoDB 的官方 Go 驱动程序来与数据库进行交互。

一、引言

 MongoDB 是一款流行的 NoSQL 数据库,它使用文档存储结构,可以存储非常复杂的数据类型。Go 语言以其简洁和高效的特性,成为越来越多开发者选择的编程语言。在本文中,我们将结合 Go 语言和 MongoDB,展示如何实现基本的数据操作。

二、环境准备

  1. 安装 MongoDB:请参考 MongoDB 的官方文档进行安装。
  2. 安装 Go 语言环境:请参考 Go 语言的官方文档进行安装。
  3. 安装 MongoDB Go 驱动程序:在终端中运行 go get go.mongodb.org/mongo-driver/mongo

三、代码实现

 以下是一个简单的 Go 语言示例,展示了如何使用 MongoDB 进行数据操作。

1. 连接到 MongoDB

func MongoClient() *mongo.Client {
	clientOptions := options.Client().ApplyURI("mongodb://10.90.45.1:27017/?connect=direct")
	client, err := mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}
	return client
}

2. 插入数据

func InsertOne(client *mongo.Client, databaseName string, collectionName string, doc bson.M) error {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	collection := client.Database(databaseName).Collection(collectionName)
	_, err := collection.InsertOne(ctx, doc)
	return err
}
func InsertMany(client *mongo.Client, databaseName string, collectionName string, doc []interface{}) error {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	collection := client.Database(databaseName).Collection(collectionName)
	_, err := collection.InsertMany(ctx, doc)
	return err
}

3. 查询数据

func Find(client *mongo.Client, databaseName string, collectionName string, filter bson.M) ([]bson.M, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	collection := client.Database(databaseName).Collection(collectionName)
	cur, err := collection.Find(ctx, filter)
	if err != nil {
		return nil, err
	}
	defer cur.Close(ctx)
	var results []bson.M
	for cur.Next(ctx) {
		var result bson.M
		err := cur.Decode(&result)
		if err != nil {
			return nil, err
		}
		results = append(results, result)
	}
	if err := cur.Err(); err != nil {
		return nil, err
	}
	return results, nil
}

4. 更新数据

func UpdateOne(client *mongo.Client, databaseName string, collectionName string, filter bson.M, update bson.M) error {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	collection := client.Database(databaseName).Collection(collectionName)
	_, err := collection.UpdateOne(ctx, filter, bson.M{"$set": update})
	return err
}
func UpdateMany(client *mongo.Client, databaseName string, collectionName string, filter bson.M, update bson.M) error {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	collection := client.Database(databaseName).Collection(collectionName)
	_, err := collection.UpdateMany(ctx, filter, bson.M{"$set": update})
	return err
}

5. 删除数据

func DeleteOne(client *mongo.Client, databaseName string, collectionName string, filter bson.M) error {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	collection := client.Database(databaseName).Collection(collectionName)
	_, err := collection.DeleteOne(ctx, filter)
	return err
}
func DeleteMany(client *mongo.Client, databaseName string, collectionName string, filter bson.M) error {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	collection := client.Database(databaseName).Collection(collectionName)
	_, err := collection.DeleteMany(ctx, filter)
	return err
}

6.Main执行

package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
	client := MongoClient()
	defer client.Disconnect(context.TODO())

	dbName := "mydatabase"
	dcName := "mycollection"

	// 插入操作
	record := bson.M{"name": "John Doe", "age": 30}
	if err := InsertOne(client, dbName, dcName, record); err != nil {
		log.Fatal(err)
	}
	records := []interface{}{
		bson.M{"name": "Taylor Smith", "sex": "male", "age": 27},
		bson.M{"name": "Lisa Rune", "sex": "female", "age": 28},
		bson.M{"name": "Lily", "sex": "female", "age": 28},
		bson.M{"name": "Alex", "sex": "female", "age": 26},
		bson.M{"name": "Alisa", "sex": "female", "age": 19},
		bson.M{"name": "Tom", "sex": "male", "age": 28},
		bson.M{"name": "Felix", "sex": "male", "age": 32},
		bson.M{"name": "Richard", "sex": "male", "age": 30},
	}
	if err := InsertMany(client, dbName, dcName, records); err != nil {
		log.Fatal(err)
	}
	// 查询操作
	results, err := Find(client, dbName, dcName, bson.M{"age": 30})
	if err != nil {
		log.Fatal(err)
	}
	for _, result := range results {
		fmt.Println(result)
	}
	// 更新操作
	if err := UpsertOne(client, dbName, dcName, bson.M{"name": "Lisa Rune"}, bson.M{"age": 31}); err != nil {
		log.Fatal(err)
	}
	if err := UpdateMany(client, dbName, dcName, bson.M{"sex": "male"}, bson.M{"age": 31}); err != nil {
		log.Fatal(err)
	}
	// 删除操作
	if err := DeleteOne(client, dbName, dcName, bson.M{"name": "John Doe"}); err != nil {
		log.Fatal(err)
	}
	if err := DeleteMany(client, dbName, dcName, bson.M{"sex": "female"}); err != nil {
		log.Fatal(err)
	}
}

7.结果
在这里插入图片描述

四、总结

 本文通过一个简单的 Go 语言示例,介绍了如何使用 MongoDB 进行基本的数据操作。我们使用了 MongoDB 的官方 Go 驱动程序,实现了插入、查询、更新和删除操作。希望这个示例能够帮助您更好地了解如何在 Go 语言中使用 MongoDB 进行数据操作。

  • 17
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值