sharedCollection
Definição
shardCollection
Fragmentos a collection to distribute its documents across shards. The
shardCollection
command must be run against theadmin
database.Observação
Alterado na versão 6.0.
Starting in MongoDB 6.0, sharding a collection does não require you to first run the
enableSharding
command to configure the database.Dica
Em
mongosh
, esse comando também pode ser executado por meio do método auxiliarsh.shardCollection()
.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.
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
Para executar shardCollection
, utilize o método db.runCommand( { <command> } )
.
O comando tem o seguinte formato:
db.adminCommand( { shardCollection: "<database>.<collection>", key: { <field1>: <1|"hashed">, ... }, unique: <boolean>, numInitialChunks: <integer>, presplitHashedZones: <boolean>, collation: { locale: "simple" }, timeseries: <object> } )
Campos de comando
O comando utiliza os seguintes campos:
Campo | Tipo | Descrição |
---|---|---|
| string | O namespace da collection para fragmentar no formato |
| documento | The document that specifies the field or fields to use as the chave de fragmento.
Defina os valores do campo como:
chave de fragmento must be
supported by an index. Unless the collection is empty, the
index must exist prior to the Consulte também Índices de chaves de shard |
| booleano | Specify You cannot specify |
| inteiro | Specifies the initial number of chunks to create across all shards in
the cluster when sharding an empty collection with a
hashed shard key. MongoDB
will then create and balance chunks across the cluster. The
If the collection is not empty or the shard key does not contain a hashed field, the operation returns an error.
|
| documento | Optional. If the collection specified to |
booleano | Optional. Specify
| |
objeto | Optional. Specify this option to create a new sharded time series collection. To shard an existing time series collection, omit this parameter. When the collection specified to For detailed syntax, see Time Series Options. Novidades na versão 5.1. |
Time Series Options
Novidades na versão 5.1.
To create a new Time series collection that is sharded, specify the
timeseries option to
shardCollection
.
The timeseries option takes the following fields:
Campo | Tipo | Descrição |
---|---|---|
| string | Obrigatório. O nome do campo que contém a data em cada documento da série temporal. Os documentos em uma collection de séries temporais devem ter uma data BSON válida como o valor do A partir do MongoDB 8.0, o uso de |
| string | Opcional. O nome do campo que contém metadados em
cada documento de série temporal. Os metadados no campo especificado devem ser dados utilizados para rotular uma série exclusiva de documentos. Os metadados raramente devem mudar. O nome do campo especificado não pode ser Embora o campo |
| string | Optional. Possible values are:
By default, MongoDB sets the Manually set the If you specify the If you do not specify If you set the |
Considerações
Chaves de fragmentação
While you can change your shard key later, it is important to carefully consider your shard key choice to avoid scalability and perfomance issues.
Veja também:
Shard Keys on Time Series Collections
Ao fragmentar coleções de série temporal, você só pode especificar os seguintes campos na chave de fragmento:
O
metaField
Subcampos de
metaField
O
timeField
Você pode especificar combinações desses campos na chave do fragmento. Nenhum outro campo, incluindo _id
, é permitido no padrão da chave de fragmento.
Quando você especifica a chave de fragmento:
metaField
pode ser a:timeField
deve ser:Uma chave fragmentada de longo alcance
No final do padrão de chave de fragmento
Dica
Evite especificar apenas o timeField
como a chave de fragmento. Como o timeField
aumenta monotonicamente, isso pode fazer com que todas as gravações apareçam em um único bloco dentro do cluster. Idealmente, os dados são distribuídos uniformemente entre os blocos.
Para saber como escolher melhor uma chave de fragmento, consulte:
A partir do MongoDB 8.0, o uso de timeField
como uma chave de fragmento em uma coleção de séries temporais será descontinuado.
Hashed Shard Keys
Hashed shard keys use a hashed index or a compound hashed index as the shard key.
Use the form field: "hashed"
to specify a hashed shard key field.
Observação
If chunk migrations are in progress while creating a hashed shard key collection, the initial chunk distribution may be uneven until the balancer automatically balances the collection.
Veja também:
Zone Sharding and Initial Chunk Distribution
The shard collection operation (i.e. shardCollection
command and the sh.shardCollection()
helper) can perform
initial chunk creation and distribution for an empty or a
non-existing collection if zones and zone ranges have been defined for the collection. Initial
chunk distribution allows for a faster setup of zoned sharding.
After the initial distribution, the balancer manages the chunk
distribution going forward per usual.
See Pre-Define Zones and Zone Ranges for an Empty or Non-Existing Collection for an example. If sharding a
collection using a ranged or single-field hashed shard key, the
numInitialChunks
option has no effect if zones and zone ranges have
been defined for the empty collection.
To shard a collection using a compound hashed index, see Zone Sharding and Compound Hashed Indexes.
Zone Sharding and Compound Hashed Indexes
MongoDB oferece suporte à fragmentação de coleção em índices compostos com hash. Ao fragmentar uma coleção vazia ou inexistente usando uma chave de fragmento composta com hash, aplicam-se requisitos adicionais para que o MongoDB execute a criação e a distribuição inicial da parte.
The numInitialChunks
option has no effect if zones and zone ranges
have been defined for the empty collection and
presplitHashedZones is
false
.
Consulte Predefinir zonas e faixas de zona para uma collection vazia ou não existente para ver um exemplo.
Veja também:
Uniqueness
If specifying unique: true
:
If the collection is empty,
shardCollection
creates the unique index on the shard key if such an index does not already exist.If the collection is not empty, you must create the index first before using
shardCollection
.
Embora possa existir um índice composto exclusivo onde a chave de fragmentação é um prefixo, se você utilizar o parâmetro unique
, a collection deverá ter um índice exclusivo que esteja na chave de fragmentação.
See also Sharded Collection and Unique Indexes
Agrupamentos
If the collection has a default agrupamento,
the shardCollection
command must include a collation
parameter with the
value { locale: "simple" }
. For non-empty collections with a
default collation, you must have at least one index with the simple
collation whose fields support the shard key pattern.
You do not need to specify the collation
option for collections
without a collation. If you do specify the collation option for
a collection with no collation, it will have no effect.
Escreva preocupação
mongos
uses "majority"
for the
Escreva preocupação of the
shardCollection
command, its helper
sh.shardCollection()
, and the
sh.shardAndDistributeCollection()
method.
Exemplo
The following operation enables sharding for the people
collection
in the records
database and uses the zipcode
field as the
chave de fragmento:
db.adminCommand( { shardCollection: "records.people", key: { zipcode: 1 } } )
Veja também: