PyMongo - Write to Primary when using Secondary as seed

1.4k views Asked by At

I'm trying to connect to my MongoDB and updating a document. We're using a replica server as a seed and then we want to write a collection (specifically, update a document).

No matter what I do, every time I try to update the given document, I get the following error: NotMasterError: not master, full error: {'ok': 0.0, 'errmsg': 'not master', 'code': 10107, 'codeName': 'NotMaster'}.

I've tried changing the read pereference to Primary, changing the write concern to w: 1 but nothing seems to work.

When I debug, I can see that the client discovered all the machines in the network, including the actual master.

With a Mongo library in another language (Reactivemongo in Scala), this is done automatically but seems that with PyMongo I'm struggling. How can I ensure that the update gets forwarded to a Primary node?

If anybody can help, that'd be great :)

2

There are 2 answers

1
D. SM On

Read preference applies to reads. It has no effect on writes. All writes must be sent to the primary.

You should be connecting to replica set (also known as "discovering the topology") instead of using a direct connection, and then specifying read preference for secondary reads.

0
sid802 On

So thanks to @D. SM answer, I ensured that when I init the MongoClient, I connect to the specific replicaset by adding the keyword param: client = MongoClient(uri, replicaset='my-replica-set-name').

To find out what the replica set name is (if you don't know it), you can look at your server status and go down to the conf key repl.setName.

Thanks again :)