sh.shardCollection()
Nesta página
Definição
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âmetroTipoDescriçãonamespace
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:
"hashed"
para especificar uma chave de fragmento com hash.
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 tofalse
.You cannot specify
true
when using hashed shard keys.For Shell legado mongo, you must explicitly specify the value for
unique
if you specify theoptions
document.mongosh
doesn't requireunique
when you specify theoptions
document.options
documento
Optional. A document containing optional fields, including
numInitialChunks
andcollation
.The
options
argument supports the following options:ParâmetroTipoDescriçãonumInitialChunks
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 than8192
chunks per shard. Defaults to2
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 theshardCollection
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()
withpresplitHashedZones: true
returns an error if any of the following are true:The shard key does not contain a hashed field (i.e. is not a single field hashed index or compound hashed index).
The collection has no defined zones or zone ranges.
The defined zone ranges do not meet the requirements.
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 thetimeseries
option is not specified, MongoDB uses the values that define the existing time series collection to populate thetimeseries
field.For detailed syntax, see Time Series Options.
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 |
---|---|---|
| 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 |
| 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 |
Compatibilidade
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
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.
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:
Veja também:
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 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
.
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,
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
Agrupamentos
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.
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
Simple Usage
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 } )
Usage with Options
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, anda collation of
simple
.
sh.shardCollection( "phonebook.contacts", { last_name: "hashed" }, false, { numInitialChunks: 5, collation: { locale: "simple" } } )
Veja também: