updateZoneKeyRange
Definição
updateZoneKeyRange
The
updateZoneKeyRange
administrative command can either create or remove the association between a range of shard key values and a zona.You can run
updateZoneKeyRange
database command and its helperssh.updateZoneKeyRange()
andsh.addTagRange()
on an unsharded collection or a non-existing collection.Dica
Em
mongosh
, esse comando também pode ser executado por meio do método auxiliarsh.updateZoneKeyRange()
.Os métodos auxiliares são práticos para os usuários
mongosh
, mas podem não retornar o mesmo nível de informações que os comandos do banco de dados. Nos casos em que a praticidade não for necessária ou os campos de retorno adicionais forem necessários, use o comando de banco de dados.Para executar
updateZoneKeyRange
, use o métododb.runCommand( { <command> } )
.You must run
addShardToZone
on the admin database.
Compatibilidade
Esse comando está disponível em implantações hospedadas nos seguintes ambientes:
MongoDB Atlas: o serviço totalmente gerenciado para implantações do MongoDB na nuvem
Importante
Este comando não é suportado em instâncias sem servidor. Para obter mais informações, consulte Comandos não suportados.
MongoDB Enterprise: a versão autogerenciada e baseada em assinatura do MongoDB
MongoDB Community: uma versão com código disponível, de uso gratuito e autogerenciada do MongoDB
Sintaxe
O comando tem a seguinte sintaxe:
db.adminCommand( { updateZoneKeyRange: <string>, min: <document>, max: <document>, zone: <string> | <null> } )
Campos de comando
O comando utiliza os seguintes campos:
Parâmetro | Tipo | Descrição |
---|---|---|
| string | The namespace of the collection to associate with the range. The collection must be sharded for the command to succeed. |
| documento | O limite inferior inclusivo do intervalo de valores de chave de fragmento . Especifique cada campo da chave de fragmento na forma de To use hashed sharding, the field value of |
| documento | O limite superior exclusivo do intervalo de valores da chave de fragmento . Especifique cada campo da chave de fragmento na forma de To use hashed sharding, the field value of |
| string | The name of the zone to associate with the range bounded by the
If the value does not match an existing zone, the command fails. Specify |
Comportamento
If no zone range matches the minimum and maximum bounds passed to
updateZoneKeyRange
, nothing is removed.
Emita updateZoneKeyRange
somente quando conectado a uma instância mongos
.
mongosh
provides two helper methods:
sh.updateZoneKeyRange()
for adding a range of shard key values to a zone.sh.removeRangeFromZone()
for removing a range of shard key values from a zone.
You cannot create a range of shard key values whose lower and upper boundaries
overlap with an existing range for the sharded collection. For example, given
an existing range of 1
to 10
, you cannot create a new range of 5
to 20
, as the new range would overlap with the existing range.
A zone can have multiple ranges of data associated with it, but a range can at most be associated with a single zone.
When removing the association between a range and a zone,
updateZoneKeyRange
does not remove the zone. Use the
removeShardFromZone
command to remove the association between a
zone and a shard.
Consulte a página do manual de zonas para obter mais informações sobre zonas em clusters fragmentados.
Initial Chunk Distribution for Empty or Non-Existing Collections
If you are considering performing zone sharding
on an empty or non-existent collection, use
updateZoneKeyRange
to create the zones and zone ranges
before sharding the collection (since 4.0.2). Starting in version
4.0.3, creating zones and zone ranges on empty or non-existing
collections allows MongoDB to optimize the initial chunk creation and
distribution process when sharding the collection. This optimized
process supports faster setup of zoned sharding with less balancer
overhead than creating zones after sharding. The balancer performs all chunk management after the optimized
initial chunk creation and distribution.
For an example of defining zones and zone ranges for initial chunk distribution, see Pre-Define Zones and Zone Ranges for an Empty or Non-Existing Collection.
Initial Chunk Distribution with Compound Hashed Shard Keys
MongoDB supports sharding collections on compound hashed indexes. MongoDB can perform optimized initial chunk creation and distribution when sharding the empty or non-existing collection on a compound hashed shard key.
If the hashed field is the prefix of the shard key (i.e. the first field in the shard key), all of the following must be true for MongoDB to perform initial chunk creation and distribution:
The collection has a single zone range with
MinKey
for all lower-bound fields andMaxKey
for all upper-bound fields.sh.shardCollection()
specifies the presplitHashedZones: true option.
If the hashed field is não the prefix of the shard key (i.e. the shard key has one or more non-hashed leading fields), all of the following must be true for MongoDB to perform initial chunk creation and distribution:
The collection has one zone range for each combination of distinct prefix field values (i.e. all fields preceding the hashed field).
For the lower-bound of each zone range, specify
MinKey
for the hashed field and all subsequent fields.For each zone range, at least one upper-bound prefix field must differ from its lower-bound counterpart.
sh.shardCollection()
specifies the presplitHashedZones: true option.
For a more complete example of defining zones and zone ranges for initial chunk distribution on a compound hashed shard key, see Pre-Define Zones and Zone Ranges for an Empty or Non-Existing Collection.
Balancer
After successfully running updateZoneKeyRange
, there may be chunk
migrations during the next balancer round.
After adding a range to a zone, the balancer must first run in order to migrate any chunks whose ranges are covered by the zone to shards inside of that zone. Until balancing completes, some chunks may reside on the wrong shard given the configured zones for the sharded cluster.
A remoção da associação entre uma faixa e uma zona remove as restrições que mantêm as partes cobertas pela faixa nos shards dentro dessa zona. Durante a próxima rodada do balanceador, o balanceador pode migrar partes que foram cobertos anteriormente pela zona.
Consulte a documentação do balanceador de cluster fragmentado para obter mais informações sobre como as migrações funcionam em um cluster fragmentado.
Limites
As faixas de zona estão sempre inclusas no limite inferior e exclusivas do limite superior.
Dropped Collections
A eliminação de uma coleção exclui seus intervalos de zonas/tags associados.
In earlier versions, MongoDB does not remove the tag associations for a dropped collection, and if you later create a new collection with the same name, the old tag associations will apply to the new collection.
Segurança
Para clusters fragmentados em execução com autenticação, você deve autenticar como:
um usuário cujos privilégios incluem as ações especificadas em várias coleções no banco de dados
config
:ou, alternativamente,
um usuário cujos privilégios incluem
enableSharding
no recurso do cluster .
The clusterAdmin
or clusterManager
built-in roles have
the appropriate permissions for issuing updateZoneKeyRange
. See
the documentation page for Controle de acesso com base em função
for more information.
Exemplo
Given a sharded collection exampledb.collection
with a shard key of { a
: 1 }
, the following operation creates a range with a lower bound of 1
and an upper bound of 10
on the alpha
zone:
admin = db.getSiblingDB("admin") admin.runCommand( { updateZoneKeyRange : "exampledb.collection", min : { a : 1 }, max : { a : 10 }, zone : "alpha" } )
The following operation removes the previously created range by passing
null
to the zone
field.
admin = db.getSiblingDB("admin") admin.runCommand( { updateZoneKeyRange : "exampledb.collection", min : { a : 1 }, max : { a : 10 }, zone : null } )
Os min
e max
devem corresponder exatamente aos limites do intervalo alvo. A operação a seguir tenta remover o intervalo criado anteriormente, mas especifica { a : 0 }
como o limite min
:
admin = db.getSiblingDB("admin") admin.runCommand( { updateZoneKeyRange : "exampledb.collection", min : { a : 0 }, max : { a : 10 }, zone : null } )
While the range of { a : 0 }
and { a : 10 }
encompasses the existing
range, it is not an exact match and therefore updateZoneKeyRange
does not remove anything.
Chave de shard composta
Given a sharded collection exampledb.collection
with a shard key of { a
: 1, b : 1 }
, the following operation creates a range covering the lower
bound of { a: 1, b : 1 }
and an upper bound of { a : 10, b : 10}
and
associates it with the alpha
zone:
admin = db.getSiblingDB("admin") admin.runCommand( { updateZoneKeyRange : "exampledb.collection", min : { a : 1, b : 1 }, max : { a : 10, b : 10 }, zone : "alpha" } )