在mongodb-go-driver中,如何将BSON编组/解组为结构 [英] In mongodb-go-driver, how to marshal/unmarshal BSON in to a struct

查看:62
本文介绍了在mongodb-go-driver中,如何将BSON编组/解组为结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to mongodb-go-driver. But i am stuck.

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])
}

当查看m [id]的内容时,它没有内容-全部为空.

When look at the contents of m[id], it has no content - all nulls.

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

My map is like this : m map[string]Language

并且语言定义如下:

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"`
}

我在做什么错了?

我正在使用以下示例进行学习: https ://github.com/mongodb/mongo-go-driver/blob/master/examples/documentation_examples/examples.go

I am learning using this example : https://github.com/mongodb/mongo-go-driver/blob/master/examples/documentation_examples/examples.go

推荐答案

MongoDB官方驱动程序将objectid.ObjectID类型用于MongoDB ObjectId.此类型是:

The official MongoDB driver uses the objectid.ObjectID type for MongoDB ObjectIds. This type is:

type ObjectID [12]byte

因此,您需要将结构更改为:

So you need to change your struct to:

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"`
}

我在以下方面取得了成功:

I had success with:

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
}

这篇关于在mongodb-go-driver中,如何将BSON编组/解组为结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