Reputation: 2751
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).
Upvotes: 4
Views: 1603
Reputation: 417797
The Database.Collection()
method has "optional" options.CollectionOptions
parameter which does have option to set the bsoncodec.Registry
. If you acquire your collection using an options that's configured with a registry, that registry will be used with all operations performed with that collection.
Use it like this:
opts := options.Collection().SetRegistry(myReg)
c := client.Database("db").Collection("coll", opts)
Quoting from my related answer: How to ignore nulls while unmarshalling a MongoDB document?
Registries can be set / applied at multiple levels, even to a whole
mongo.Client
, or to amongo.Database
or just to amongo.Collection
, when acquiring them, as part of their options, e.g.options.ClientOptions.SetRegistry()
.
So when you're not doing migration from old to new format, you may set the registry at the "client" level and "be done with it". Your registry and custom coders / decoders will be applied whenever the driver deals with a value of your registered custom type.
Upvotes: 1