Bussola

Shell Syntax vs Extended JSON: Writing MongoDB Filters That Work Everywhere

MongoDB Extended JSON is a JSON-compatible text format that represents BSON types JSON cannot express. Instead of ObjectId("507f1f77bcf86cd799439011") you write { "$oid": "507f1f77bcf86cd799439011" }. Shell syntax, the form mongosh and most query bars accept, is JavaScript with helper functions such as ObjectId(), ISODate() and NumberLong(). Both describe the same BSON values. The practical rule: use shell syntax when you type into mongosh or a shell-style query box, and use Extended JSON when the filter must be valid JSON, for example in a file, a config, an HTTP body, or mongoexport and mongoimport data.

This article shows the mapping for the types you meet most, explains the difference between canonical and relaxed mode, and lists where each format is expected.

Why two syntaxes exist

Plain JSON has strings, numbers, booleans, null, arrays and objects. BSON also has ObjectId, Date, Int32, Int64, Double, Decimal128, binary data, regular expressions, timestamps and more. If you serialize a BSON document to JSON without a convention, types get lost: a date becomes a string, a 64-bit integer may lose precision when parsed (see Int64 precision in JavaScript), and an ObjectId becomes a string you can no longer tell from any other string.

Extended JSON (EJSON) solves this by wrapping typed values in objects whose key starts with $. Shell syntax solves it differently, by being code: ObjectId("...") is a function call, and it only works where a JavaScript-like parser evaluates it. A plain JSON parser rejects it.

Conversion table

BSON type Shell syntax Extended JSON (canonical)
ObjectId ObjectId("507f1f77bcf86cd799439011") { "$oid": "507f1f77bcf86cd799439011" }
Date ISODate("2026-11-23T00:00:00Z") { "$date": { "$numberLong": "<milliseconds since epoch>" } }
Int32 NumberInt(42) { "$numberInt": "42" }
Int64 NumberLong("9007199254740993") { "$numberLong": "9007199254740993" }
Double 1.5 { "$numberDouble": "1.5" }
Decimal128 NumberDecimal("19.99") { "$numberDecimal": "19.99" }
Regular expression /^ab/i { "$regularExpression": { "pattern": "^ab", "options": "i" } }
Binary BinData(0, "aGVsbG8=") { "$binary": { "base64": "aGVsbG8=", "subType": "00" } }
UUID UUID("123e4567-e89b-12d3-a456-426614174000") { "$binary": { "base64": "<base64 of the 16 bytes>", "subType": "04" } }
Timestamp Timestamp(1700000000, 1) { "$timestamp": { "t": 1700000000, "i": 1 } }
MinKey / MaxKey MinKey() / MaxKey() { "$minKey": 1 } / { "$maxKey": 1 }

In canonical mode every numeric value is wrapped, including plain integers and doubles. That is why canonical documents look verbose.

Canonical versus relaxed mode

The Extended JSON specification defines two output modes for the same data.

Canonical mode preserves the type of every value. An Int32 is { "$numberInt": "1" }, an Int64 is { "$numberLong": "1" }, a Double is { "$numberDouble": "1.0" }. Parsing it gives back exactly the BSON you started with. Use it when you need a lossless round trip.

Relaxed mode favors readability. Numbers are written as ordinary JSON numbers, and dates in the range of years 1970 to 9999 are written as ISO 8601 strings: { "$date": "2026-11-23T00:00:00Z" }. The cost is that the exact numeric type is no longer recorded: 1 could have been an Int32, an Int64 or a Double with a whole value. Types that have no JSON equivalent, such as ObjectId, still use their wrapper in both modes.

Two details that trip people up:

  • $oid looks the same in both modes. Only numbers and dates differ.
  • When reading Extended JSON, parsers accept both modes, so a filter written in relaxed form works even if the exporting tool produced canonical output.

Writing the same filter both ways

A filter combining an ObjectId, a date range and a 64-bit field in mongosh:

db.events.find({
  accountId: ObjectId("507f1f77bcf86cd799439011"),
  createdAt: {
    $gte: ISODate("2026-11-01T00:00:00Z"),
    $lt: ISODate("2026-12-01T00:00:00Z")
  },
  sequence: { $gt: NumberLong("9007199254740993") }
})

The same filter as relaxed Extended JSON, valid in a JSON file or an HTTP body:

