In mongodb-go-driver, how to marshal/unmarshal BSON in to a struct

后端 未结 4 912
野趣味
野趣味 2021-02-05 21:19

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.Nex         


        
4条回答
  •  别跟我提以往
    2021-02-05 22:21

    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
    }
    

提交回复
热议问题