How to achieve a read only connection using pymongo

我怕爱的太早我们不能终老 提交于 2019-12-11 07:13:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!