MongoDB.live, free & fully virtual. June 9th - 10th. Register Now MongoDB.live, free & fully virtual. June 9th - 10th. Register Now

Best practice for multiple read concerns? Transactions and multiple changestreams with golang

I have a server that requires data integrity that is enforced through the use of multi-document transactions (which requires Primary ReadPreference), but also serves many Changestreams across multiple different collections (SecondaryPreferred would be the preferred ReadConcern here).

What would be the best practice to support this? It seems you can’t set a read preference on ChangeStreams, which would have been the easiest way. It seems the only way to set a ReadPreference is client-wide with the official MongoDB golang driver.

Would maintaining two clients, one with ReadPref Primary and one with ReadPref SecondaryPreferred, be the best way to handle this? Or does Mongo have a more elegant way of handling this?

Thanks for any suggestions

Are you creating the change streams through Client.Watch, Database.Watch, or Collection.Watch? If it’s Database or Collection, you can make a database or collection object configured with secondary read preference:

secondary := readpref.Secondary()
dbOpts := options.Database().SetReadPreference(secondary)
db := client.Database("dbname", dbOpts)

You’re absolutely correct; I facepalmed when I realized it shortly after posting.

The biggest benefit I got out of realizing it is how to further hone my repository pattern to pass Collections instead of collection names. This gets me more customizable ReadPreferences, which I need because not every call will be a Transaction, but certainly some will.

Thanks for your help!