在mongodb-go-driver中,如何将BSON编组/解组到结构中

iam*_*yan 7 go mongodb

我是mongodb-go-driver的新手.但我被卡住了.

cursor, e := collection.Find(context.Background(), bson.NewDocument(bson.EC.String("name", id)))

for cursor.Next(context.Background()) {

    e := bson.NewDocument()
    cursor.Decode(e)

    b, _ := e.MarshalBSON()
    err := bson.Unmarshal(b, m[id])
}
Run Code Online (Sandbox Code Playgroud)

当查看m [id]的内容时,它没有内容 - 所有空值.

我的地图是这样的:m map [string]语言

和语言定义如下:

type Language struct {
    ID         string   `json:"id" bson:"_id"`                   // is this wrong?
    Name       string   `json:"name" bson:"name"`
    Vowels     []string `json:"vowels" bson:"vowels"`
    Consonants []string `json:"consonants" bson:"consonants"`
}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

我正在学习使用这个例子:https://github.com/mongodb/mongo-go-driver/blob/master/examples/documentation_examples/examples.go

Ale*_*sov 11

较新的“ github.com/mongodb/mongo-go-driver”期望将对象ID定义为

type Application struct {
    ID      *primitive.ObjectID `json:"ID" bson:"_id,omitempty"`
}
Run Code Online (Sandbox Code Playgroud)

这将序列化为JSON "ID":"5c362f3fa2533bad3b6cf6f0",这是从插入结果中获取ID的方法

if oid, ok := res.InsertedID.(primitive.ObjectID); ok {
    app.ID = &oid
}
Run Code Online (Sandbox Code Playgroud)

从字符串转换

appID := "5c362f3fa2533bad3b6cf6f0"    
id, err := primitive.ObjectIDFromHex(appID)
if err != nil {
    return err
}
_, err = collection.DeleteOne(nil, bson.M{"_id": id})
Run Code Online (Sandbox Code Playgroud)

转换成字符串

str_id := objId.Hex()
Run Code Online (Sandbox Code Playgroud)


Far*_*ahi 8

官方MongoDB驱动程序使用MongoDB ObjectIds的objectid.ObjectID类型.这种类型是:

type ObjectID [12]byte

所以你需要将你的结构更改为:

type Language struct {
    ID         objectid.ObjectID   `json:"id" bson:"_id"`             
    Name       string   `json:"name" bson:"name"`
    Vowels     []string `json:"vowels" bson:"vowels"`
    Consonants []string `json:"consonants" bson:"consonants"`
}
Run Code Online (Sandbox Code Playgroud)

我成功了:

m := make(map[string]Language)
cursor, e := collection.Find(context.Background(), bson.NewDocument(bson.EC.String("name", id)))

for cursor.Next(context.Background()) {

    l := Language{}
    err := cursor.Decode(&l)
    if err != nil {
        //handle err
    }
    m[id] = l // you need to handle this in a for loop or something... I'm assuming there is only one result per id
}
Run Code Online (Sandbox Code Playgroud)


Ill*_*nko 6

更新: 最近进行了新的更改,现在必须更改为:

import "github.com/mongodb/mongo-go-driver/bson/primitive"

type Language struct {
    ID         primitive.ObjectID `bson:"_id,omitempty"` // omitempty to protect against zeroed _id insertion         
    Name       string   `json:"name" bson:"name"`
    Vowels     []string `json:"vowels" bson:"vowels"`
    Consonants []string `json:"consonants" bson:"consonants"`
}
Run Code Online (Sandbox Code Playgroud)

并取 ID 值:

log.Println("lang id:", objLang.ID)
...
Run Code Online (Sandbox Code Playgroud)