golang convert primative.D to struct

886 views
Skip to first unread message

Matthew Shaver

unread,
Jun 24, 2019, 6:35:26 PM6/24/19
to mongodb-user
In go I am storing a structure with an interface{} field to be able to store different sub structures in the mongodb record. When I read back the record into the struct I can see the interface{} field has type primitive.D. 

I can convert that data to a specific struct type using the following steps but I want to know if this is the recommended / most efficient method

type Record struct {
  Type         string
  SubStruct interface{}
}

type SubRec struct {
  Val1 int
  Val2 int
}

rec, err := jobs.Find(StdDb, insertId)

subPrimativeD := rec.SubStruct.(primitive.D)

temp, err := bson.MarshalExtJSON(subPrimativeD, true, true)

var subRec SubRec
err := bson.UnmarshalExtJSON(temp, true, &subRec)


Wan Bachtiar

unread,
Jul 1, 2019, 8:49:39 PM7/1/19
to mongodb-user

In go I am storing a structure with an interface{} field to be able to store different sub structures in the mongodb record. When I read back the record into the struct I can see the interface{} field has type primitive.D.

Hi Matthew,

Not exactly sure what the problem here, but other than interface you can also use either bson.D (ordered), or bson.M (unordered). For example:

type Record struct {
    Type string
    SubStruct bson.D
}

And you can just call Cursor.Decode() instead of the marshal/unmarshal, for example:

cursor, err := collection.Find(context.TODO(), bson.D{})
if err != nil {
    log.Fatal(err)
}
defer cursor.Close(context.TODO())
for cursor.Next(context.Background()) {
    doc := &Record{}
    err = cursor.Decode(doc)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(doc)
}

The above is assuming you’re using the current version of MongoDB Go driver v1.0.3. If you have further question, please include the driver version that you’re using.

Regards,
Wan.

Reply all
Reply to author
Forward
0 new messages