MongoDB $isNumber Operator

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 4 Examples
Type Check

What You’ll Learn

The $isNumber operator checks whether a value is a numeric BSON type. It returns true or false — useful for data validation, safe math in pipelines, and filtering documents before applying operators like $add, $abs, or $round.

01

Type Check

Test if value is numeric.

02

Syntax

One expression inside $isNumber.

03

Boolean Output

Returns true or false.

04

$expr + $match

Filter numeric fields.

05

Use Cases

Validation, safe math.

06

Not Strings

"42" returns false.

Definition and Usage

In MongoDB’s aggregation framework, the $isNumber operator evaluates an expression and returns true when the result is a numeric BSON type (int, long, double, or decimal), and false for strings, booleans, objects, arrays, null, and missing fields. This is especially helpful when imported data stores prices or quantities as strings like "19.99" instead of actual numbers.

Use $isNumber as a guard before math operators. For example, only run $add or $abs when a field is truly numeric, preventing pipeline errors on malformed documents.

💡
Beginner Tip

$isNumber is an expression operator, not a direct query filter. To filter documents in $match, wrap it in $expr: { $match: { $expr: { $isNumber: "$price" } } }. It checks BSON type, not whether a string looks like a number.

📝 Syntax

The $isNumber operator takes a single expression to evaluate:

mongosh
{ $isNumber: <expression> }

Common Patterns

mongosh
// Check a document field
{ $isNumber: "$price" }

// Filter documents where price is numeric
{ $match: { $expr: { $isNumber: "$price" } } }

// Guard before math in $cond
{ $cond: [
    { $isNumber: "$quantity" },
  { $multiply: [ "$quantity", "$unitPrice" ] },
  0
] }

Syntax Rules

  • <expression> — can be a field path ("$price"), a literal number, or another expression.
  • Returns true for int, long, double, and decimal BSON types.
  • Returns false for numeric-looking strings like "42" or "19.99".
  • Returns false for null, missing fields, arrays, objects, and booleans.
  • Use inside $project, $addFields, $cond, and $match (with $expr).

⚠️ Number Type vs Numeric String

$isNumber checks BSON type, not text content:

price: 29.99$isNumber returns true (double)
price: "29.99"$isNumber returns false (string)
price: null$isNumber returns false (null)
To convert strings: use $convert or $toDouble first

💡 Expression Operator vs Query Filter

$isNumber must be used as an aggregation expression:

$project{ priceIsNumber: { $isNumber: "$price" } } (adds boolean field)
$match{ $expr: { $isNumber: "$price" } } (filters documents)
Invalid{ price: { $isNumber: true } } (will not work)

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (type check)
Syntax{ $isNumber: <expression> }
Outputtrue or false
True forint, long, double, decimal
Common stages$project, $addFields, $cond, $match + $expr
Field check
{
  $isNumber: "$price"
}

true if price is numeric

Literal number
{
  $isNumber: 42
}

Returns true

Numeric string
{
  $isNumber: "42"
}

Returns false

$match filter
{
  $expr: {
    $isNumber: "$score"
  }
}

Keep numeric scores only

Examples Gallery

Walk through sample inventory data with mixed field types, validate numeric values with $project, and apply safe math only when types are correct.

📚 Check Numeric Fields

Start with an inventory collection where price and quantity are not always stored as numbers.

Sample Input Documents

Some documents have numeric prices, others store prices as strings, and one has a missing price field:

mongosh
[
  { "_id": ObjectId("609c26812e9274a86871bc6a"), "item": "Notebook", "price": 12.50, "quantity": 100 },
  { "_id": ObjectId("609c26812e9274a86871bc6b"), "item": "Pen Pack", "price": "8.99", "quantity": 50 },
  { "_id": ObjectId("609c26812e9274a86871bc6c"), "item": "Stapler", "price": 15.00, "quantity": "25" },
  { "_id": ObjectId("609c26812e9274a86871bc6d"), "item": "Eraser", "quantity": 200 }
]

Example 1 — Basic $isNumber on Fields

Add boolean fields showing whether price and quantity are numeric:

mongosh
db.inventory.aggregate([
  {
    $project: {
      item: 1,
      price: 1,
      quantity: 1,
      priceIsNumber: {
        $isNumber: "$price"
      },
      quantityIsNumber: {
        $isNumber: "$quantity"
      }
    }
  }
])

How It Works

  • 12.50 and 100 are real BSON numbers, so both return true.
  • "8.99" and "25" are strings — they look numeric but return false.
  • Missing price on the Eraser document also returns false.

📈 Practical Patterns

Filter valid numeric documents, compute totals safely, and flag data quality issues.

Example 2 — Filter with $match and $expr

Keep only documents where both price and quantity are numeric:

mongosh
db.inventory.aggregate([
  {
    $match: {
      $expr: {
        $and: [
          { $isNumber: "$price" },
          { $isNumber: "$quantity" }
        ]
      }
    }
  },
  {
    $project: {
      item: 1,
      price: 1,
      quantity: 1
    }
  }
])

