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例如,考虑一个使用messagescollection 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:要更新分片键值,请使用以下操作:
update with multi: false | db.collection.replaceOne()db.collection.updateOne()null value, the update must be performed either inside a transaction or as a retryable write.null值,必须在事务内部或作为可重试写入执行更新。 |
findAndModify | db.collection.findOneAndReplace()db.collection.findOneAndUpdate()db.collection.findAndModify()null value, the update must be performed either inside a transaction or as a retryable write.null值,必须在事务内部或作为可重试写入执行更新。 |
db.collection.bulkWrite()Bulk.find.updateOne()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集合。该集合包含一个_id为12345、location为""的文档。要更新此文档的字段值,可以运行以下命令:
db.sales.updateOne(
{ _id: 12345, location: "" },
{ $set: { location: "New York"} }
)