Change a Document's Shard Key Value更改文档的分片键值
On this page本页内容
Starting in MongoDB 4.2, you can update a document's shard key value unless the shard key field is the immutable 从MongoDB 4.2开始,您可以更新文档的分片-key值,除非分片健字段是不可变的_id
field._id
字段。
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.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:要更新分片键值,请使用以下操作:
multi: false 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() 1 。null value, the operation must be performed either inside a transaction or as a retryable write. null 值,必须在事务内部或作为可重试写入执行该操作。 |
Starting in version 4.4, 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.从4.4版本开始,分片集合中的文档可能会缺少分片键字段。请采取预防措施,避免在更改文档的分片键值时意外删除分片键。
Example实例
Consider a 考虑一个sales
collection which is sharded on the location
field. sales
集合,它在location
字段上进行了分片。The collection contains a document with the 集合包含一个_id
12345
and the location
""
. _id
为12345
、location
为""
的文档。To update the field value for this document, you can run the following command:要更新此文档的字段值,可以运行以下命令:
db.sales.updateOne(
{ _id: 12345, location: "" },
{ $set: { location: "New York"} }
)