MongoDB SQL dialect reference

Each execution runs one read-only statement on the active database. Try these examples in Sample data → acme → job_runs → SQL. The examples below use the original sample records.

Execution, editing and reuse

Open SQL in a collection. In a script you can highlight a selection or place the cursor inside one statement. Press ⌘ Enter on Mac or Ctrl Enter on Windows and Linux. The Run control identifies the active scope. Contextual completions include collection fields and local aliases.

Open or save a .sql file with File. A file opens for review. Each collection tab retains its draft during the session. Generated MongoDB exposes the translation, and Copy as code offers mongosh, Node.js or Python snippets for reuse with a connected client.

Explain uses the live server and account. A modified draft can differ from the last successful Table or JSON result. Full-last-run export reruns that SQL on a live connection. Include a stable ORDER BY before paginating.

BSON values, identifiers and missing fields

SELECT name, BSON_TYPE(plan) AS stored_type
FROM customers WHERE plan IS MISSING
ORDER BY name;

Returns Ren Ito and Tessa Morgan on a clean sample. IS MISSING isolates field absence. IS NULL also includes missing values; comparisons involving null produce unknown, and a filter retains only true conditions.

Quote reserved names with brackets or backticks, as in [release]. Dotted field paths can address nested fields and positions, such as [items.0.sku]. Use exact BSON constructors such as ObjectId, ISODate, NumberLong and NumberDecimal. Quote large numbers to retain precision. UUID, BinData and EJSON express binary and embedded data.

SELECT NumberLong('9007199254740993') AS exact_value
FROM job_runs LIMIT 1;

Joins and grouped results

SELECT r.[release] AS release_name, COUNT(*) AS runs
FROM job_runs AS r
LEFT JOIN deployments AS d ON r.[release] = d.[release]
WHERE d.[release] IS NULL
GROUP BY r.[release]
HAVING COUNT(*) > 0
ORDER BY runs DESC;

Returns release 2026.12.2 with 17 runs lacking a deployment. Inner and left joins produce a row for each matching pair. A left join keeps an unmatched source row. Use distinct aliases for output fields that share a name.

Use COUNT, COUNT(DISTINCT …), SUM, AVG, MIN and MAX. Arithmetic, CASE, CAST, COALESCE, and supported string, date and array functions can shape the projection. LIKE is case-sensitive.

CTEs, derived tables and subqueries

WITH deployed AS (SELECT [release] AS rel FROM deployments)
SELECT COUNT(*) AS linked_runs
FROM (SELECT [release] AS rel FROM job_runs) AS runs
WHERE runs.rel IN (SELECT rel FROM deployed);

Returns 55 linked runs across the two releases with a deployment. Define nonrecursive CTEs in dependency order. A derived table can act as a named source. Use IN, EXISTS and their negations, and qualify outer fields when correlating a subquery.

SELECT COUNT(*) AS unmatched
FROM job_runs AS r
WHERE NOT EXISTS (SELECT d._id FROM deployments AS d
                  WHERE d.[release] = r.[release]);

Returns 17. A scalar subquery must select one column and return at most one row. An empty scalar result is null. A second row is an error.

UNION and UNION ALL

SELECT [release] AS rel FROM job_runs
UNION SELECT [release] AS deployed_release FROM deployments
ORDER BY rel;

Returns three distinct release names. UNION ALL appends both streams, including duplicates. Columns correspond by position and output names come from the first arm. Select the same number of columns explicitly. Final ordering and pagination apply to the combined result.

To remove duplicates inside one part of a larger union, wrap that union in a derived table. For example, combine the distinct known releases with each deployment again:

SELECT rel FROM (
  SELECT [release] AS rel FROM job_runs
  UNION SELECT [release] FROM deployments
) AS known
UNION ALL SELECT [release] FROM deployments;

Window functions and frames

SELECT [release], duration_ms,
       RANK() OVER by_release AS slow_rank,
       DENSE_RANK() OVER by_release AS dense_rank
FROM job_runs
WINDOW by_release AS (PARTITION BY [release] ORDER BY duration_ms DESC)
ORDER BY [release] DESC, duration_ms DESC, _id LIMIT 3;

The tied 8,120 ms runs get ranks 1 and 1 under both functions. The 5,876 ms run gets rank 3 and dense rank 2. ROW_NUMBER gives each row its own position. Use a unique tie-breaker in the window if individual positions matter.

LAG, LEAD, FIRST_VALUE, LAST_VALUE and window aggregates can share a named window. ROWS BETWEEN 1 PRECEDING AND CURRENT ROW defines a two-row moving frame. RANGE with current-row or unbounded endpoints includes peers. Live window queries require MongoDB 5.0 or later.

Scope and unsupported syntax

Dialect boundaries
QuestionBehavior
Can SQL modify documents?SELECT and WITH queries are read-only. INSERT, UPDATE, DELETE and write stages are excluded.
Can I join another database?Queries and all their sources must be in the active database and readable by the current account.
Can a CTE reference itself?Recursive CTEs are unsupported. Reference a preceding CTE or use a separate query.
Are time- or number-offset RANGE frames supported?Numeric-offset RANGE frames are unsupported. Choose a supported ROWS frame or an unbounded/current peer range.
Can I run a script in one click?Run a single statement or selection at a time. Opening a SQL file loads its text for review.