I have read this friendly article about encoding and decoding custom object using official go mongo driver.
There is nice example how to marshaling them into extended json format (bson.MarshalExtJSONWithRegistry
). But I would like to know how to put this document into collection with InserOne()
(and later get it from). Look at this pseudo code:
// myReg - variable created according to linked article in question.
// WithRegistry do **not** exist in mongo-driver lib is part of pseudocode
mongoCollection := client.Database("db").Collection("coll").WithRegistry(myReg)
// Now InserOne() honor myReg (type *bsoncodec.Registry) when serialize `val` and puting it into mongodb
mongoCollection.InsertOne(context.TODO(), val)
I have go through API doc and I have found there are Marshaler and Unmarshaler interfaces, but with registry way I would be able to (de)serialize the same type in different way on different collection (for example when migrate from old format to new one).
So the question is how to use *bsoncodec.Registry
with collection functions (like InserOne
, UpdateOne
, FindOne
etc.) if not what is the most idiomatic way to achieve my goal (custom (de)serialize).