sh.shardAndDistributeCollection()
Definição
sh.shardAndDistributeCollection(namespace, key, unique, options)
Shards a collection and immediately redistributes the data using the provided chave de fragmento. The immediate redistribution of data allows for faster data movement and reduced impact to workloads.
Importante
Método mongosh
Esta página documenta um método
mongosh
. Esta não é a documentação para um driver específico de idioma, como Node.js.Para drivers de API do MongoDB, consulte a documentação do driver do MongoDB específica da linguagem.
Running
sh.shardAndDistributeCollection()
inmongosh
has the same result as consecutively running theshardCollection
andreshardCollection
commands.
Parâmetros
sh.shardAndDistributeCollection()
usa os seguintes parâmetros:
Parâmetro | Tipo | necessidade | Descrição |
---|---|---|---|
| String | Obrigatório | The namespace of the collection to shard in the format
|
| Documento | Obrigatório | O documento que especifica o campo ou campos a serem usados como a chave de shard.
Set the field value to either:
Veja também: Índices de chave de fragmentação |
| Boolean | Opcional | Especifique When using hashed shard keys, you can't
specify |
| Documento | Opcional | A document containing optional fields, including
|
The options
argument supports the following options:
Parâmetro | Tipo | Descrição |
---|---|---|
| Inteiro | Specifies the initial number of chunks to create across all shards in
the cluster when sharding and resharding a collection. MongoDB then
creates and balances chunks across the cluster. The
|
| Documento | If the collection specified to |
| Boolean | Specify
|
| Documento | Specify this option to create a new sharded time series collection. Para fragmentar uma collection de séries temporais existente, omita este parâmetro. When the collection specified to Para obter uma sintaxe detalhada, consulte Opções de séries temporais. |
Considerações
The following factors can impact performance or the distribution of your data.
Chaves de fragmentação
Although you can change your shard key later, carefully consider your shard key choice to optimize scalability and perfomance.
Chaves de shard em collections de séries temporais
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:
Veja também:
Hashed shard keys
As hashed shard keys com índice hashed usam um índice hashed composto como a chave de shard.
To specify a hashed shard key field, use field: "hashed"
.
Observação
Se as migrações de chunks estiverem em andamento durante a criação de uma collection de hashed shard keys, a distribuição inicial de chunks poderá ser desigual até que o balanceador equilibre automaticamente a collection.
Veja também:
Fragmentação de zonas e distribuição inicial de chunks
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.
For an example, see Predefinir zonas e faixas de zona para uma collection vazia ou inexistente. 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 Initial Chunk Distribution with Compound Hashed Indexes.
Initial Chunk Distribution with 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
.
For an example, see Predefinir zonas e faixas de zona para uma collection vazia ou inexistente.
Veja também:
Exclusividade
If you specify unique: true
, you must create the index
before using sh.shardAndDistributeCollection()
.
Although you can have a unique Índice Composto where the shard
key is a prefix, if you use the unique
parameter, the collection must have a unique index that is on the shard
key.
Veja também:
Agrupamentos
If the collection has a default agrupamento,
the sh.shardAndDistributeCollection
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.
Você não precisa especificar a opção collation
para collections sem agrupamento. Se você especificar a opção de agrupamento para uma coleção sem agrupamento, ela não terá efeito.
Escreva preocupação
mongos
uses "majority"
for the
Escreva preocupação of the
shardCollection
command, its helper
sh.shardCollection()
, and the
sh.shardAndDistributeCollection()
method.
Exemplos
The following examples show how you can use the
sh.shardAndDistributeCollection()
method with or without optional
parameters.
Simple Usage
A database named records
contains a collection named people
. The
following command shards the collection by the zipcode
field and
immediately redistributes the data in the records.people
collection:
sh.shardAndDistributeCollection("records.people", { zipcode: 1 } )
Usage with Options
The phonebook
database has a contacts
collection with no
default agrupamento. The
following example uses sh.shardAndDistributeCollection()
to shard and
redistribute the phonebook.contacts
collection with:
uma Chave de fragmento com hash on the
last_name
field.5
initial chunks.simple
collation.
sh.shardAndDistributeCollection( "phonebook.contacts", { last_name: "hashed" }, false, { numInitialChunks: 5, collation: { locale: "simple" } } )