Write Results, Duplicate Keys, and Error Handling

MongoDB write methods return result information that applications should inspect. A successful request, an acknowledged write, a matched document, and a modified document are different concepts.

Insert results

An insert result can include:

  • acknowledged
  • insertedId for insertOne().
  • insertedIds for insertMany(), depending on the interface.

Update results

Update results commonly include:

  • acknowledged
  • matchedCount
  • modifiedCount
  • upsertedCount
  • upsertedId

Delete results

Delete results commonly include:

  • acknowledged
  • deletedCount

Exact result shapes can differ by driver version and operation.

Duplicate-key errors

A duplicate-key error occurs when a write violates a unique index. The _id index is a common example, but applications can create unique indexes on other fields.

For example, a unique email index may prevent multiple user records from sharing the same normalized email identifier.

Validation errors

A collection validator can reject writes that do not meet the configured rules. The application should handle validation failures appropriately rather than assuming every write is valid.

Network failures and ambiguous outcomes

A network failure may occur before the server receives a write, while processing it, or after the server has applied it but before the client receives the response.

The client may therefore be uncertain whether an operation succeeded. Blindly retrying non-idempotent operations such as increments can produce unintended results if the original write was applied.

MongoDB drivers support retryable writes for eligible operations and deployments, but retryability does not make every arbitrary business workflow exactly-once.

Error-handling strategy

  1. Validate input before issuing the write.
  2. Use appropriate unique indexes and schema validation.
  3. Inspect write results.
  4. Distinguish duplicate-key errors from validation and connectivity errors.
  5. Avoid logging credentials or sensitive document contents.
  6. Design retry behavior around the semantics of the operation.
  7. Use idempotency keys or other deduplication mechanisms when the business workflow requires them.
Inspect an update result
db.resultDemo.updateOne(
  { email: "arun@example.com" },
  {
    $set: {
      active: true
    }
  },
  {
    upsert: true
  }
);
💡 Inspect the returned result in mongosh to determine whether a document matched, whether it was modified, and whether an upsert inserted a document. The exact counts depend on the initial collection contents and the existing value.
Key Takeaways
  • Write results provide counts and identifiers useful for verification.
  • A matched document may not be modified if the requested update changes nothing.
  • Unique indexes can reject duplicate writes.
  • Collection validators can reject invalid documents.
  • Retries must account for ambiguous outcomes and whether an operation is idempotent.
Knowledge Check

Why can blindly retrying `$inc: { count: 1 }` after a network timeout be dangerous?