Error
Error Code: 211

MongoDB Error 211: Key Not Found Error

📦 MongoDB
📋

Description

MongoDB Error 211, "Key Not Found", indicates that an operation attempted to access or modify data using a key, _id, or index entry that does not exist within the specified collection or index. This typically occurs during read, update, or delete operations when the target data cannot be located.
💬

Error Message

Key Not Found
🔍

Known Causes

3 known causes
⚠️
Document Not Found
The query attempted to retrieve, update, or delete a document using an _id or specific key that does not exist in the collection.
⚠️
Incorrect Index Usage
An operation tried to utilize an index key that is not present, valid, or correctly defined for the specified index.
⚠️
Typo or Mismatch in Key/ID
The provided key, _id, or field name in the query contains a typo, incorrect casing, or does not exactly match the stored data.
🛠️

Solutions

4 solutions available

1. Check _id Value easy

Verify document with _id exists

1
Check if document exists
db.collection.findOne({ _id: ObjectId("...") })
2
List some documents
db.collection.find().limit(5)

2. Fix ObjectId Format easy

Ensure correct ObjectId type

1
Convert string to ObjectId
// Wrong:
db.collection.findOne({ _id: "507f1f77bcf86cd799439011" })

// Right:
db.collection.findOne({ _id: ObjectId("507f1f77bcf86cd799439011") })
2
Validate ObjectId string
// Check if valid 24-char hex string
const isValid = /^[0-9a-fA-F]{24}$/.test(idString);

3. Check Index Exists easy

For index operations, verify index exists

1
List indexes
db.collection.getIndexes()
2
Drop with correct name
db.collection.dropIndex("index_name")

4. Handle Document Deletion Race medium

Document deleted between find and update

1
Use findOneAndUpdate atomically
const result = db.collection.findOneAndUpdate(
  { _id: ObjectId("...") },
  { $set: { status: "updated" } },
  { returnNewDocument: true }
);

if (!result) {
  console.log("Document not found");
}
🔗

Related Errors

5 related errors