go操作MongoDB

MongoDB介绍

MongoDB是目前比较流行的一个基于分布式文件存储的数据库,它是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库中功能最丰富,最像关系数据库的
MongoDB中将一条数据储存为一个文档(document),数据结构由键值对(K-V)组成,其中文档类似于平常使用到的JSON对象,文档中的字段值可以包含其他文档,数组,及文档数组

insert

package main

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

func main() {
	ctx := context.Background()
	mc, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://username:password@localhost:27017/?authSource=admin"))
	if err != nil {
		panic(err)
	}

	col := mc.Database("coolcar").Collection("account")
	insertRows(col, ctx)
}

// insertRows 新增mongodb
func insertRows(col *mongo.Collection, ctx context.Context) {
	res, err := col.InsertMany(ctx, []interface{}{
		bson.M{
			"open_id": "123",
		},
		bson.M{
			"open_id": "456",
		},
	})
	if err != nil {
		panic(err)
	}
	// &{InsertedIDs:[ObjectID("623f086deda4096b61beaae4") ObjectID("623f086deda4096b61beaae5")]}
	fmt.Printf("%+v", res)
}

在这里插入图片描述

delete

package main

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

func main() {
	ctx := context.Background()
	mc, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://username:password@localhost:27017/?authSource=admin"))
	if err != nil {
		panic(err)
	}

	col := mc.Database("coolcar").Collection("account")
	deleteRows(col, ctx)
}

// deleteRows 输出操作的条数
func deleteRows(col *mongo.Collection, ctx context.Context) {
	res, err := col.DeleteOne(ctx, bson.M{"open_id": "456"})
	if err != nil {
		panic(err)
	}
	// 1
	fmt.Println(res.DeletedCount)
}

在这里插入图片描述

update

package main

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

func main() {
	ctx := context.Background()
	mc, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://username:password@localhost:27017/?authSource=admin"))
	if err != nil {
		panic(err)
	}

	col := mc.Database("coolcar").Collection("account")
	updateRows(col, ctx)
}

// updateRows 输出操作的条数
func updateRows(col *mongo.Collection, ctx context.Context) {
	res, err := col.UpdateOne(ctx, bson.M{"open_id": "123"}, bson.M{"$set": bson.M{"open_id": "123456"}})
	if err != nil {
		panic(err)
	}
	// 1
	fmt.Println(res.ModifiedCount)
}

在这里插入图片描述

find

package main

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

func main() {
	ctx := context.Background()
	mc, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://username:password@localhost:27017/?authSource=admin"))
	if err != nil {
		panic(err)
	}

	col := mc.Database("coolcar").Collection("account")
	findRows(ctx, col)
}

// findRows 查询mongo
func findRows(ctx context.Context, col *mongo.Collection) {
	res := col.FindOne(ctx, bson.M{
		"open_id": "123456",
	})
	var row struct {
		Id     primitive.ObjectID `bson:"_id"`
		OpenID string             `bson:"open_id"`
	}
	err := res.Decode(&row)
	if err != nil {
		panic(err)
	}
	// {Id:ObjectID("623f086deda4096b61beaae4") OpenID:123456}
	fmt.Printf("%+v\n", row)
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要使用 Go 操作 MongoDB,你可以使用第三方库来连接和操作数据库。其中最受欢迎的库是官方推荐的 "mongo-go-driver"。 首先,你需要安装 "mongo-go-driver" 库。你可以使用以下命令进行安装: ``` go get go.mongodb.org/mongo-driver ``` 接下来,你可以使用以下代码示例来连接 MongoDB 数据库并执行一些操作: ```go package main import ( "context" "fmt" "log" "time" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) func main() { // 设置连接选项 clientOptions := options.Client().ApplyURI("mongodb://localhost:27017") // 连接到 MongoDB client, err := mongo.Connect(context.TODO(), clientOptions) if err != nil { log.Fatal(err) } // 检查连接 err = client.Ping(context.TODO(), nil) if err != nil { log.Fatal(err) } fmt.Println("Connected to MongoDB!") // 选择数据库和集合 database := client.Database("mydatabase") collection := database.Collection("mycollection") // 插入文档 document := bson.D{ {"name", "John Doe"}, {"age", 30}, {"email", "johndoe@example.com"}, } insertResult, err := collection.InsertOne(context.TODO(), document) if err != nil { log.Fatal(err) } fmt.Println("Inserted document ID:", insertResult.InsertedID) // 查询文档 var result bson.M filter := bson.M{"name": "John Doe"} err = collection.FindOne(context.TODO(), filter).Decode(&result) if err != nil { log.Fatal(err) } fmt.Println("Found document:", result) // 更新文档 update := bson.D{ {"$set", bson.D{{"age", 35}}}, } updateResult, err := collection.UpdateOne(context.TODO(), filter, update) if err != nil { log.Fatal(err) } fmt.Println("Updated", updateResult.ModifiedCount, "document(s)") // 删除文档 deleteResult, err := collection.DeleteOne(context.TODO(), filter) if err != nil { log.Fatal(err) } fmt.Println("Deleted", deleteResult.DeletedCount, "document(s)") // 断开与 MongoDB 的连接 err = client.Disconnect(context.TODO()) if err != nil { log.Fatal(err) } fmt.Println("Disconnected from MongoDB!") } ``` 在上述示例中,我们首先建立了与 MongoDB 的连接,然后选择了一个数据库和一个集合。之后,我们插入了一个文档、查询了一个文档、更新了一个文档,并最后删除了一个文档。最后我们断开了与 MongoDB 的连接。 请确保你已经安装了 MongoDB 并且运行在本地的默认端口 27017 上。你还可以根据需要进行更多的操作,包括创建索引、使用聚合管道等。 希望这个示例能帮助到你!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

.番茄炒蛋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值