MongoDB $toDouble Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $toDouble?

$toDouble is a MongoDB aggregation expression that converts a value to a double (64-bit floating-point number). It is shorthand for { $convert: { input: <expr>, to: "double" } }.

Remember
$toDouble = convert value → double

{ $toDouble: <expression> }

numbers / numeric strings → double
true → 1, false → 0
Date → millis since epoch
null / missing → null
invalid string → pipeline error

Good for scores & measurements
(money? prefer $toDecimal)
UsePrefer
General float math$toDouble
Exact decimal / money$toDecimal
Convert with onError / onNull$convert

How to Use $toDouble in MongoDB

Convert numeric strings (or mixed types), then sort, average, or filter.

  1. Choose an expression stage ($addFields or $project).
  2. Pass the number or numeric string to $toDouble.
  3. Optional: sort or aggregate on the converted double.
  4. If strings may be invalid, prefer $convert with onError.
PieceRequired?Role
$toDoubleYesConvert expression → double (or null)
ExpressionYesNumber, numeric string, bool, Date, or double
$convertNoSame conversion with error/null handling

Pseudocode

Pseudocode
for each document:
    x = evaluate(expression)
    if x is null or missing:
        result = null
    else if x is convertible (number, "26.1", bool, Date, …):
        result = double(x)
    else:
        error  // aggregation fails
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while converting to double.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $toDouble: <expression> }
Shorthand for{ $convert: { input: <e>, to: "double" } }
String example"26.1" → 26.1
Booleantrue → 1, false → 0
DateMilliseconds since Unix epoch
vs $toDecimalDouble is binary float; decimal is better for money

Live Preview

Pick an input and see the double-style result (browser demo of the same idea).

Simulates $toDouble for numeric strings and booleans (same idea as the mongosh examples below).

Result
input = "26.1"
$toDouble → 26.1

{ asDouble: 26.1 }

Worked Walkthrough — Temperature Strings

Two cities store temperature as strings. Convert them so you can sort hottest first.

Calculation
Documents:
  { city: "Delhi",  temp: "26.1" }
  { city: "Mumbai", temp: "25.4" }

$toDouble("26.1") → 26.1
$toDouble("25.4") → 25.4

Sort by degrees descending:
  Delhi (26.1) → Mumbai (25.4)

MongoDB Examples

Insert sample readings with string temperatures, convert with $toDouble, then sort. Run these in mongosh in order.

Example 1 — Sample Data

Two readings store temp as a numeric string (common with imported sensors or CSV).

mongosh
db.readings.insertMany([
  { _id: 1, city: "Delhi", temp: "26.1" },
  { _id: 2, city: "Mumbai", temp: "25.4" }
]);

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps two documents in readings. Run find() to see them:

mongosh
db.readings.find()

Read the rows like this:

FieldExamplesPlain English
_id1, 2Document id
city"Delhi", "Mumbai"Location label
temp"26.1", "25.4"Temperature stored as a string

How It Works

  1. Insert two readings. insertMany stores simple documents for the lesson.
  2. Temps are strings. MongoDB does not auto-convert "26.1" to a double on insert.
  3. Ready to convert. The next example turns those strings into doubles.

Example 2 — Convert with $toDouble

Goal: add a degrees field as a double for every reading.

mongosh
db.readings.aggregate([
  {
    $addFields: {
      degrees: { $toDouble: "$temp" }
    }
  }
]);

How It Works

  1. Read each temp string. Values come from Example 1.
  2. Convert to double. $toDouble parses base-10 numeric strings.
  3. Numbers you can sort. degrees is a real float, not text.
  4. Keep originals. $addFields adds degrees without removing temp.

Example 3 — Sort by Temperature

Convert first, then sort hottest to coolest (Delhi before Mumbai).

mongosh
db.readings.aggregate([
  {
    $addFields: {
      degrees: { $toDouble: "$temp" }
    }
  },
  {
    $sort: { degrees: -1 }
  }
]);

How It Works

  1. Same conversion. Stage one builds degrees like Example 2.
  2. Sort on the double. $sort: { degrees: -1 } orders highest first.
  3. Why convert first? Sorting raw strings can fail for values like "9.5" vs "10.0"; doubles compare numerically.
  4. Hottest first. Delhi (26.1) appears before Mumbai (25.4).

Edge Cases & Pitfalls

Check these before using $toDouble in production pipelines.

invalid

Non-numeric strings fail the pipeline

Values like "abc" or "26.1C" throw a conversion error. Strip units first (for example with $substrBytes), or use $convert with onError.

null

Null and missing become null

$toDouble returns null for null/missing inputs—it does not become zero.

money

Not ideal for currency

Binary floats can round. For money, prefer $toDecimal.

base

Only base-10 strings

Hex-style strings such as "0x6400" are not accepted. Use $convert with a base option when needed.

Performance Notes

ApproachCostBest for
$toDouble per queryPer-document convertCleaning imported numeric strings
Store doublesCheapest long-termFields you sort/avg often
$convert + onErrorSlightly more workDirty / nullable inputs

Prefer storing numeric types when you control writes. Converting on every read is fine for cleanup, but avoid repeated string→double work on hot paths.

Key Takeaways

  • Role: convert a value to a 64-bit double.
  • Use for: scores, measurements, general float math.
  • Invalid: bad strings error—use $convert for soft fails.
  • Money: prefer $toDecimal instead.

One line: $toDouble answers “turn this into a floating-point number I can sort and average.”

Frequently Asked Questions

$toDouble converts a value to a double (64-bit floating-point number) inside an aggregation pipeline. Use it in stages such as $project and $addFields.
Use $toDouble for general numeric work—scores, measurements, averages—where tiny floating-point rounding is acceptable. Use $toDecimal for currency and exact decimal math.
$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 or missing. Invalid non-numeric strings cause a conversion error.
Yes. false → 0, true → 1. A Date becomes the millisecond count since the Unix epoch as a double.
Base-10 numeric strings such as "26.1" or "-5.5". Non-decimal forms like "0x6400" are not accepted by $toDouble.

Next: $toInt

Convert values to 32-bit integers in an aggregation pipeline.

$toInt tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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.

9 people found this page helpful