我想从 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/