How It Works

$and inside $expr requires both fields to pass the $isNumber check. Only fully numeric records proceed to later pipeline stages.

Example 3 — Safe Total Value with $cond

Calculate price × quantity only when both fields are numbers; otherwise return 0:

mongosh
db.inventory.aggregate([
  {
    $project: {
      item: 1,
      totalValue: {
        $cond: [
          {
            $and: [
              { $isNumber: "$price" },
              { $isNumber: "$quantity" }
            ]
          },
          {
            $multiply: [ "$price", "$quantity" ]
          },
          0
        ]
      }
    }
  }
])

How It Works

$multiply requires numeric operands. Wrapping it in $cond with $isNumber prevents errors and gives a sensible fallback when data is malformed.

Example 4 — Flag Invalid Data for Cleanup

Find documents where price should be numeric but is not:

mongosh
db.inventory.aggregate([
  {
    $project: {
      item: 1,
      price: 1,
      needsPriceFix: {
        $not: {
          $isNumber: "$price"
        }
      }
    }
  },
  {
    $match: {
      needsPriceFix: true
    }
  }
])

How It Works

$not inverts the boolean. Documents with string prices, missing prices, or null values get needsPriceFix: true, making them easy to locate in a data cleanup or migration job.

Bonus — Guard Before $abs

Apply $abs only when the field is a real number:

mongosh
db.transactions.aggregate([
  {
    $project: {
      amount: 1,
      absoluteAmount: {
        $cond: [
          { $isNumber: "$amount" },
          { $abs: "$amount" },
          null
        ]
      }
    }
  }
])

How It Works

Math operators like $abs, $add, and $round expect numeric input. Use $isNumber first to avoid pipeline failures on string or null amounts.

🚀 Use Cases

  • Schema validation — detect documents where numeric fields are stored as strings from imports or APIs.
  • Safe math pipelines — guard $add, $multiply, $abs, and $round with an $isNumber check.
  • Data cleanup — find and flag malformed records before ETL or reporting jobs.
  • Conditional processing — branch logic in $cond based on whether values are numeric.

🧠 How $isNumber Works

1

MongoDB evaluates the expression

The pipeline resolves the input — a field like "$price" or a literal value.

Input
2

$isNumber checks the BSON type

MongoDB tests whether the value is int, long, double, or decimal. Strings, arrays, and null return false.

Type check
3

The boolean result is applied

In $project, the result is stored in a field. In $match + $expr, only true documents pass.

Output
=

Safer numeric pipelines

You get reliable type checks before running math operators on inconsistent data.

Conclusion

The $isNumber operator is a focused type-checking tool for numeric data in MongoDB aggregation pipelines. It lets you confirm that a value is a real BSON number before applying math logic, which is essential when dealing with imported data or flexible schemas.

For beginners, remember: wrap any expression in { $isNumber: ... } inside a stage like $project or $cond. To filter documents, combine it with $expr in $match. Numeric strings like "42" do not count as numbers.

💡 Best Practices

✅ Do

  • Guard $add, $multiply, and $abs with $isNumber
  • Use $match + $expr to filter numeric fields
  • Flag invalid documents with $not: { $isNumber: ... } for cleanup
  • Combine with $convert when you need to coerce string numbers
  • Pair with $cond for safe fallback values

❌ Don’t

  • Use { field: { $isNumber: true } } as a plain query filter
  • Assume "19.99" passes because it looks numeric
  • Skip type checks before math on imported or legacy data
  • Confuse $isNumber with $type: "number" syntax in queries
  • Expect $isNumber to validate number ranges (use $gte / $lte)

Key Takeaways

Knowledge Unlocked

Five things to remember about $isNumber

Use these points when validating numeric fields in MongoDB.

5
Core concepts
📝 02

Simple Syntax

{ $isNumber: expr }

Syntax
🛠 03

Boolean Output

true or false.

Result
🔒 04

Safe Math

Guard before $multiply.

Pattern
05

Not Strings

"42" is false.

Edge case

❓ Frequently Asked Questions

$isNumber returns true when the evaluated expression is a numeric BSON type (int, long, double, or decimal), and false otherwise. It is an aggregation expression operator used inside stages like $project, $addFields, and $cond.
The syntax is { $isNumber: <expression> }. The expression can be a field reference like "$price" or any other aggregation expression.
No. $isNumber checks BSON type, not content. The string "42" returns false because it is stored as a string. Only actual number types (int, long, double, decimal) return true.
Use $match with $expr: { $match: { $expr: { $isNumber: "$price" } } }. The plain query form { price: { $isNumber: true } } does not work — $isNumber is an expression operator.
$isNumber returns true or false for numeric types only. $type returns the BSON type name or number (e.g. "string", "double", "int") and can identify any type, not just numbers.

Continue the Operator Series

Move on to $isoDayOfWeek for date extraction, or review $abs for absolute value math.

Next: $isoDayOfWeek →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful