Starting in MongoDB 4.2, you can update a document's shard key value unless the shard key field is the immutable _id field.从MongoDB 4.2开始,您可以更新文档的分片键值,除非分片键字段是不可变的_id字段。
Important重要
When updating the shard key value更新分片键值时
You must be on a mongos. 你一定在mongos上。Do not issue the operation directly on the shard.不要直接在分片上发出操作。
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. 要更新文档的分片键值,必须在查询筛选器中包括activityid: <value>, userid: <value>。You can include additional fields in the query as appropriate.您可以根据需要在查询中包含其他字段。
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:要更新分片键值,请使用以下操作:
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警告
Starting in version 4.4, documents in sharded collections can be missing the shard key fields. 从版本4.4开始,分片集合中的文档可能会缺少分片键字段。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. 考虑在location字段上分片的sales集合。The collection contains a document with the _id12345 and the location"". 该集合包含一个_id为12345且location为""的文档。To update the field value for this document, you can run the following command:要更新此文档的字段值,可以运行以下命令: