I'm using labix mgo
as a mongodb driver in my Go app and I'm wondering if there is a way to override the default writeConcern
for specific queries.
A few words about configuration: the replica set has three nodes - one primary and two secondaries, the writeConcern
and readPreference
are default. The driver uses monotonic
consistency which means that all reads are done from the secondary (when it's available, otherwise - from the primary).
There might be cases when I need to read the updated data right after writing to the database - and because of the above mongo might return the old data:
// update some data
_ := collection.Update(bson.M{"_id": "some_id"}, bson.M{"key": "value"})
// the data is still not updated when I read it immediately after update
var obj interface{}
_ := collection.Find(bson.M{"_id": "some_id"}).One(&obj)
The question is: is it possible to override the default writeConcern
(or default consistency
of the driver) and force the driver to wait until the data is written to the secondaries OR to read from the primary for some of the queries?
Appreciate any suggestions.
Ok, after doing some research I ended up with a solution. There is a method SetMode
that allows you to change a default consistency mode for a specific DB session. In our app we create a copy of the master session every time before making a request and then closing it after it's done:
// master session is configured to use monotonic consistency
session := masterSession.Copy()
// tell mgo to read from the primary in this session
session.SetMode(mgo.Strong, true)
collection := session.DB("db").C("collection")
var obj interface{}
// now we can be sure that the following request reads the data from the primary
_ := collection.Find(bson.M{"_id": "some_id"}).One(&obj)
session.Close()