GO操作mongoDB

这篇博客详细介绍了如何在Go环境中连接、操作MongoDB数据库,包括建立连接、插入、更新、查询和删除数据的基本步骤,是Go语言开发者学习MongoDB数据库操作的实用教程。

GO操作mongo数据库实战

主要是mongo官方文档抄过来的,加上一些自己简单的话术

先决条件

有go环境和mongo环境

创建好go mod文档,导入驱动

 require go.mongodb.org/mongo-driver

写个demo

创建一个main.go

导入本次需要的包,和写上一个结构体做案例

import (
    "context"
    "fmt"
    "log"

    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)
// You will be using this Trainer type later in the program
type Trainer struct {
    Name string
    Age  int
    City string
}

连接测试

// Set client options
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

// Connect to MongoDB
client, err := mongo.Connect(context.TODO(), clientOptions)

if err != nil {
    log.Fatal(err)
}

// Check the connection
err = client.Ping(context.TODO(), nil)

if err != nil {
    log.Fatal(err)
}

fmt.Println("Connected to MongoDB!")



//最后可能也需要关闭连接
err = client.Disconnect(context.TODO())

if err != nil {
    log.Fatal(err)
}
fmt.Println("Connection to MongoDB closed.")

指定操作集合以及数据库

//test数据库下的trainers集合
collection := client.Database("test").Collection("trainers")

插入

ash := Trainer{"Ash", 10, "Pallet Town"}
//这里可以使用InsertMany来插入多条
insertResult, err := collection.InsertOne(context.TODO(), ash)
if err != nil {
    log.Fatal(err)
}
fmt.Println("Inserted a single document: ", insertResult.InsertedID)

更新

//更新查询删除的时候会用到filter
filter := bson.D{{"name", "Ash"}}
//更新规则
update := bson.D{
    {"$inc", bson.D{
        {"age", 1},
    }},
}
//这儿只更新一条
updateResult, err := collection.UpdateOne(context.TODO(), filter, update)
if err != nil {
    log.Fatal(err)
}

查找

var result Trainer
//这儿只查找一条
err = collection.FindOne(context.TODO(), filter).Decode(&result)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Found a single document: %+v\n", result)


//查找多条
findOptions := options.Find()
findOptions.SetLimit(3)
// Here's an array in which you can store the decoded documents
var results []*Trainer
// Passing bson.D{{}} as the filter matches all documents in the collection
cur, err := collection.Find(context.TODO(), bson.D{{}}, findOptions)
if err != nil {
  log.Fatal(err)
}

// Finding multiple documents returns a cursor
// Iterating through the cursor allows us to decode documents one at a time
for cur.Next(context.TODO()) {
  // create a value into which the single document can be decoded
  var elem Trainer
  err := cur.Decode(&elem)
  if err != nil {
    log.Fatal(err)
  }

  results = append(results, &elem)
}

if err := cur.Err(); err != nil {
  log.Fatal(err)
}

// Close the cursor once finished
cur.Close(context.TODO())

fmt.Printf("Found multiple documents (array of pointers): %+v\n", results)
for i := 0; i < len(results); i++ {
  fmt.Println(results[i])
}

删除

deleteResult, err := collection.DeleteMany(context.TODO(), bson.D{{}})
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Deleted %v documents in the trainers collection\n", deleteResult.DeletedCount)
### Golang 操作 MongoDB 的方法 #### 连接 MongoDB 数据库 要使用 Go 语言操作 MongoDB,通常会借助官方驱动程序 `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 URI[^1] ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() client, err := mongo.Connect(ctx, clientOptions) // 建立连接[^1] if err != nil { log.Fatal(err) } err = client.Ping(ctx, nil) // 测试连接是否成功[^1] if err != nil { log.Fatal(err) } fmt.Println("Connected to MongoDB!") } ``` #### 插入数据到集合 下面是一个向 MongoDB 集合插入文档的示例代码: ```go package main import ( "context" "log" "time" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) type Person struct { // 定义结构体表示文档模型 Name string Age int City string } func insertData(client *mongo.Client) { collection := client.Database("testdb").Collection("people") person := Person{Name: "Alice", Age: 30, City: "New York"} // 创建一个Person对象 insertResult, err := collection.InsertOne(context.TODO(), person) // 插入单条记录 if err != nil { log.Fatal(err) } fmt.Printf("Inserted document with ID %v\n", insertResult.InsertedID) } ``` #### 查询数据 以下是从 MongoDB 中查询数据的一个简单例子: ```go package main import ( "context" "log" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) type Person struct { // 结构体用于映射查询结果 Name string Age int City string } func queryData(client *mongo.Client) { collection := client.Database("testdb").Collection("people") var result Person filter := bson.D{{Key: "name", Value: "Alice"}} // 构造过滤条件 err := collection.FindOne(context.TODO(), filter).Decode(&result) // 执行查询并解码结果 if err != nil { log.Fatal(err) } fmt.Printf("Found a single document: %+v\n", result) } ``` --- ### 总结 以上代码片段展示了如何利用 Go 和其官方 MongoDB 驱动完成基本的操作,包括建立连接、插入数据以及执行简单的查询。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值