Docs Menu
Docs Home
/
MongoDB Manual
/ /

Change a Document's Shard Key Value

On this page

  • Example

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 include activityid: <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-null value, the update must be performed either inside a transaction or as a retryable write.

To set to a non-null value, the update must be performed either inside a transaction or as a retryable write.

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-null value, the operation must be performed either inside a transaction or as a retryable write.

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.

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"} }
)

Tip

See also:

Back

Reshard a Collection

On this page