---
id: I0085
title: "MongoDB Long and Decimal128 amounts"
url: https://carbium.sh/library/integrate/mongodb-long-and-decimal128-amounts
collection: Integrations
category: Document and key-value stores
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# MongoDB Long and Decimal128 amounts

A Node script reads a mint's 8-byte supply from the account data as a BigInt, checks it against getTokenSupply, and prints the exact value, the digits a JavaScript number loses, and the Long and Decimal128 documents for MongoDB.

## Where the digits are lost

A u64 runs to 18,446,744,073,709,551,615. A JavaScript `number` is a 64-bit float and holds every integer exactly only up to 2^53 - 1, which is 9,007,199,254,740,991. Past that, the representable values sit two apart, then four, then eight, so a decoded amount rounds to its nearest neighbour and prints as a clean integer with the wrong last digits. Nothing throws and no log line marks it.

Token amounts get there sooner than people expect, because the chain stores them in the smallest unit. A mint with 9 decimals passes 2^53 at roughly 9 million tokens. A mint with 5 decimals passes it at roughly 90 billion. Supplies and pool reserves are the usual first casualties, and a sum of many small balances crosses the line even when each balance is safe.

| Type | Exact range | Holds a u64? |
|---|---|---|
| Number (double) | Integers up to 9,007,199,254,740,991 | No |
| Long (int64) | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 | Up to half of the u64 range |
| Decimal128 | 34 significant decimal digits | Yes, a u64 has at most 20 |

MongoDB compares and sorts all three numerically, so a field that mixes them still answers range queries. It stays a trap, since each value then keeps or loses digits by its own type.

## Reading the eight bytes as a BigInt

An SPL mint account is 82 bytes. The supply is the 8 bytes at offset 36, after a 4-byte option tag and the 32-byte mint authority, and the decimals are the byte at offset 44. Token-2022 mints begin with the same layout. A token account puts its amount at offset 64, after the 32-byte mint and the 32-byte owner.

Ask `getAccountInfo` for `base64`, decode the string into bytes, and read with `DataView.getBigUint64(offset, true)`. The second argument is the little-endian flag. Leave it out and the same eight bytes read big-endian, which gives a huge number that looks like a supply. When the bytes sit in a Node `Buffer`, build the view with the buffer's `byteOffset`, because small buffers share a pool and offset zero can be another buffer's memory.

A wrong offset still returns a plausible 64-bit number, so check it. `getTokenSupply` returns the same integer as a decimal string in `amount`, and the script compares the two. A match shows that the offset and the byte order are right for this account.

> The `jsonParsed` encoding also returns token amounts as strings, which are safe to hand to `BigInt`. The byte route is for accounts the node has no parser for, where you hold the layout yourself.

## Choosing Long or Decimal128

Pick by field, with the range of that field in hand.

- `Long` fits a field that stays below 9,223,372,036,854,775,807. A token balance never exceeds its mint's supply, so if the supply fits, every balance of that mint fits. A Long takes 8 bytes and indexes and sorts as an integer. `$sum` over Longs stays a long until the total overflows, and then MongoDB returns a double and the digits go again.
- `Decimal128` fits any u64 and any total you will compute from them. It takes 16 bytes and holds 34 significant digits, so `$sum` stays exact even over a million values near the u64 maximum.
- A string keeps every digit and compares as text, so `$gt`, `$sort` and `$sum` give wrong answers or none. Keep a string for a copy you only display.

A field that is only stored and matched can be a Long when its range is known. A field that is summed, ranged, or read from a layout with no known bound takes Decimal128. Query values need the same care. A shell filter written `{ supply: { $gt: 9007199254740993 } }` hands the server a double, so write the bound as `NumberLong("9007199254740993")` or `NumberDecimal("9007199254740993")`.

## The script

Install the client with `npm install @solana/kit@8.6.0` and set `"type": "module"` in `package.json`. Node 24 strips the types on load. The script needs `CARBIUM_KEY`, and `CARBIUM_RPC_URL` is optional. It takes a mint address as its first argument and reads the BONK mint when given none, a mint whose raw supply is far past 2^53.

The account read and the supply read go out together in one `Promise.allSettled`, so one failed call is printed and the other still lands. Both read at confirmed commitment. A `getAccountInfo` call costs [10 cells](https://carbium.sh/docs/rpc), at 0.5 req/s on Free, 15 on Dev, 50 on Business and 400 on Pro. A rate class absorbs bursts up to [1,024 cells](https://carbium.sh/docs/limits), so the account read of a single run sits well inside it on any plan.

`main.ts` (run: `node main.ts`)

```ts
// I0085 · MongoDB Long and Decimal128 amounts
// https://carbium.sh/library/integrate/mongodb-long-and-decimal128-amounts
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { address, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";

const key = process.env.CARBIUM_KEY;
if (!key) {
  console.error("Set CARBIUM_KEY.");
  process.exit(1);
}
const rpc = createSolanaRpcFromTransport(
  createDefaultRpcTransport({
    url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",
    headers: { "x-api-key": key },
  }),
);
// Default: the BONK mint, whose raw supply is far past 2^53.
const mint = address(process.argv[2] ?? "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263");
const SUPPLY_OFFSET = 36; // 4-byte option tag + 32-byte mint authority
const LONG_MAX = 2n ** 63n - 1n;
const why = (e: unknown) => (e instanceof Error ? e.message : String(e));

const [acct, supply] = await Promise.allSettled([
  rpc.getAccountInfo(mint, { commitment: "confirmed", encoding: "base64" }).send(),
  rpc.getTokenSupply(mint, { commitment: "confirmed" }).send(),
]);

const info = acct.status === "fulfilled" ? acct.value.value : null;
if (!info) {
  console.error(acct.status === "rejected" ? `getAccountInfo failed: ${why(acct.reason)}` : "mint account not found");
  process.exit(1);
}
const bytes = Buffer.from(info.data[0], "base64");
if (bytes.length < 82) {
  console.error(`account holds ${bytes.length} bytes, not a mint`);
  process.exit(1);
}
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const raw = view.getBigUint64(SUPPLY_OFFSET, true); // true = little-endian
const decimals = bytes[44];

console.log(`exact u64      ${raw} (decimals ${decimals})`);
console.log(`Number()       ${Number(raw)} ${BigInt(Number(raw)) === raw ? "exact" : "digits lost"}`);
if (supply.status === "fulfilled") {
  const rpcAmount = BigInt(supply.value.value.amount);
  console.log(`getTokenSupply ${rpcAmount} ${rpcAmount === raw ? "matches the bytes" : "differs from the bytes"}`);
} else {
  console.error(`getTokenSupply failed: ${why(supply.reason)}`);
}

const asLong = raw <= LONG_MAX ? { $numberLong: raw.toString() } : "does not fit a signed 64-bit Long";
console.log(JSON.stringify({ _id: mint, supplyLong: asLong, supplyDecimal: { $numberDecimal: raw.toString() }, decimals }));
```

The output has four lines: the exact BigInt, the same value through `Number` with a verdict, the `getTokenSupply` comparison, and one JSON document with both MongoDB forms.

## Writing the documents

The script prints extended JSON, where a 64-bit integer is `{ "$numberLong": "..." }` and a decimal is `{ "$numberDecimal": "..." }`. Both carry the digits as a string, so the value never passes through a double on its way to the database.

- From a file: save the printed line as `mints.jsonl` and run `mongoimport --db chain --collection mints --mode upsert --file mints.jsonl`. The import reads both wrapper forms and replaces a document with the same `_id`.
- From an application: build the values with the driver's `bson` types, `Long.fromBigInt(raw)` and `Decimal128.fromString(raw.toString())`. Pass the BigInt through `toString()`, because a `number` in between puts the loss back.
- On the way out: `doc.supplyLong.toBigInt()` for a Long and `BigInt(doc.supplyDecimal.toString())` for a Decimal128.

Aggregations then stay exact in the database: `$sum` over a Decimal128 field returns a Decimal128, and a `$gt` against a `NumberDecimal` bound compares every digit. [Token mint supply and authorities](https://carbium.sh/library/howsolana/token-mint-supply-and-authorities) covers the other mint fields.

## Where it ends

- Long is signed. A raw value above 9,223,372,036,854,775,807 does not fit, and the script prints that line in place of a Long. `Long.fromBigInt(raw, true)` builds an unsigned Long, but MongoDB stores the same 64 bits as a signed int64, so the value reads back negative and sorts first. Those values go in as Decimal128.
- Decimal128 stops at 34 digits and a u128 can have 39, so a u128 field can overflow it. Store such a field as a string, and add the high and low u64 halves as two Decimal128 fields when you need range queries.
- Drivers can undo the work on read. With the Node driver's default `promoteLongs`, a Long that fits in 53 bits comes back as a `number` and a larger one stays a `Long` object, so code that handles only one of them breaks on large values alone. Set `useBigInt64: true` to get a BigInt for every Long, and call `toString()` on a Decimal128 before `BigInt`.
- The stored value is the raw integer. Keep `decimals` as its own field beside it and divide at display time. A float stored as "tokens" brings the loss back.
- The account and the supply come from two calls. A mint that mints or burns between them can make the comparison differ by one change, and a second run settles it. The script reads one account and writes nothing to MongoDB; the driver lines are yours to add.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The stored amount ends in zeros or differs from the chain in the last digits. | The value went through `Number` before the write. Keep the BigInt from `getBigUint64` and send `raw.toString()` into `$numberLong` or `$numberDecimal`. |
| `getBigUint64` returns a huge number that does not match `getTokenSupply`. | The little-endian flag is missing or the offset is wrong. Pass `true` as the second argument and read a mint at offset 36 and a token account at offset 64. |
| `RangeError: Offset is outside the bounds of the DataView`. | The account is shorter than the layout expects, so it is not a mint or the address is wrong. Check the byte length before the read, as the script does with 82. |
| `JSON.stringify` throws `Do not know how to serialize a BigInt`. | Write the BigInt as text, `raw.toString()`, inside the wrapper. The wrapper form needs a string, and the string needs no conversion back. |
| A `$sum` over a Long field returns a value like 1.8446744073709552e19. | The total passed the signed 64-bit maximum and MongoDB switched to a double. Store the field as Decimal128 and re-import it. |
| A run over many mints on a Free key gets 429. | Account reads are paced at 0.5 req/s on Free. Space the calls to the [req/s of your plan](https://carbium.sh/docs/limits) and retry after the hint in the response. |

## Questions

### Can I store the amount as a string and convert it later?

You keep every digit, but the database cannot sum, sort or range-query it. Use a string for display copies and a Long or Decimal128 for the field you query.

### Why pick Long for balances when Decimal128 holds everything?

A Long is half the size and indexes as an integer. A balance never exceeds the supply of its mint, so a mint whose supply fits in a Long has balances that fit.

### Do lamport balances need the same handling?

A single wallet seldom passes 2^53 lamports, about 9 million SOL, but totals across many wallets can. [BigInt lamport amounts](https://carbium.sh/library/howsolana/bigint-lamport-amounts) covers that case.

### Does a Decimal128 keep the token decimals?

No, it holds the raw integer. Store `decimals` in a separate field and divide when you display.

## Related

- [Token mint supply and authorities](https://carbium.sh/library/howsolana/token-mint-supply-and-authorities) (How to use Solana, HS0005)
- [BigInt lamport amounts](https://carbium.sh/library/howsolana/bigint-lamport-amounts) (How to use Solana, HS0046)
- [carbium.sh/docs/rpc](https://carbium.sh/docs/rpc)
- [carbium.sh/docs/limits](https://carbium.sh/docs/limits)
