MongoDB $toDouble Operator

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
Type Conversion

What You’ll Learn

The $toDouble operator converts values to a double (64-bit floating-point number) in MongoDB aggregation pipelines. Use it to parse numeric strings and enable arithmetic on imported or mixed-type data.

01

Double Conversion

Values to float.

02

Syntax

One expression.

03

String Parsing

Text to number.

04

$project Stage

Enable math ops.

05

Use Cases

Scores, averages.

06

vs $toDecimal

Float vs exact.

Definition and Usage

In MongoDB’s aggregation framework, the $toDouble operator converts an expression to a 64-bit floating-point number (double). Imported CSV and JSON data often stores numbers as strings like "85.5" or "3.14". $toDouble parses those strings so you can use $multiply, $avg, $sum, and other numeric operators.

$toDouble is shorthand for { $convert: { input: <expression>, to: "double" } }. It is part of the type-conversion family alongside $toInt, $toDecimal, and $toString.

💡
Beginner Tip

Use $toDouble for general numeric work like scores and measurements. For currency and financial calculations where every cent must be exact, prefer $toDecimal instead.

📝 Syntax

The $toDouble operator takes one expression:

mongosh
{ $toDouble: <expression> }

Literal Examples

mongosh
{ $toDouble: "85.5" }
// Result: 85.5

{ $toDouble: 42 }
// Result: 42.0

{ $toDouble: true }
// Result: 1.0

{ $toDouble: "$score" }
// Convert the score field

Conversion Rules

  • null — returns null.
  • Double — returns the same double value.
  • String — parses numeric strings (invalid strings cause an error).
  • Integer / Long / Decimal — converts to double.
  • Booleantrue becomes 1.0, false becomes 0.0.
  • Use inside $project, $addFields, $set, or $group.

💡 $toDouble vs $toDecimal

$toDouble — binary floating point; fast; good for scores, stats, science
$toDecimal — Decimal128; exact decimal; best for currency and accounting
Example: 0.1 + 0.2 with doubles may not equal 0.3 exactly; decimals preserve precision
See the $toDecimal operator tutorial for financial math

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (type conversion)
Syntax{ $toDouble: <expression> }
Output typeDouble (64-bit float)
Equivalent{ $convert: { input: <expr>, to: "double" } }
Best forScores, measurements, averages, general math
Common stages$project, $addFields, $group
String
{
  $toDouble: "$score"
}

Parse text number

Literal
{
  $toDouble: "3.14"
}

Fixed value

Average
{
  $avg: {
    $toDouble: "$rating"
  }
}

Mean of strings

Multiply
{
  $multiply: [
    { $toDouble: "$qty" },
    { $toDouble: "$rate" }
  ]
}

Numeric math

Examples Gallery

Parse string scores, compute averages, multiply numeric fields, and compare double precision with decimal conversion.

📚 Student Scores

Start with a students collection where scores are stored as strings and convert them with $toDouble.

Sample Input Documents

Suppose you have a students collection with string scores from a CSV import:

mongosh
[
  { "_id": 1, "name": "Alice", "score": "92.5" },
  { "_id": 2, "name": "Bob",   "score": "78.0" },
  { "_id": 3, "name": "Carol", "score": "85.5" },
  { "_id": 4, "name": "Dave",  "score": "91.0" }
]

Example 1 — Convert String Score to Double

Parse the score string into a numeric double:

mongosh
db.students.aggregate([
  {
    $project: {
      name: 1,
      score: 1,
      numericScore: { $toDouble: "$score" }
    }
  }
])

How It Works

$toDouble parses numeric strings into doubles. Once converted, the field supports sorting, comparison, and arithmetic operators.

📈 Aggregations and Math

Compute averages, multiply fields, and sort by numeric values.

Example 2 — Calculate Average Score with $avg

Convert string scores before computing the class average:

mongosh
db.students.aggregate([
  {
    $group: {
      _id: null,
      averageScore: {
        $avg: { $toDouble: "$score" }
      },
      count: { $sum: 1 }
    }
  }
])

// averageScore: 86.75
// (92.5 + 78.0 + 85.5 + 91.0) / 4

How It Works

$avg requires numeric input. Wrapping the field in $toDouble converts each string score before the average is calculated.

Example 3 — Multiply Numeric Fields

Calculate a weighted score from quantity and rate fields stored as strings:

mongosh
db.metrics.aggregate([
  {
    $project: {
      label: 1,
      result: {
        $multiply: [
          { $toDouble: "$quantity" },
          { $toDouble: "$rate" }
        ]
      }
    }
  }
])

