美文网首页
go 操作 mongodb

go 操作 mongodb

作者: 天空蓝雨 | 来源:发表于2020-08-13 22:24 被阅读0次

    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)
    }
    
    • 查找文档
      需要一个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()
    
    • 删除文档
    collection.DeleteOne() 或者 collection.DeleteMany()
    

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

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

    相关文章

      网友评论

          本文标题:go 操作 mongodb

          本文链接:https://www.haomeiwen.com/subject/qjkudktx.html