mongodb在go中api实践

本文介绍了如何在Go中使用docker部署MongoDB运行环境,详细步骤包括领取镜像、安装、创建admin用户。此外,文章讲解了MongoDB的实际操作,强调在插入数据时自动创建数据库和集合的特点,以及在Go中连接MongoDB、进行CRUD操作的方法,特别是使用D类型构建BSON文档。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

docker部署mongodb运行环境

  • 领取镜像并安装

1、docker search mongo

2、docker pull mongo

3、docker images

4、docker run -itd --name mongo -p 27017:27017 mongo --auth

  • 插入admin用户

1、docker exec -it mongo mongosh admin

2、db.createUser({ user:‘admin’,pwd:‘123456’,roles:[ { role:‘userAdminAnyDatabase’, db: ‘admin’},“readWriteAnyDatabase”]});

3、db.auth(‘admin’,‘123456’);

mongodb 实际操作

MongoDB 中的数据库和集合无需提前创建,它们会在首次插入数据时自动创建。因此,在使用 MongoDB 进行开发时,不需要显式地创建数据库或集合。

当你使用 db.collection.insert() 命令向一个不存在的集合插入数据时,MongoDB 会自动创建该集合,并将文档插入到其中。

  • 连接
func main() {
	clientOptions := options.Client().ApplyURI("mongodb://username:password@localhost:27017")
	client, err := mongo.Connect(context.Background(), clientOptions)
	if err != nil {
		fmt.Println("Failed to connect to MongoDB:", err)
		return
	}
	err = client.Ping(context.Background(), nil)
	if err != nil {
		fmt.Println("Failed to ping MongoDB:", err)
		return
	}
	fmt.Println("Connected to MongoDB!")
}
  • 文档的crud

连接MongoDB的Go驱动程序中有两大类型表示BSON数据:D和Raw。

类型D家族被用来简洁地构建使用本地Go类型的BSON对象。这对于构造传递给MongoDB的命令特别有用。D家族包括四类:

D:一个BSON文档。这种类型应该在顺序重要的情况下使用,比如MongoDB命令。

M:一张无序的map。它和D是一样的,只是它不保持顺序。

A:一个BSON数组。

E:D里面的一个元素。

Raw类型家族用于验证字节切片。你还可以使用Lookup()从原始类型检索单个元素。如果你不想要将BSON反序列化成另一种类型的开销,那么这是非常有用的。这个教程我们将只使用D类型。

package main

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

func TestCreateDocument(t *testing.T) {
	clientOptions := options.Client().ApplyURI("mongodb://admin:123456@localhost:27017")
	client, err := mongo.Connect(context.Background(), clientOptions)
	if err != nil {
		panic("init mongo error")
	}

	err = client.Ping(context.Background(), nil)
	if err != nil {
		panic("mongo auth failed")
	}

	collection := client.Database("test").Collection("test")
	document := bson.M{
		"title":   "MongoDB Go Driver",
		"version": "1.0",
		"url":     "https://github.com/mongodb/mongo-go-driver",
	}
	result, err := collection.InsertOne(context.Background(), document)
	if err != nil {
		fmt.Println("Failed to insert document:", err)
		return
	}
	fmt.Printf("Inserted document with ID: %v\n", result.InsertedID)
}

func TestQueryDocument(t *testing.T) {
	clientOptions := options.Client().ApplyURI("mongodb://admin:123456@localhost:27017")
	client, err := mongo.Connect(context.Background(), clientOptions)
	if err != nil {
		panic("init mongo error")
	}

	err = client.Ping(context.Background(), nil)
	if err != nil {
		panic("mongo auth failed")
	}

	type Document struct {
		Title   string `bson:"title"`
		Version string `bson:"version"`
		URL     string `bson:"url"`
	}

	query := bson.M{"title": "MongoDB Go Driver", "version": "1.0"}
	var res Document

	collection := client.Database("test").Collection("test")

	err = collection.FindOne(context.Background(), query).Decode(&res)
	if err != nil {
		panic(err)
	}
	fmt.Println(res)
}

func TestUpdateDocument(t *testing.T) {
	clientOptions := options.Client().ApplyURI("mongodb://admin:123456@localhost:27017")
	client, err := mongo.Connect(context.Background(), clientOptions)
	if err != nil {
		panic("init mongo error")
	}

	err = client.Ping(context.Background(), nil)
	if err != nil {
		panic("mongo auth failed")
	}

	filter := bson.M{"version": "2.0"}
	update := bson.M{"$set": bson.M{
		"version": "3.0",
	}}

	collection := client.Database("test").Collection("test")
	res, err := collection.UpdateOne(context.Background(), filter, update)
	if err != nil {
		panic(err)
	}
	fmt.Println(res)
}

func TestDeleteDocument(t *testing.T) {
	clientOptions := options.Client().ApplyURI("mongodb://admin:123456@localhost:27017")
	client, err := mongo.Connect(context.Background(), clientOptions)
	if err != nil {
		panic("init mongo error")
	}

	err = client.Ping(context.Background(), nil)
	if err != nil {
		panic("mongo auth failed")
	}

	filter := bson.M{"version": "3.0"}
	collection := client.Database("test").Collection("test")
	res, err := collection.DeleteOne(context.Background(), filter)
	if err != nil {
		panic(err)
	}
	fmt.Println(res)
}

资料补充

补充资料1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值