On this page本页内容
If a replica set member or members are associated with tags
, you can specify a tag set (array of tag specification documents) in the read preference to target those members.
To configure a member with tags, set members[n].tags
to a document that contains the tag name and value pairs. The value of the tags must be a string.
Then, you can include a tag set in the read preference to target tagged members. A tag set is an array of tag specification documents, where each tag specification document contains one or more tag/value pairs.
To find replica set members, MongoDB tries each document in succession until a match is found. See Order of Tag Matching for details.
For example, if a secondary member has the following members[n].tags
:
Then, the following tags sets can direct read operations to the aforementioned secondary (or other members with the same tags):
If the tag set lists multiple documents, MongoDB tries each document in succession until a match is found. Once a match is found, that tag specification document is used to find all eligible matching members, and the remaining tag specification documents are ignored. If no members match any of the tag specification documents, the read operation returns with an error.
Tip
To avoid an error if no members match any of the tag specifications, you can add an empty document { }
as the last element of the tag set to read from any eligible member.
For example, consider the following tag set with three tag specification documents:
First, MongoDB tries to find members tagged with both "region":
"South"
and "datacenter": "A"
.
The empty document matches any eligible member.
Tags are not compatible with mode primary
, and in general, only apply when selecting a secondary member of a set for a read operation. However, the nearest
read mode, when combined with a tag set, selects the matching member with the lowest network latency. This member may be a primary or secondary.
Mode | |
---|---|
primaryPreferred |
Specified tag set only applies if selecting eligible secondaries. |
secondary |
Specified tag set always applies. |
secondaryPreferred |
Specified tag set only applies if selecting eligible secondaries. |
nearest |
Specified tag set applies whether selecting either primary or eligible secondaries. |
For information on the interaction between the modes and tag sets, refer to the specific read preference mode documentation.
For information on configuring tag sets, see the Configure Replica Set Tag Sets tutorial.