go 操作 mongodb

MongoDB Go驱动程序

MongoDB Go Driver使用帮助文档

安装使用:

go.mongodb.org/mongo-driver/mongo

安装直接 go mod 就 ok了

使用Go Driver连接到MongoDB

1、链接数据库 mongo.Connect()
Connect 需要两个参数,一个context和一个options.ClientOptions对象
简单的链接实例:

// 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!")

上面代码的流程就是 创建 链接对象 option 和 context , 然后写入mongo.Connect , Connect 函数返回一个链接对象 和一个错误 对象,如果错误对象不为空,那就链接失败了
然后我们可以再次测试,链接:client.Ping(context.TODO(), nil)
cilent 对象 Ping 就好了,他会返回一个错误对象,如果不为空,就链接失败了
2、链接成功后,可以创建 数据表的链接对象了:

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

test 是数据库,aaa是数据表
3、断开链接对象 client.Disconnect()
如果我们不在使用 链接对象,那最好断开,减少资源消耗

err = client.Disconnect(context.TODO())
if err != nil {
    log.Fatal(err)
}
fmt.Println("Connection to MongoDB closed.")
操作数据库

使用 bson 结构来传递命令,mongo 保存的数据是 json 的二进制形式,此外还扩展 了数据类型,可以表示 int, array 等字段类型。
Go Driver有两个系列的类型表示BSON数据:D系列类型和Raw系列类型
既然文档只讲了 D系列,那就先看 D

– D:一个BSON文档。这个类型应该被用在顺序很重要的场景, 比如MongoDB命令。
– M: 一个无需map。 它和D是一样的, 除了它不保留顺序。
– A: 一个BSON数组。
– E: 在D里面的一个单一的子项。

M (map) A(array) 其他两个不知啥缩写。

bson.D{{
    "name", 
    bson.D{{
        "$in", 
        bson.A{"Alice", "Bob"}
    }}
}}

上面是一个简单的过滤文档,匹配的是 name 是Alice 或 Bob的数据

CRUD操作

明天看吧》》》
和 pymongo 基本是兄弟

  • 插入单个文档
collection.InsertOne()
type Trainer struct {
    Name string
    Age  int
    City string
}
ash := Trainer{"Ash", 10, "Pallet Town"}
insertResult, err := collection.InsertOne(context.TODO(), ash)
if err != nil {
    log.Fatal(err)
}
fmt.Println("Inserted a single document: ", insertResult.InsertedID)
  • 插入多条文档
collection.InsertMany()

不同的是接受一个 切片作为数据集合

trainers := []interface{}{misty, brock}

insertManyResult, err := collection.InsertMany(context.TODO(), trainers)
if err != nil {
    log.Fatal(err)
}

fmt.Println("Inserted multiple documents: ", insertManyResult.InsertedIDs)
  • 更新文档
    更新单个文档
collection.UpdateOne()
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)
}
// update := bson.M{"$set": server.Task_info{Task_id: "update task id"}}  // 不推荐直
接用结构体,玩意结构体字段多了,初始化为零值。
// 因为可能会吧零值更新到数据库,而不是像 gorm 的updates 忽略零值
  • 查找文档
    需要一个filter文档, 以及一个指针在它里边保存结果的解码
    查询单个文档:
collection.FindOne()
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)

查询多个文档使用:

collection.Find()

查询多个文档事例:

one, _:= collect.Find(context.TODO(), bson.M{"task_id": "cccccc"})

    defer func() {  // 关闭
        if err := one.Close(context.TODO()); err != nil {
            log.Fatal(err)
        }
    }()

    c := []server.Task_info{}
    _ = one.All(context.TODO(), &c)   // 当然也可以用   next
    for _, r := range c{
        Println(r)
    }
  • 删除文档
collection.DeleteOne() 或者 collection.DeleteMany()

bson.D{{}}作为filter参数,这会匹配集合内所有的文档

deleteResult, err := collection.DeleteMany(context.TODO(), bson.D{{}})

为字段建立索引

mod := mongo.IndexModel{
        Keys: bson.M{
            "Some Int": -1, // index in descending order 
        },
        // create UniqueIndex option
        Options: options.Index().SetUnique(true),
    }

    // Create an Index using the CreateOne() method
collect = some_database.Collection("xxx")  // 拿到数据表 
ind, err = collect.Indexes().CreateOne(context.TODO(), mod)  // returns (string, error)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容