// quantity: "2.5", rate: "10" → result: 25.0

How It Works

Both operands must be numeric for $multiply. Convert each string field with $toDouble before the operation.

Example 4 — Sort by Numeric Value

Convert scores to doubles, then sort highest to lowest:

mongosh
db.students.aggregate([
  {
    $addFields: {
      numericScore: { $toDouble: "$score" }
    }
  },
  {
    $sort: { numericScore: -1 }
  },
  {
    $project: {
      name: 1,
      numericScore: 1
    }
  }
])

How It Works

Sorting string numbers alphabetically gives wrong results ("9" > "85"). Converting to double first ensures correct numeric ordering.

Example 5 — Convert Boolean to Double

Booleans convert to 1.0 (true) or 0.0 (false):

mongosh
db.settings.aggregate([
  {
    $project: {
      flag: 1,
      asNumber: { $toDouble: "$enabled" }
    }
  }
])

// enabled: true  → asNumber: 1.0
// enabled: false → asNumber: 0.0

How It Works

This is useful when you need a numeric representation of a boolean flag for charts or statistical calculations.

Bonus — Safe Conversion with $convert

When values may be invalid, use $convert with onError:

mongosh
db.students.aggregate([
  {
    $project: {
      name: 1,
      numericScore: {
        $convert: {
          input: "$score",
          to: "double",
          onError: 0,
          onNull: 0
        }
      }
    }
  }
])

// "92.5"  → 92.5
// "N/A"   → 0 (fallback)
// null    → 0

How It Works

$toDouble errors on invalid strings. $convert with onError lets the pipeline continue with a safe default.

🚀 Use Cases

  • CSV/JSON import cleanup — parse numeric strings into doubles for math and sorting.
  • Statistical analysis — compute $avg, $stdDevPop, and other numeric aggregations on string fields.
  • Sensor and measurement data — convert text readings to numbers for charts and thresholds.
  • Rating systems — parse string ratings for averaging and ranking.
  • Schema migration — transform legacy string-number fields in aggregation pipelines.

🧠 How $toDouble Works

1

MongoDB reads the expression

The input resolves from a field path, numeric string, number, boolean, or nested expression.

Input
2

Value is converted to double

Strings are parsed as numbers; integers, longs, and decimals are cast to 64-bit float.

Convert
3

A double result is returned

The output supports $add, $multiply, $avg, sorting, and comparisons.

Output
=

Numeric field ready

Use in math, aggregations, sorting, and reporting pipelines.

Conclusion

The $toDouble operator converts values to 64-bit floating-point numbers in MongoDB aggregation pipelines. It is the go-to choice for parsing numeric strings and enabling general math on mixed-type data.

For currency and financial calculations, use $toDecimal instead. For conversions with error handling, use $convert. Next in the series: $toInt.

💡 Best Practices

✅ Do

  • Use $toDouble to parse numeric strings before math operations
  • Convert before $sort when fields are stored as strings
  • Use $convert with onError for messy imported data
  • Choose $toDecimal when penny-level precision matters
  • Test with integers, decimals, null, and invalid strings

❌ Don’t

  • Use $toDouble for currency when exact cents are required
  • Assume string fields auto-convert in $multiply or $avg
  • Sort string numbers without converting first
  • Forget that invalid strings error with bare $toDouble
  • Mix unconverted strings and numbers in the same calculation

Key Takeaways

Knowledge Unlocked

Five things to remember about $toDouble

Use these points when converting values to double in MongoDB.

5
Core concepts
📝 02

{ $toDouble: x }

One argument.

Syntax
🔢 03

Parse strings

Text to number.

Input
🛠 04

$avg / $multiply

Enable math.

Usage
05

Not for money

Use $toDecimal.

Compare

❓ Frequently Asked Questions

$toDouble converts a value to a double (64-bit floating-point number) inside an aggregation pipeline. It is an aggregation expression operator used in stages like $project and $addFields.
The syntax is { $toDouble: <expression> }. The expression can be a field reference like "$score", a numeric string, or another numeric expression.
Use $toDouble for general numeric work — scores, measurements, averages — where tiny floating-point rounding differences are acceptable. Use $toDecimal for currency and financial calculations that require exact decimal precision.
$toDouble is shorthand for { $convert: { input: <expr>, to: "double" } }. Use $convert with onError when invalid values should return a fallback instead of failing the pipeline.
$toDouble returns null when the input is null. It does not throw an error for null input.

Continue the Operator Series

Move on to $toInt for integer conversion, or review $toDecimal for financial precision.

Next: $toInt →

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