Error
Error Code: 14

MongoDB Error 14: Data Type Mismatch

📦 MongoDB
📋

Description

This error indicates that an operation attempted to use data with an incompatible BSON type. It typically occurs when querying, inserting, or updating documents where a field's value does not match the expected or existing data type.
💬

Error Message

Type Mismatch
🔍

Known Causes

4 known causes
⚠️
Mismatched Query Types
Attempting to query a document field using a value of a different BSON data type than stored, leading to comparison failures.
⚠️
Inconsistent Data Operations
Inserting or updating a document field with a value whose BSON type differs from the expected or previously stored type.
⚠️
Aggregation Pipeline Type Issues
An aggregation pipeline stage receives or produces data types that are incompatible with subsequent operations or expected outputs.
⚠️
Schema Validation Violations
An operation attempts to modify or insert data that violates the BSON type constraints specified in a collection's schema validation rules.
🛠️

Solutions

4 solutions available

1. Use Correct Type in Query easy

Match data type stored in document

1
Check document structure
db.users.findOne()
2
Query with correct type
// If age is stored as number:
db.users.find({ age: 30 })  // Not { age: "30" }

// If date is stored as Date:
db.users.find({ created: new Date("2024-01-15") })  // Not string

2. Convert Types in Update medium

Fix inconsistent types in existing data

1
Convert string to number
db.users.updateMany(
  { age: { $type: "string" } },
  [{ $set: { age: { $toInt: "$age" } } }]
);
2
Convert string to date
db.events.updateMany(
  { date: { $type: "string" } },
  [{ $set: { date: { $toDate: "$date" } } }]
);

3. Fix Aggregation Type Errors medium

Handle type mismatches in pipeline

1
Use $convert for safe conversion
db.users.aggregate([
  {
    $project: {
      age: {
        $convert: {
          input: "$age",
          to: "int",
          onError: 0,
          onNull: 0
        }
      }
    }
  }
]);

4. Check for Mixed Types easy

Find documents with wrong types

1
Find documents with specific type
// Find where age is string instead of number:
db.users.find({ age: { $type: "string" } })

// BSON type numbers:
// 1 = double, 2 = string, 3 = object, 4 = array
// 9 = date, 10 = null, 16 = int, 18 = long
🔗

Related Errors

5 related errors