# Why Your MongoDB Int64 Values Change in JavaScript

> MongoDB Int64 values change in JavaScript because Number is a double, exact only up to 2^53. See where rounding happens and how to keep 64-bit integers intact.

Source: https://bussolaformongo.app/blog/mongodb-int64-precision-javascript/ · 2026-10-22

A MongoDB Int64 can silently change when it passes through JavaScript because a JavaScript `Number` is an IEEE 754 double, which represents integers exactly only up to 2^53 − 1 (`Number.MAX_SAFE_INTEGER`, 9007199254740991). Anything larger is rounded to the nearest representable double. The database is not losing data: the rounding happens when a value is parsed with `JSON.parse`, converted with `Number()`, or written back from a plain JS number. This article explains where that happens, how to reproduce it, and how to avoid it. The problem behind `mongodb int64 javascript precision` questions shows up most often with Snowflake-style IDs, nanosecond timestamps, and counters that outgrow 2^53.

## The numeric types involved

BSON has four numeric types that matter here:

| BSON type | Size | Exact range |
|---|---|---|
| Int32 | 32 bits | −2^31 to 2^31 − 1 |
| Int64 (`long`) | 64 bits | −2^63 to 2^63 − 1 |
| Double | 64 bits, IEEE 754 | integers exact only up to 2^53 |
| Decimal128 | 128 bits | 34 decimal digits |

An Int64 holds values up to about 9.2 × 10^18. A JavaScript `Number` is a Double, so integers between 2^53 and 2^63 can exist in the database but cannot all be represented as a `Number`.

## Reproducing the problem

You can see the rounding without MongoDB at all:

```js
Number.MAX_SAFE_INTEGER;                    // 9007199254740991
9007199254740992 === 9007199254740993;      // true, both become ...992
JSON.parse('{"id": 9007199254740993}').id;  // 9007199254740992
```

Now insert a real Int64 in `mongosh` and read it back:

```js
db.events.insertOne({ _id: 1, seq: NumberLong("9007199254740993") })

db.events.findOne({ _id: 1 }).seq
// Long("9007199254740993")   (the exact value is kept)
```

`mongosh` prints the exact value because it holds a `Long` object. The damage appears later, when something converts it:

```js
const doc = db.events.findOne({ _id: 1 });
doc.seq.toNumber();   // 9007199254740992, rounded
```

The same thing happens in an application. A REST handler that returns a document to a browser can emit a bare number, which the browser's `JSON.parse` then rounds, even if the server kept the value intact.

## What the Node.js driver does with Int64

The Node.js driver deserializes BSON with options that control this directly: `promoteLongs`, `promoteValues` and `useBigInt64`. Check your driver version's documentation for the exact defaults, but the behavior is:

- **`promoteLongs: true` (the default).** An Int64 that fits in a safe integer is returned as a plain `Number`. One that does not fit is returned as a `Long` object, so precision is not lost at read time. The consequence is a mixed type: the same field is a `number` for small values and a `Long` for large ones, and code like `doc.seq + 1` behaves differently for each.
- **`promoteLongs: false`.** Every Int64 comes back as a `Long`. This is consistent, but you have to call methods on it.
- **`useBigInt64: true`** (available in newer driver and `bson` releases). Every Int64 comes back as a JavaScript `bigint`, exact over the whole 64-bit range. Don't combine it with `promoteLongs: false`; the settings conflict.
- **`promoteValues: false`.** Returns wrapper objects (`Int32`, `Double`, `Long` and so on) instead of native values, preserving the BSON type of every field.

You can set these on the client:

```js
import { MongoClient } from "mongodb";

const client = new MongoClient(
  "mongodb+srv://<user>:<password>@cluster0.example.mongodb.net/",
  { useBigInt64: true }
);

const doc = await client.db("app").collection("events").findOne({ _id: 1 });
typeof doc.seq;   // "bigint"
doc.seq + 1n;     // 9007199254740994n
```

`JSON.stringify` throws `TypeError: Do not know how to serialize a BigInt` on a `bigint`. That failure is useful: it forces you to choose a representation instead of rounding silently.

## The write path is just as risky

When you write, the driver has to pick a BSON type for each JavaScript value:

