Docs 菜单

Docs 主页开发应用程序MongoDB Manual

读取偏好标签集列表

在此页面上

  • 标签匹配顺序
  • 标签集列表和读取偏好模式

如果副本集的一个或多个成员与 tags 关联,则可以在读取偏好中指定标签集列表(标签集数组),以这些成员为目标。

如需使用标签配置成员,请将 members[n].tags 设置为包含标签名称和值对的文档。标签的值必须是字符串。

{ "<tag1>": "<string1>", "<tag2>": "<string2>",... }

然后,您可以在读取偏好中包含标签集列表以定位已标记的节点。标签集列表是标签集的数组,其中每个标签集包含一个或多个标签/值对。

[ { "<tag1>": "<string1>", "<tag2>": "<string2>",... }, ... ]

为了查找副本集成员,MongoDB 会依次尝试每个文档,直到找到匹配为止。有关详细信息,请参阅标记匹配顺序

例如,如果从节点有以下 members[n].tags

{ "region": "South", "datacenter": "A" }

然后以下标签集列表就可以将读取操作指向上述从节点(或具有相同标签的其他节点):

[ { "region": "South", "datacenter": "A" }, { } ] // Find members with both tag values. If none are found, read from any eligible member.
[ { "region": "South" }, { "datacenter": "A" }, { } ] // Find members with the specified region tag. Only if not found, then find members with the specified datacenter tag. If none are found, read from any eligible member.
[ { "datacenter": "A" }, { "region": "South" }, { } ] // Find members with the specified datacenter tag. Only if not found, then find members with the specified region tag. If none are found, read from any eligible member.
[ { "region": "South" }, { } ] // Find members with the specified region tag value. If none are found, read from any eligible member.
[ { "datacenter": "A" }, { } ] // Find members with the specified datacenter tag value. If none are found, read from any eligible member.
[ { } ] // Find any eligible member.

如果标签集列表包含多个文档,MongoDB 会依次尝试每个文档,直到找到匹配为止。找到匹配后,就会使用该标签集来查找所有符合条件的匹配成员,而忽略其余的标签集。如果没有成员与任何标签集匹配,读取操作将返回错误。

提示

为了避免在没有成员符合任何标签规范时出现错误,可以添加空文档 { } 作为标签集列表的最后一个元素,以读取任何符合条件的成员。

例如,以下标签集列表包含三个标签集:

[ { "region": "South", "datacenter": "A" }, { "rack": "rack-1" }, { } ]

首先,MongoDB 会尝试查找同时标记为 "region": "South""datacenter": "A" 的成员。

{ "region": "South", "datacenter": "A" }
  • 如果找到成员,则不考虑其余标签集。相反,MongoDB 会使用此标签集来查找所有符合条件的成员。

  • 否则,MongoDB 会尝试查找带有第二个文档中指定的标签的成员。

    { "rack": "rack-1" }
    • 如果发现某个成员被标记,则不考虑剩余的标签集。相反,MongoDB 会使用此标签集来查找所有符合条件的成员。

    • 否则,将考虑第三个文档。

      { }

      空文档匹配任何符合条件的成员。

标签与模式 primary 不兼容,一般情况下,仅适用于在读取操作中选择集合的从节点时。不过,nearest 读取模式与标签集列表相结合时,会选择网络延迟最低的匹配节点。该节点可以是主节点,也可以是从节点。

模式
注意
primaryPreferred
指定的标签集列表仅在选择符合条件的从节点时适用。
指定的标签集列表始终适用。
指定的标签集列表仅在选择符合条件的从节点时适用。
无论选择主节点还是符合条件的从节点,指定的标签集列表都适用。

有关模式与标签集列表之间的交互信息,请参阅特定读取偏好模式文档

有关配置标签集列表的信息,请参阅“配置副本集标签集”教程。

← 读取偏好