Pymongo如何设置read_preference

Pymongo how to set read_preference

我们如何使 PyMongo 从最近读取?此字段 db.read_preference 现在是只读的。

from pymongo import ReplicaSetConnection
from pymongo import ReadPreference

db = ReplicaSetConnection('localhost:27017', replicaSet='rs1')['my_db']
db.read_preference = ReadPreference.NEAREST
db.tag_sets = [{'secondaries': 1}]

您需要将其添加到连接字符串中,如下所示:

db = ReplicaSetConnection('localhost:27017?readPreference=nearest', replicaSet='rs1')['my_db']

db = MongoClient("myhost:27017", read_preference=ReadPreference.NEAREST, replicaSet='rs1')['my_db']

无论出于何种原因,您使用的给定语法都失败了,它似乎是旧版 Pymongo 支持的语法。

选项 1(每个连接):

>>> from pymongo import MongoClient, ReadPreference
>>> db = MongoClient("myhost:27017", read_preference=ReadPreference.NEAREST).test
>>> db.collection.find_one({test:1})

选项 2(每个查询):

>>> db.collection.find_one({test:1},read_preference=ReadPreference.NEAREST)

PyMongo ReadPreference can also be applied at database, collection or a query level (in addition to within Connection String URI and with the MongoClient).

from pymongo import ReadPreference

# Specifying read preference at database level
db1 = client.testdb1
db2 = client.get_database('testdb2', read_preference=ReadPreference.NEAREST)

# Specifying read preference at collection level
coll2 = db1.coll1.with_options(read_preference=ReadPreference.NEAREST)

# Specifying read preference for a specific query
result = db1.coll1.with_options(read_preference=ReadPreference.NEAREST).find()

请注意,在较低级别(例如,集合)设置的读取首选项将覆盖在上一级(例如,数据库或 mongo 客户端)设置的读取首选项。