Search code examples
mongodbgomgo

Set MongoDB write concern through mgo driver


I have a Go client that repeatedly inserts data into MongoDB for 1 minute. I don't want the writes to be acknowledged to the client until they are replicated to the secondary of my primary-secondary-arbiter replica set, so I specified majority write concern through the mongo shell.

However, the client's execution completes far ahead of the writes being replicated to the secondary (I'm watching the doc count to be sure). If the primary were to crash before the replication is done, data would be rolled back that--from the client's perspective--had already been acknowledged.

Doesn't this behavior contradict the majority write concern I set through the shell? Do I also need to set the write concern through the mgo driver? This article suggests I need to:

Running MongoDB Queries Concurrently With Go

We use the mgo.DialWithInfo method to create a mgo.Session object. Each session specifies a Strong or Monotonic mode, and other settings such as write concern and read preference.

But I don't see anything in the mgo driver docs about setting write concern. What am I missing?


Solution

  • This is what you are looking for (full documentation):

    session.SetSafe(&mgo.Safe{WMode: "majority"})