Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

mongodb

go

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

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

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

and Language is defined like :

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

What am I doing wrong?

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

like image 305
iam thadiyan Avatar asked Jul 29 '18 05:07

iam thadiyan


People also ask

How do you Unmarshal BSON?

You can unmarshal BSON documents by using the Decode() method on the result of the FindOne method or any *mongo.

Why does MongoDB use BSON?

Unlike systems that store JSON as string-encoded values, or binary-encoded blobs, MongoDB uses BSON to offer powerful indexing and querying features on top of the web's most popular data format.

What is MongoDB explain JSON and BSON data?

In MongoDB, BSON is used to encrypt the JSON data. It provides additional data types over the JSON data. It is also a language independent, and can be easily parsed. It supports the adding of documents and arrays within other documents and arrays.


2 Answers

Newer "github.com/mongodb/mongo-go-driver" expects object IDs defined as

type Application struct {
    ID      *primitive.ObjectID `json:"ID" bson:"_id,omitempty"`
}

This serializes into JSON "ID":"5c362f3fa2533bad3b6cf6f0" and here is how you get the ID from insert result

if oid, ok := res.InsertedID.(primitive.ObjectID); ok {
    app.ID = &oid
}

Convert from string

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

Convert into string

str_id := objId.Hex()
like image 155
Alexey Podlasov Avatar answered Sep 21 '22 03:09

Alexey Podlasov


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
}
like image 45
Farhad Farahi Avatar answered Sep 20 '22 03:09

Farhad Farahi