# MongoServerError: shard key not found in document for namespace mydb.mycollection

- **ID:** `mongodb/shard-key-not-found-in-document`
- **Domain:** mongodb
- **Category:** data_error
- **Verification:** ai_generated
- **Fix Rate:** 90%

## Root Cause

An insert or update operation attempted to modify a document in a sharded collection without including the shard key field.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| MongoDB 4.4 | active | — | — |
| MongoDB 5.0 | active | — | — |
| MongoDB 6.0 | active | — | — |
| MongoDB 7.0 | active | — | — |

## Workarounds

1. **Modify the application code to always include the shard key field in insert and update operations: `db.mycollection.insert({ _id: ObjectId(), shardKeyField: value, ...otherFields })`** (90% success)
   ```
   Modify the application code to always include the shard key field in insert and update operations: `db.mycollection.insert({ _id: ObjectId(), shardKeyField: value, ...otherFields })`
   ```
2. **Use `updateOne` with `upsert: true` and include the shard key in the filter to ensure it's present.** (85% success)
   ```
   Use `updateOne` with `upsert: true` and include the shard key in the filter to ensure it's present.
   ```

## Dead Ends

- **** — This removes the benefit of sharding; the real fix is to include the shard key in all operations. (95% fail)
- **** — MongoDB does not support default values for shard keys; the field must be explicitly present in the document. (100% fail)
