Menu Docs

sh.shardCollection()

sh.shardCollection(namespace, key, unique, options)

Shards a collection using the key as a the chave de fragmento. The shard key determines how MongoDB distributes the collection's documents among the shards.

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 sh.enableSharding() method to configure the database.

Importante

Método mongosh

Esta página documenta um método mongosh. Esta não é a documentação para comandos de banco de dados nem drivers específicos de linguagem, como Node.js.

Para o comando do banco de dados, consulte o comando shardCollection.

Para drivers de API do MongoDB, consulte a documentação do driver do MongoDB específica da linguagem.

sh.shardCollection() takes the following arguments:

Parâmetro
Tipo
Descrição

namespace

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">, ... }

Set the field value to either:

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

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

You cannot specify true when using hashed shard keys.

For Shell legado mongo, you must explicitly specify the value for unique if you specify the options document. mongosh doesn't require unique when you specify the options document.

options

documento

Optional. A document containing optional fields, including numInitialChunks and collation.

The options argument supports the following options:

Parâmetro
Tipo
Descrição

numInitialChunks

inteiro

Optional. Specifies the minimum number of chunks to create initially when sharding an empty collection with a hashed shard key. MongoDB then creates and balances chunks across the cluster. The numInitialChunks parameter must be less than 8192 chunks per shard. Defaults to 2 chunks 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:

documento

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.

To create a new Time series collection that is sharded, specify the timeseries option to sh.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.

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.

Esse método 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

Esse comando não é suportado em clusters M0, M2, M5 e Flex. 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

While you can change your shard key later, it is important to carefully consider your shard key choice to avoid scalability and perfomance issues.

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:

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

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, sh.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 sh.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 sh.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.

Given a collection named people in a database named records, the following command shards the collection by the zipcode field:

sh.shardCollection("records.people", { zipcode: 1 } )

The phonebook database has a collection contacts with no default agrupamento. The following example uses sh.shardCollection() to shard the phonebook.contacts with:

  • a hashed shard key on the last_name field,

  • 5 initial chunks, and

  • a collation of simple.

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

Veja também: