$toDouble (Convert to Double)
Last updated: 2026-10-09
$toDouble (Convert to Double)
$toDouble converts a value to a BSON double. It accepts numbers, numeric strings, booleans and dates; null stays null. Typical uses: turning CSV-imported string numbers into numerics for aggregation or widening integers to floats so division keeps fractions. Strings must be valid number literals or the conversion throws. It is the $convert shortcut for to: double; prefer $toDecimal for money.
| Category | Set, Condition & Conversion |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $toDouble: <expression> }
⚙️ Parameters
| expression | A number, numeric string, boolean, or date. |
|---|
Returns:A double; null when the input is null
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $toDouble: parse a string score into a number
db.reviews.aggregate([
{ $project: {
score: { $toDouble: '$scoreStr' }
} }
])
Output:
{ '_id': 1, 'score': 4.5 }
📌 Notes
- Strings must be valid numbers like '4.5'; 'abc' throws
- double precision is limited; use $toDecimal for money
- Booleans convert to 1.0 and 0.0
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QCan the string '4.5' convert?
AYes, as long as it is a valid number literal.
QShould money use $toDouble?
APrefer $toDecimal — double suffers precision errors.
QWhat does null return?
AIt returns null.