Menu Docs

sharedCollection

shardCollection

Fragmentos a collection to distribute its documents across shards. The shardCollection command must be run against the admin 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 auxiliar sh.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.

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

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

O comando utiliza os seguintes campos:

Campo
Tipo
Descrição

shardCollection

string

O namespace da collection para fragmentar no formato <database>.<collection>.

key

documento

The document that specifies the field or fields to use as the chave de fragmento.

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

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 shardCollection command. If the collection is empty, MongoDB creates the index prior to sharding the collection if the index that can support the shard key does not already exist.

Consulte também Índices de chaves de shard

unique

booleano

Specify true to ensure that the underlying index enforces a unique constraint. Defaults to false.

You cannot specify true when using hashed shard keys.

numInitialChunks

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 numInitialChunks must result in less than 8192 per shard.

If the collection is not empty or the shard key does not contain a hashed field, the operation returns an error.

  • If sharding with presplitHashedZones: true, MongoDB attempts to evenly distribute the specified number of chunks across the zones in the cluster.

  • If sharding with presplitHashedZones: false or omitted and no zones and zone ranges are defined for the empty collection, MongoDB attempts to evenly distributed the specified number of chunks across the shards in the cluster.

  • If sharding with presplitHashedZones: false or omitted and zones and zone ranges have been defined for the empty collection, numInitialChunks has no effect.

collation

documento

Optional. If the collection specified to shardCollection has a default agrupamento, you must include a collation document with { locale : "simple" }, or the shardCollection command fails. At least one of the indexes whose fields support the shard key pattern must have the simple collation.

booleano

Optional. 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.

shardCollection with presplitHashedZones: true returns an error if any of the following are true:

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 shardCollection 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.

For detailed syntax, see Time Series Options.

Novidades na versão 5.1.

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

timeField

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 timeField.

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.

metaField

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 _id ou o mesmo que o timeseries.timeField. O campo pode ser de qualquer tipo de dados.

Embora o campo metaField seja opcional, o uso de metadados pode melhorar a otimização da query. Por exemplo, o MongoDB cria automaticamente um índice composto nos campos metaField e timeField para novas collections. Se você não fornecer um valor para este campo, os dados serão agrupados exclusivamente com base no tempo.

granularity

string

Optional. Possible values are:

  • "seconds"

  • "minutes"

  • "hours"

By default, MongoDB sets the granularity to "seconds" for high-frequency ingestion.

Manually set the granularity parameter to improve performance by optimizing how data in the time series collection is stored internally. To select a value for granularity, choose the closest match to the time span between consecutive incoming measurements.

If you specify the timeseries.metaField, consider the time span between consecutive incoming measurements that have the same unique value for the metaField field. Measurements often have the same unique value for the metaField field if they come from the same source.

If you do not specify timeseries.metaField, consider the time span between all measurements that are inserted in the collection.

If you set the granularity parameter, you can't set the bucketMaxSpanSeconds and bucketRoundingSeconds parameters.

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:

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:

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 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:

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.

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:

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

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.

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

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: