My understanding of doing so is to ensure: "If a process reads the value of a data item x, any successive read operation on x by that process will always return that same value or a more recent value."
Yes, but not always. Let's look into the code comment for Monotonic mode session.go#L73:
// Monotonic mode is specific to mgo, and is same as SecondaryPreferred before first write.
// Same as Primary after first write.
Monotonic Mode = 1
According to godoc.org/github.com/globalsign/mgo for SetMode()
:
In the Monotonic consistency mode reads may not be entirely
up-to-date, but they will always see the history of changes moving
forward, the data read will be consistent across sequential queries in
the same session, and modifications made within the session will be
observed in following queries (read-your-writes).
In practice, the Monotonic mode is obtained by performing initial
reads on a unique connection to an arbitrary secondary, if one is
available, and once the first write happens, the session connection is
switched over to the primary server. This manages to distribute some
of the reading load with secondaries, while maintaining some useful
guarantees.
For most of the cases this is true, however there could be instances where SecondaryPreferred
may choose different secondaries that could have different Oplog times.
How would I do this using the official driver?
Monotonic mode is a term specific for mgo, and does not exist for MongoDB Go driver. This has been superseded by new features such as causal consistency and/or multi-document transactions.
mongo-go-driver
is more verbose, but also to provide more control over read preferences, read concern, and write concern
Example of causal consistency:
opts := options.Client().ApplyURI(mongoURI).SetReadPreference(readpref.Secondary()).SetReadConcern(readconcern.Majority()).SetWriteConcern(writeconcern.New(writeconcern.WMajority()))
client, err := mongo.NewClient(opts)
if err != nil {
panic(err)
}
For transactions example see Transactions in Applications (Choose Go
language on the tab)