Skip to content Skip to sidebar Skip to footer

How To Achieve A Read Only Connection Using Pymongo

How to achieve a read-only connection to the secondary nodes of the MongoDB. I have a primary node and two secondary nodes. I want a read-only connection to secondary nodes. I tri

Solution 1:

You'll want to specify a Read Preference on your queries. A read preference of Secondary Preferred will send queries to a Secondary node but will fall back to the Primary in the event that a Secondary is not available.

The read preference in pymongo is configured in the MongoClient:

>>> client = MongoClient(
...     'localhost:27017',
...     replicaSet='foo',
...     readPreference='secondaryPreferred')
>>> client.read_preference
SecondaryPreferred(tag_sets=None)

More information (and source of above) can be found here.


Solution 2:

Secondaries are read-only by default. However, you can specify the read preference to read from secondaries. By default, it reads from the primary.

This can be achieved using readPreference=secondary in connection string


Post a Comment for "How To Achieve A Read Only Connection Using Pymongo"