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 _id
field.
Important
When updating the shard key value
You must be on a
mongos
. Do not issue the operation directly on the shard.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. To update the shard key value for a document, you must includeactivityid: <value>, userid: <value>
in the query filter. 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:
Command | Method |
---|---|
update with multi: false | To set to a non- |
To set to a non- | |
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. 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- |
Warning
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.
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:
db.sales.updateOne( { _id: 12345, location: "" }, { $set: { location: "New York"} } )