如何使用pymongo实现只读连接 [英] How to achieve a read only connection using pymongo
问题描述
如何实现与MongoDB辅助节点的只读连接. 我有一个主节点和两个辅助节点.我想要与次要节点的只读连接.
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.
我尝试了MongoReplicaSetClient
,但没有得到我想要的东西.
可以与主节点建立只读连接吗?
I tried MongoReplicaSetClient
but did not get what I wanted.
Is it possible to have a read-only connection to primary node?
推荐答案
您将要指定阅读查询. 次要首选的读取首选项将发送查询到次要节点,但如果次要节点不可用,则会回退到主要节点.
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.
在pymongo中的读取首选项在MongoClient中配置:
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.
这篇关于如何使用pymongo实现只读连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!