Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Collections

Collections store schemaless documents using _id and doc. See CREATE COLLECTION and DROP COLLECTION.

The document codec is available. The generic SQL path can insert and select _id and doc. The Rust driver’s find command and SQL matches() use the same server-side matcher and the documented MQL subset below, plus cursor skip and limit.

The Rust and Python clients send typed MQL collection requests over the same connection used for SQL. The Python DB-API exposes connection.collection(name):

collection = conn.collection("events")
created = collection.insert_one({"name": "Ana", "score": 7})
found = collection.find_one({"name": "Ana"})
updated = collection.update_one({"name": "Ana"}, {"$inc": {"score": 1}})
deleted = collection.delete_one({"name": "Ana"})

find, find_one, insert_one, insert_many, replace_one, modifier update_one, and delete_one use typed MQL requests. They share the DB-API connection and explicit transaction with SQL. find accepts optional sort, project, skip, and limit arguments. ampsql supports typed CRUD through \\mql find|insert|replace|update|delete; cursor options and typed aggregation are not available in that command yet. This does not provide compatibility with clients that speak the MongoDB wire protocol.

Documents without _id receive a server-generated UUIDv7. The relational _id column is canonical; object documents expose the same value in doc._id as a UUID string, including in client results. A supplied _id must be a matching UUID or the write fails with SQLSTATE 22023. ObjectId is not supported by this contract. _id remains globally unique across the physical leaves of a partitioned collection, including leaves created after the parent collection. upsert_one is also available in the driver.

Modifier-style update_one supports $set, $unset, and integer $inc. The client sends the filter and modifiers in a typed request; the server rechecks the filter and applies the update to the selected row in the session’s normal transaction and executor path. A replacement document passed to update_one uses the replacement operation instead.

SQL can project a document path with dotted notation. The result remains of type doc; a missing path becomes NULL and can be tested with IS NULL or IS NOT NULL:

SELECT doc.profile.age
FROM events
WHERE doc.profile.age IS NOT NULL;

UPDATE can replace a value inside a document. Sibling fields are preserved, and missing intermediate objects are created. If an existing intermediate value is a scalar, array, or null, the statement fails with SQLSTATE 22023. SQL NULL assigned to a path is stored as document null.

Collections can participate in regular SQL joins with tables. Reads in a statement share transaction visibility, including the current transaction’s uncommitted writes:

SELECT a.name, doc.kind
FROM accounts AS a
JOIN events AS e ON a.id = doc.account_id;

Other sessions do not see the current transaction’s uncommitted rows.

UPDATE events
SET doc.profile.age = 31
WHERE _id = '00000000-0000-0000-0000-000000000001'::uuid
RETURNING doc;

Each statement accepts one assignment to the doc column. The target must start with the doc column; DEFAULT is not accepted for paths. Supported scalar values include boolean, integers, float, numeric, text, bytea, UUID, and other documents. numeric is converted to the document floating-point number model and may lose precision; unsupported SQL types return SQLSTATE 0A000.

To filter by document contents, use matches(doc, filter), which shares the MQL subset supported by FIND:

SELECT _id, doc
FROM events
WHERE matches(doc, '{"age":{"$gte":18}}'::doc);

GIN indexes on documents

A collection can have a GIN index on doc to narrow candidates for content searches with @>:

CREATE INDEX events_doc_gin ON events USING gin (doc);

SELECT _id
FROM events
WHERE doc @> '{"profile":{"city":"SP"}}'::doc;

The operator uses the same matcher as matches(doc, filter), and the complete predicate is rechecked on candidate rows. The planner uses the index for positive structural equality when every extracted term is required for a match. Filters with logical or negative operators, equality with null, and empty objects or arrays remain valid but use a sequential scan. EXPLAIN shows IndexScan when GIN is selected.

The current subset includes equality, $eq, dotted paths, $gt, $gte, $lt, $lte, $in, $all, $elemMatch, $size, $type, $mod, $regex, $not, $nin, $ne, $exists, $and, $or, and $nor. $nor matches when none of the filters in its array match; an empty list matches every document. Unsupported operators, including $expr and $where, return SQLSTATE 22023. $elemMatch applies a per-element filter to arrays of objects or scalars; one element must satisfy every condition. Object elements use a document filter; scalar elements accept an object made only of operators. $all requires a nonempty array of values and matches only when the field is an array containing every expected value as a direct element; nested objects and arrays use equality. A $size predicate matches an array only when its length equals the given non-negative integer. Negative and non-integer sizes are malformed predicates. A $not predicate negates a non-empty field-operator object. It includes missing fields when the inner predicate does not match, and malformed inner operators still return an error. $type accepts one of null, bool, int, float, text, bytea, uuid, array, or object. For arrays, array checks the value itself; other names match when a direct element has that type. Unsupported names and non-text arguments are errors. $eq makes the same structural comparison as a direct value and also matches a scalar contained in an array field. $mod accepts [divisor, remainder] with two integers and a nonzero divisor. Only integer document values participate; for arrays, one matching integer element is enough. Remainder follows the dividend’s sign, and invalid division arguments are errors. $regex accepts a pattern in the Rust regex crate syntax and tests scalar text or direct text elements in an array. $options accepts i (case insensitive), m (line anchors), s (. matches newlines), and x (ignore pattern whitespace and comments). $options requires $regex; PCRE syntax unsupported by the crate is outside this contract. Invalid patterns, patterns larger than 16 KiB, or patterns compiling to more than 1 MiB are errors. Equality with JSON null (direct, $eq: null, or $in: [null]) matches both null values and missing paths. $ne: null matches only existing non-null values; $nin also matches missing paths. Use $exists to test presence independently of value. MQL relational comparisons compare each array element with the expected scalar and match if any element satisfies the operator; different types do not match. Lexicographic array comparisons are outside this subset. SQL relational comparisons accept document paths and scalar SQL values on either side, for example doc.profile.age >= 18 or 30 = doc.profile.age. Comparisons preserve document types: SQL integers compare with document integers, float/numeric values with document floats, text with text, and so on. Different document types do not match (=, <>, <, <=, >, and >= return false). A missing path is SQL NULL, so its comparison is NULL; JSON null is a document value, not SQL NULL. SQL types that cannot yet be represented in doc do not receive an implicit conversion.