mongodb - 来自 MongoDB 的 alpha 驱动程序的简单 CRUD 示例

标签 mongodb go

我想从 MongoDB 测试 Golang MongoDB 驱动程序 ( https://github.com/mongodb/mongo-go-driver ,目前处于 alpha 状态)。

包文档 ( https://godoc.org/github.com/mongodb/mongo-go-driver/mongo ) 中的示例对我帮助不大。我正在寻找的是基本 CRUD 操作的简单(但完整)示例。

最佳答案

@Stennie:感谢您的详细解释。我已经看过上面提到的例子,但它们看起来很低级,对我来说不是 Go 的惯用语言。所以我想到了这个:

// Size defines the item size
type Size struct {
    H   int
    W   float64
    Uom string
}

// Item defines an item
type Item struct {
    OID  objectid.ObjectID `bson:"_id,omitempty"` // omitempty not working
    Item string
    Qty  int
    Tags []string
    Size Size
}

func main() {
    // connect to MongoDB
    client, err := mongo.Connect(context.Background(), "mongodb://localhost:27017", nil)
    if err != nil {
        log.Fatal(err)
    }
    db := client.Database("mongosample")
    inventory := db.Collection("inventory")

    // write document
    itemWrite := Item{Item: "canvas", Qty: 100, Tags: []string{"cotton"}, Size: Size{H: 28, W: 35.5, Uom: "cm"}}
    itemWrite.OID = objectid.New()
    fmt.Printf("itemWrite = %v\n", itemWrite)

    result, err := inventory.InsertOne(context.Background(), itemWrite)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("result = %#v\n", result)

    // read documents
    cursor, err := inventory.Find(
        context.Background(),
        bson.NewDocument(bson.EC.String("item", "canvas")),
    )
    if err != nil {
        log.Fatal(err)
    }
    defer cursor.Close(context.Background())

    itemRead := Item{}
    for cursor.Next(context.Background()) {
        err := cursor.Decode(&itemRead)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("itemRead = %v\n", itemRead)
    }
}

我不需要控制应用程序中的ObjectID,想让驱动程序或数据库按需生成ID。这里的问题:我找不到省略 ID 的方法。这个 bson:"_id,omitempty" 不工作。它导致一个 OID,所有内容都设置为零“ObjectID(“000000000000000000000000”)”。可能是一个普遍的问题,因为 ObjectID 是一个数组而不是一个 slice :type ObjectID [12]byte

关于mongodb - 来自 MongoDB 的 alpha 驱动程序的简单 CRUD 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50346585/

相关文章:

node.js - 当数据库位于服务器文件夹之外时如何启动 Mongoose 连接?

javascript - 无需编辑 MEAN 中的整个条目即可将数据推送到 MongoDB

c - 与 c 相比,Go 的二进制大小

go - 在 Go 模板中,访问范围内的父/全局管道

cookies - 使用 net/http 设置 cookie

python - "AttributeError: ' GridFS ' object has no attribute ' 查找 '"

mongodb - 如何将 MongoDB 图表嵌入到应用程序中

ruby-on-rails - Mongoid:一次调用创建多个对象

Golang 接口(interface)反射与接口(interface)指针

mongodb - 官方 mongodb go-driver heroku 连接到 mongodb atlas 沙箱