```js
await coll.insertOne({ a: 5 });          // Int32
await coll.insertOne({ a: 2 ** 40 });    // Double, not Int64
await coll.insertOne({ a: 5.5 });        // Double
await coll.insertOne({ a: 123n });       // Int64
await coll.insertOne({ a: Long.fromString("9007199254740993") }); // Int64
```

A plain `Number` that is an integer fitting in 32 bits becomes an Int32; larger integers and any fraction become a Double. So `{ a: 2 ** 40 }` is stored as a Double even though it prints like an integer. Queries still compare it by numeric value, but the type matters for `$type` queries, for exactness near 2^53, and for any tool that shows the type. If a field is meant to be Int64, write it as `Long` or `bigint`, never as a computed `Number`.

A read-modify-write cycle is the classic way to corrupt data:

```js
const doc = await coll.findOne({ _id: 1 });   // seq arrives as a Long, fine
doc.seq = Number(doc.seq) + 1;                // rounded here
await coll.replaceOne({ _id: 1 }, doc);       // rounded value written back
```

Prefer server-side arithmetic, which stays in 64-bit integers:

```js
await coll.updateOne({ _id: 1 }, { $inc: { seq: Long.fromNumber(1) } });
```

In `mongosh` the equivalent is `$inc: { seq: NumberLong(1) }`. Adding a Double to an integer field produces a Double, so keep the operand an integer type.

## Extended JSON: relaxed versus canonical

When you move documents as text, the format decides whether the type survives. MongoDB's Extended JSON (EJSON) has two modes:

```text
Canonical: { "seq": { "$numberLong": "9007199254740993" } }
Relaxed:   { "seq": 9007199254740993 }
```

Canonical mode wraps every Int64 as a string inside `$numberLong`, so no parser can round it and the type is preserved. Relaxed mode emits a bare JSON number. The JSON grammar does not limit number size, but most JavaScript parsers convert it to a double and round it. If another system will consume the text, use canonical EJSON.

With the `bson` package:

```js
import { EJSON, Long } from "bson";

const doc = { seq: Long.fromString("9007199254740993") };

EJSON.stringify(doc, { relaxed: false });
// {"seq":{"$numberLong":"9007199254740993"}}

EJSON.parse('{"seq":{"$numberLong":"9007199254740993"}}', { relaxed: false });
// { seq: Long { ... } }
```

Use EJSON whenever the output will be parsed again; plain `JSON.stringify` is not a safe round trip for BSON types. For the other half of this topic, how shell syntax maps to Extended JSON in filters, see the article on writing filters that work everywhere once it is published, or check each tool's documentation for which form it expects.

## Decimal128 and money

If the real need is exact decimals, such as currency, don't use Int64 or Double. Decimal128 stores decimal digits exactly, and the Node driver returns a `Decimal128` object. Convert with `toString()`, never `Number()`:

```js
import { Decimal128 } from "bson";

const price = Decimal128.fromString("19.99");
price.toString();   // "19.99"
```

## How to find affected fields

To see which types a field actually holds, group by `$type`:

```js
db.events.aggregate([
  { $group: { _id: { $type: "$seq" }, n: { $sum: 1 } } }
])
```

A mix of `int`, `long` and `double` in one field suggests some writer is going through plain JS numbers. To list Int64 values beyond the safe range, use exact `NumberLong` literals in the filter so the shell does not round the boundary:

```js
db.events.find({
  $or: [
    { seq: { $gt: NumberLong("9007199254740991") } },
    { seq: { $lt: NumberLong("-9007199254740991") } }
  ]
}).limit(20)
```

When you are checking this away from a laptop, a viewer that shows exact types helps. [Bussola](/), a free iPhone MongoDB client, displays Int32, Int64, Double and Decimal128 as distinct types and edits them with a typed editor, so you can tell whether a value is stored as a `long` or a `double`. If you are investigating a live problem, the [on-call checklist](/blog/mongodb-on-call-checklist/) covers what else to inspect.

## Checklist

- Treat any integer above 2^53 − 1 as unsafe in a plain `Number`.
- Set `useBigInt64: true` (or `promoteLongs: false`) when a field can exceed that range.
- Write Int64 fields as `Long` or `bigint`, never as `Number(...)` results.
- Increment on the server with `$inc` instead of read, add, replace.
- Serialize with canonical EJSON, or send large IDs as strings in your own API.
- Use Decimal128 for exact decimal values and read it with `toString()`.
- Audit mixed types with `$type` and `$group`.
