cursor.readPref()

在本页面

Definition

  • cursor. readPref(* mode tagSet *)
    • readPref()附加到光标以控制 Client 端如何将查询路由到副本集的成员。

Note

从数据库中检索任何文档之前,必须将readPref()应用于光标。

Parameters

ParameterTypeDescription
modestring下列read preference模式之一:primaryprimaryPreferredsecondarysecondaryPreferrednearest
tagSet文件阵列可选的。 tag set用于将读取定向到具有指定标签的成员。如果使用primary,则tagSet不可用。


有关详细信息,请参见Tag Set

cursor.setReadPref()不支持maxStalenessSeconds选项的读取首选项。

Example

以下操作使用读取首选项模式将读取定向到辅助成员。

db.collection.find({ }).readPref( "secondary")

要使用特定标签定位次级标签,请包含标签集数组:

db.collection.find({ }).readPref(
   "secondary",
   [
      { "datacenter": "B" },    // First, try matching by the datacenter tag
      { "region": "West"},      // If not found, then try matching by the region tag
      { }                       // If not found, then use the empty document to match all eligible members
   ]
)

在辅助选择过程中,MongoDB 尝试首先查找带有datacenter: "B"标签的辅助成员。

  • 如果找到,则 MongoDB 会将符合条件的次级限制为带有datacenter: "B"标签的次级,并忽略其余标签。

  • 如果未找到,则 MongoDB 尝试使用"region": "West"标签查找辅助成员。

  • 如果找到,则 MongoDB 会将合格的次级限制为带有"region": "West"标签的次级。

    • 如果未找到,则 MongoDB 将使用任何合格的辅助数据库。

有关详情,请参见标签匹配 Sequences