问题
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 tried MongoReplicaSetClient
but did not get what I wanted.
Is it possible to have a read-only connection to primary node?
回答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.
回答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
来源:https://stackoverflow.com/questions/42849056/how-to-achieve-a-read-only-connection-using-pymongo