{
  "accountId": { "$oid": "507f1f77bcf86cd799439011" },
  "createdAt": {
    "$gte": { "$date": "2026-11-01T00:00:00Z" },
    "$lt": { "$date": "2026-12-01T00:00:00Z" }
  },
  "sequence": { "$gt": { "$numberLong": "9007199254740993" } }
}

Notice that the $numberLong value is a string. That is deliberate: it keeps a number above 2^53 intact through any JSON parser. For the date range pattern itself, half-open bounds with $gte and $lt, see querying dates in MongoDB.

Where each format is used

Context What it expects
mongosh Shell syntax. A JSON-style { "$oid": "..." } there is just a plain object with a $oid key, not an ObjectId.
mongoexport Writes Extended JSON. The default is relaxed in current versions; --jsonFormat=canonical switches to canonical.
mongoimport Reads Extended JSON, one document per line or a JSON array. Both modes are accepted.
Drivers Use native types (ObjectId, datetime, Date). Most drivers also ship an EJSON or bson.json_util helper to convert to and from Extended JSON.
HTTP bodies, config files, fixtures Extended JSON, because the surrounding format must be JSON.
Query bars in GUI clients Varies by tool; many accept shell syntax and some also accept Extended JSON. Check the tool’s documentation.

The most common bug is mixing the two. Pasting { "_id": { "$oid": "507f..." } } into mongosh does not raise an error, but it matches nothing, because it compares _id to an embedded document rather than an ObjectId. The reverse also fails: pasting ObjectId("...") into a JSON file produces a parse error.

Converting in practice

In mongosh, the EJSON helper converts between the two worlds:

// Document with real BSON types -> Extended JSON text
EJSON.stringify(db.orders.findOne(), { relaxed: false })

// Extended JSON text -> real BSON types, usable in a query
const filter = EJSON.parse('{ "_id": { "$oid": "507f1f77bcf86cd799439011" } }')
db.orders.find(filter)

In Node.js, the bson package (a dependency of the official driver) exposes the same functions:

import { EJSON } from "bson";

const filter = EJSON.parse('{ "createdAt": { "$gte": { "$date": "2026-11-01T00:00:00Z" } } }');
const text = EJSON.stringify(doc, { relaxed: false });

Python offers bson.json_util.loads and dumps, with a json_options argument to pick canonical or relaxed output. Whatever the language, parse Extended JSON with the EJSON-aware function, never with plain JSON.parse or json.loads, or you get objects with $oid keys instead of ObjectIds.

Common mistakes

  • Dates as strings. { createdAt: { $gte: "2026-11-01" } } compares against a string and matches nothing if the field is a BSON date. Use ISODate() or { "$date": ... }.
  • Plain numbers for large integers. In JSON, write 64-bit values as $numberLong strings. In JavaScript code, a bare literal above 2^53 is already rounded before it reaches the database.
  • Worrying about Int32 versus Int64 versus Double in filters. MongoDB compares numbers by value across numeric types, so { qty: 5 } matches a stored Int32, Int64 or Double equal to 5. The type matters mainly for $type queries and when you write data back.
  • Single quotes and comments. Extended JSON is strict JSON: double quotes only, no trailing commas, no comments. Shell syntax allows unquoted keys and single quotes.
  • Old or far-future dates. Relaxed mode uses the ISO string only for years 1970 to 9999. Outside that range the output falls back to the $numberLong form.

Quick checklist

  1. Typing into mongosh or a shell-style query box: use ObjectId(), ISODate(), NumberLong().
  2. Writing a file, a fixture or an HTTP body: use Extended JSON with $oid, $date, $numberLong.
  3. Need a lossless round trip: export and parse canonical mode.
  4. Reading data for humans: relaxed mode is shorter.
  5. Always parse with an EJSON-aware function, not plain JSON.
  6. Put 64-bit values in $numberLong strings, never bare numbers.

The same distinction applies when you check a record from a phone. A client that takes shell-syntax filters, such as Bussola with its { status: "shipped", total: { $gt: 50 } } style, expects ObjectId("...") and ISODate("..."), not $oid wrappers copied from an export, so convert before you paste.

mongodbextended-jsonmongoshbsonqueries

Bussola is a free MongoDB client for iPhone: query, edit and aggregate over a direct connection, with no backend.

Coming soon to the App Store