Golang实现Mongo数据库增删改查操作

 更新时间:2024年01月09日 11:38:58   作者:Amctwd  
本文主要介绍了Golang实现Mongo数据库增删改查操作,我们使用了 MongoDB的官方Go驱动程序,实现了插入、查询、更新和删除操作,感兴趣的可以了解一下

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

一、引言

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

二、环境准备

安装 MongoDB:请参考 MongoDB 的官方文档进行安装。

安装 Go 语言环境:请参考 Go 语言的官方文档进行安装。

安装 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 进行数据操作。

到此这篇关于Golang实现Mongo数据库增删改查操作的文章就介绍到这了,更多相关Golang Mongo增删改查内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • go语言反射的基础教程示例

    go语言反射的基础教程示例

    这篇文章主要为大家介绍了go语言反射的基础教程,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-08-08
  • Go语言在终端打开实现进度条处理数据方法实例

    Go语言在终端打开实现进度条处理数据方法实例

    这篇文章主要介绍了Go语言在终端打开实现进度条处理数据方法实例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-12-12
  • Golang 操作 Kafka 如何设置消息的失效时间

    Golang 操作 Kafka 如何设置消息的失效时间

    在使用 Golang 操作 Kafka 时,你可以使用 Sarama 库来设置消息的失效时间,这篇文章主要介绍了Golang操作Kafka设置消息的失效时间,需要的朋友可以参考下
    2023-06-06
  • go语言定义零值可用的类型学习教程

    go语言定义零值可用的类型学习教程

    这篇文章主要为大家介绍了go语言定义零值可用的类型教程学习,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-06-06
  • go写文件后出现大量NUL字符问题解决

    go写文件后出现大量NUL字符问题解决

    本文主要介绍了go写文件后出现大量NUL字符问题解决,由于每次写的时候设置的长度都是64,在某次不足64时,byte切片空余位置被填充为空字符,下面就来介绍一下如何解决
    2023-12-12
  • 解决go 生成的exe不在bin文件夹里的问题

    解决go 生成的exe不在bin文件夹里的问题

    这篇文章主要介绍了解决go 生成的exe不在bin文件夹里的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-12-12
  • Golang中如何对MySQL进行操作详解

    Golang中如何对MySQL进行操作详解

    这篇文章主要给大家介绍了关于在Golang中如何对MySQL进行操作的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者使用Golang具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-03-03
  • Go中的动态速率限制有效控制流量

    Go中的动态速率限制有效控制流量

    这篇文章主要为大家介绍了Go中的动态速率限制有效控制流量,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-10-10
  • 使用Go实现在命令行输出好看的表格

    使用Go实现在命令行输出好看的表格

    这篇文章主要介绍了使用Go实现在命令行输出好看的表格方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-04-04
  • 深入理解golang的基本类型排序与slice排序

    深入理解golang的基本类型排序与slice排序

    大家都知道排序有内部排序和外部排序,内部排序是数据记录在内存中进行排序,而外部排序是因排序的数据很大,一次不能容纳全部的排序记录,在排序过程中需要访问外存。下面就来详细介绍golang的基本类型排序与slice排序,有需要的朋友们可以参考借鉴。
    2016-09-09

最新评论