Menu Docs

sh.shardAndDistributeCollection()

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() in mongosh has the same result as consecutively running the shardCollection and reshardCollection commands.

sh.shardAndDistributeCollection() usa os seguintes parâmetros:

Parâmetro
Tipo
necessidade
Descrição

namespace

String

Obrigatório

The namespace of the collection to shard in the format "<database>.<collection>".

key

Documento

Obrigatório

O documento que especifica o campo ou campos a serem usados como a chave de shard.

{ <field1>: <1|"hashed">, ... }

Set the field value to either:

Veja também: Índices de chave de fragmentação

unique

Boolean

Opcional

Especifique true para garantir que o índice subjacente imponha uma restrição exclusiva. O padrão é false.

When using hashed shard keys, you can't specify true.

options

Documento

Opcional

A document containing optional fields, including numInitialChunks and collation.

The options argument supports the following options:

Parâmetro
Tipo
Descrição

numInitialChunks

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 numInitialChunks parameter must result in less than 8192 per shard. Defaults to 1000 chunks per shard.

collation

Documento

If the collection specified to shardAndDistributeCollection() has a default agrupamento, you must include a collation document with { locale : "simple" }, or the shardAndDistributeCollection() method fails.

presplitHashedZones

Boolean

Specify true to perform initial chunk creation and distribution for an empty or non-existing collection based on the defined zones and zone ranges for the collection. For hashed sharding only.

shardAndDistributeCollection() with presplitHashedZones: true returns an error if any of the following are true:

timeseries

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 shardAndDistributeCollection is a time series collection and the timeseries option is not specified, MongoDB uses the values that define the existing time series collection to populate the timeseries field.

Para obter uma sintaxe detalhada, consulte Opções de séries temporais.

The following factors can impact performance or the distribution of your data.

Although you can change your shard key later, carefully consider your shard key choice to optimize scalability and perfomance.

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:

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:

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:

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.

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:

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:

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.

mongos uses "majority" for the Escreva preocupação of the shardCollection command, its helper sh.shardCollection(), and the sh.shardAndDistributeCollection() method.

The following examples show how you can use the sh.shardAndDistributeCollection() method with or without optional parameters.

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 } )

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:

sh.shardAndDistributeCollection(
"phonebook.contacts",
{ last_name: "hashed" },
false,
{
numInitialChunks: 5,
collation: { locale: "simple" }
}
)