Database Manual / Sharding / Shard Keys

Change a Document's Shard Key Value更改文档的分片键值

You can update a document's shard key value unless the shard key field is the immutable _id field.您可以更新文档的分片键值,除非分片键字段是不可变的_id字段。

Important

When updating the shard key value更新分片键值时

  • You must be on a mongos. Do not issue the operation directly on the shard.必须在mongos上运行。不要直接在分片上执行操作。
  • You must run either in a transaction or as a retryable write.必须在事务中运行或作为可重试写入运行。
  • You must include an equality condition on the full shard key in the query filter. 您必须在查询筛选器中的完整分片键上包含相等条件。For example, consider a messages collection that uses { activityid: 1, userid : 1 } as the shard key.例如,考虑一个使用{ activityid: 1, userid : 1 }作为分片键的messages集合。 To update the shard key value for a document, you must include activityid: <value>, userid: <value> in the query filter. You can include additional fields in the query as appropriate.要更新文档的分片键值,您必须在查询筛选器中包含activityid: <value>, userid: <value>。您可以根据需要在查询中包含其他字段。

See also the specific write command/methods for additional operation-specific requirements when run against a sharded collection.另请参阅特定的写入命令/方法,了解对分片集合运行时的其他特定操作要求。

To update a shard key value, use the following operations:要更新分片键值,请使用以下操作:

Command命令Method方法
update with multi: falsedb.collection.replaceOne()
db.collection.updateOne()
To set to a non-null value, the update must be performed either inside a transaction or as a retryable write.要设置为非null值,必须在事务内部或作为可重试写入执行更新。
findAndModifydb.collection.findOneAndReplace()
db.collection.findOneAndUpdate()
db.collection.findAndModify()
To set to a non-null value, the update must be performed either inside a transaction or as a retryable write.要设置为非null值,必须在事务内部或作为可重试写入执行更新。
db.collection.bulkWrite()
Bulk.find.updateOne()
If the shard key modification results in moving the document to another shard, you cannot specify more than one shard key modification in the bulk operation; the batch size has to be 1.如果分片键的修改导致文档移动到另一个分片,则在批量操作中不能指定多个分片键修改;批量大小必须为1。
If the shard key modification does not result in moving the document to another shard, you can specify multiple shard key modification in the bulk operation.如果分片键的修改不会导致文档移动到另一个分片,则可以在批量操作中指定多个分片键修改。
To set to a non-null value, the operation must be performed either inside a transaction or as a retryable write.要设置为非null值,必须在事务内部或作为可重试写入执行该操作。

Warning

Documents in sharded collections can be missing the shard key fields. Take precaution to avoid accidentally removing the shard key when changing a document's shard key value.分片集合中的文档可能缺少分片键字段。采取预防措施,避免在更改文档的分片键值时意外删除分片键。

Example示例

Consider a sales collection which is sharded on the location field. The collection contains a document with the _id 12345 and the location "". To update the field value for this document, you can run the following command:考虑在location字段上分片的sales集合。该集合包含一个_id12345location""的文档。要更新此文档的字段值,可以运行以下命令:

db.sales.updateOne(
{ _id: 12345, location: "" },
{ $set: { location: "New York"} }
)