# MongoServerError: shard key not found in document. Document does not contain shard key field 'shardKeyField'

- **ID:** `database/mongodb-shard-key-missing`
- **Domain:** database
- **Category:** data_error
- **Error Code:** `61`
- **Verification:** ai_generated
- **Fix Rate:** 82%

## Root Cause

A write operation to a sharded MongoDB collection targets a document that is missing the shard key field, which is required for routing to the correct shard.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| MongoDB 6.0 | active | — | — |
| MongoDB 7.0 | active | — | — |
| MongoDB 8.0 | active | — | — |
| pymongo 4.6 | active | — | — |
| mongosh 2.1 | active | — | — |

## Workarounds

1. **Update the document to include the shard key field before the write. Example in pymongo: collection.update_one({'_id': doc_id}, {'$set': {'shardKeyField': value}}, upsert=True)** (85% success)
   ```
   Update the document to include the shard key field before the write. Example in pymongo: collection.update_one({'_id': doc_id}, {'$set': {'shardKeyField': value}}, upsert=True)
   ```
2. **If the shard key is based on a hashed field, ensure all documents have that field. Use a migration script to add the field to existing documents: db.collection.updateMany({shardKeyField: {$exists: false}}, {$set: {shardKeyField: default_value}})** (80% success)
   ```
   If the shard key is based on a hashed field, ensure all documents have that field. Use a migration script to add the field to existing documents: db.collection.updateMany({shardKeyField: {$exists: false}}, {$set: {shardKeyField: default_value}})
   ```

## Dead Ends

- **Ignore the missing shard key field and retry the write operation without changes.** — The operation will fail again because the document still lacks the required shard key field. (95% fail)
- **Remove the shard key index from the collection.** — Removing the shard key index can break sharding and cause data distribution issues; it requires re-sharding the collection. (90% fail)
