Collections
collection, §M15 D3
Ez az oldal a nucleus saját dokumentációjából készül, ezért angol nyelvű.
CREATE COLLECTION [IF NOT EXISTS] c [WITH (schema = '…', storage = …, engine = …)] makes a table of documents: (_id json PRIMARY KEY, doc json NOT NULL), marked a collection in the catalog (Table::collection,
catalog encoding 29). _id is a stored generated column, doc -> '_id': the document holds its id and round-trips whole, and a read by
id (WHERE _id = '7') is a primary-key read. A document written
without an _id is given one before the generated columns are computed
(collection::FILL, bound once with the table’s writer and evaluated in
Writer::complete): on an UPDATE the row’s own — a document replaced
whole keeps its id —, on an insert a UUIDv7 as a string (time-ordered
and increasing within the process, so new documents append at the key
range’s end). A new _id in an updated document moves the row to it.
A document must be an object (doc_object, checked before the id is
filled) and its _id anything but an array (id_not_array, MongoDB’s
rule); WITH (schema = '…') adds doc_schema, json_matches_schema(doc, '…') (§8.31, §M14.15 J5) — the text must be JSON (22023).
ALTER COLLECTION c SET (schema = '…') replaces it, checked against the
documents there as ADD CONSTRAINT checks (23514 when one breaks it);
RESET (schema) takes it away; RENAME TO. DROP COLLECTION [IF EXISTS] a, b [CASCADE]. ALTER and DROP refuse a table that is not
a collection (42809); making one needs CREATE on the schema, changing
or dropping it its ownership (the table statements they run are checked
as well).
Everything else is the table’s: documents are inserted, replaced,
updated by the JSON functions (json_set, #-, ||), deleted and
upserted (INSERT … ON CONFLICT (_id) DO UPDATE SET doc = c.doc || excluded.doc; an arbiter’s part named as an index’s — ON CONFLICT (email), (login.name) — is a path, as in CREATE INDEX) in SQL; indexes on fields are expression indexes
(CREATE INDEX ON c ((doc ->> 'name'))), and every storage and engine
holds them.
Path indexes (§M15 D4, §M16 Q2): on a collection, CREATE [UNIQUE] INDEX [name] ON c (a.b.c, …) — a key part that names no column
(a.b.c, or name alone) is a path in the documents (the keys split at
the dots), named c_a_b_c_idx when unnamed. The first such part of an
index that is not UNIQUE holds the values lax mode finds there: the
multi-valued part json_path_query(doc, '$."a"."b"."c"[*]')
(collection::index_path_sql, below) — so a filter document’s
conditions on the field are served by it, through arrays along the path
as MongoDB’s multikey indexes are. A UNIQUE index’s part and a later
part hold the json value there, the expression doc -> 'a' -> 'b' -> 'c' (collection::path_sql; a document without it: a NULL key),
which serves the query’s doc -> 'a' -> 'b' -> 'c' = '…' or doc #> '{a,b,c}' = '…' — both bound as the same one walk — as any expression
index (equality, ranges in json’s order, UNIQUE; ON CONFLICT’s
arbiter). Either way the definition is the expression’s. A text comparison (doc ->> 'name' = 'x') wants an index
on that expression (((doc ->> 'name'))): a json value’s text form is
not its key. _id and doc are columns, so a field named doc is
indexed by its expression; a key holding a dot or reading as an array
position is too. On a table a path is no column (42703, the hint
naming the expression to index); an index method’s index takes columns
only (0A000).
Multi-valued indexes (§M15 D5, multikey): a B-tree key part may
be the elements of an array — CREATE INDEX ON t ((json_array_elements(doc -> 'tags'))), ((unnest(tags))) for an SQL
array, ((json_array_elements(doc -> 'items') ->> 'sku')) for each
element’s field; on a collection tags[*] and items[*].sku (one [*]
a path, 0A000 otherwise); or the items a lax path of keys ending in
[*] finds — ((json_path_query(doc, '$.a.b[*]'))), a collection’s path
index (above): a field’s value, an array’s elements, along the path
arrays unwrapped as lax mode does (any other path 0A000). A row has an entry per distinct value
(MySQL’s multi-valued index, MongoDB’s multikey one): a value that is no
array is its one element; an element’s field that holds an array gives
its elements (so a containment through the field finds the row); a row
with none has no entry. One such part an index, which is not UNIQUE
(0A000); unnest takes an SQL array, the json functions json, a key
only after json elements (42804). Bound, the part is a call of
multikey::Each on its array: dml::IndexKeys gives an index’s entries
as a list (one per value), every writer keeps them — an update matches
its old and new entries by key —, and an index build, an online one and
the integrity check take them as they come. A scan of such an index
reads each row once (IndexRows remembers the row keys it read), and a
lookup join reads it through the plan. The optimizer (multikey::probe)
finds a bound on the part in a condition on its array and keeps the
condition as the filter (an entry says a row may match; no condition is
applied exactly): a @> c (or c <@ a) of an SQL array, c a constant
array — its first element that is not NULL (an empty c holds in
every row: no bound; a && c is not served yet); a @> c with c a constant — a the part’s array or
a json value it is a path below (doc @> '{"tags": ["x"]}'), c taken
down that path, to its first element if an array, down the part’s keys,
a scalar —; c = ANY(a) of an SQL array; x @? 'strict $.k…[*].f… ? (@.g… op c)' (or a conjunct of the filter, c op @… too) — an
equality or a range, the path to [*] the part’s array below x and
the keys after it the part’s. A lax path is no bound: lax unwraps
arrays on the way to [*], which the part’s array does not, so a row
could match the path with no entry. Two conditions are never combined
into one range on the part (two elements may meet them). Not served:
a ? 'x' (true of an object with key x too, which has no entry x),
JSON_EXISTS (its ON ERROR TRUE would hold where the path fails).
A lax path part (multikey::lax_bound) is bound by a lax x @? '$.k… ? (C)' — a filter document’s path —, a conjunct of C @.g… op c (or
c op @.g…) whose keys before the filter and g… are the part’s: an
equality with a scalar, a range with a number (a path compares strings
by code point, which need not be the index’s order), an equality
preferred; its entries are exactly what the comparison compares, so a
row it holds for has an entry in the bound. $or, $in, $ne,
$exists, $regex and strict paths are not served; and a -> chain’s
equality with a json constant but an array (doc -> 'a' -> 'b' = '3',
#> too): the value there is one of the part’s.
Filter documents (§M16 Q1, D22; json::path::filter):
json_filter(f) compiles a MongoDB-style filter document to a lax
SQL/JSON path, which @? applies — doc @? json_filter('{"age": {"$gt": 30}, "tags": "vip"}') is doc @? '$ ? (@.age > 30 && @.tags == "vip")': the same operator, plan and evaluation; a constant filter is
compiled once, where the statement is bound (EXPLAIN shows its path).
The matching rules are MongoDB’s, which are lax mode’s: a field that is
an array matches when it or an element does; values of other types
never compare ("40" is not > 30); a missing field compares false.
Where MongoDB goes further the path says so: null (in $eq, $in,
$gte, $lte too) matches a missing field — a path missing at a step
whose value is missing or a scalar, an array walked into through its
objects only; $ne, $nin, $not, $nor hold where what they negate
is false or unknown ((p) is unknown || !(p)); equality with an object
or array is exact (keys, elements in order, types), of the field or an
element; $size, $elemMatch, $type: "array" hold of arrays,
$type of another type of the field or an element. The operators:
$eq $ne $gt $gte $lt $lte $in $nin $exists $type $size $all $regex $options (i, m, s) $elemMatch $not $and $or $nor $comment;
dotted paths. Errors: an unknown operator, an object mixing operators
and fields, a filter that is not an object, an empty $and / $or /
$nor (22023); $expr, $where, $text, $jsonSchema, $mod,
bitwise and geospatial operators, a position in a path (a.0), an
ordering comparison with an object or array (0A000); a bad pattern
(2201B). Differences from MongoDB, recorded: JSON has one number type
($type "int", "double", "long", "decimal" all mean a number);
keys are unordered (§M15 item 3), so object equality ignores their order
and an object of operators and fields is an error, not read by its
first key; $elemMatch over an element that is itself an array tests
that array’s elements (lax mode unwraps it) where MongoDB tests the
array whole. A collection’s path indexes serve it (§M16 Q2, above):
an equality on a field, a range on a number. Checked against
MongoDB 8: slt/95_json_filter.slt (every answer MongoDB’s on the same
documents but the $elemMatch difference, marked) and a differential fuzzer of random filters over random
irregular documents (outside the repository, as the bug hunt’s) —
4,500 filters without nested arrays or without $elemMatch, every
answer MongoDB’s, and 4,500 again with path indexes on every path one
and two keys deep (INDEX=1).
Reads and writes by filter (§M16 Q3; json::document): what
MongoDB’s find, update, replace, delete and upserts do, as SQL
over a collection — one statement, one plan:
SELECT json_project(doc, '{"name": 1, "_id": 0}') FROM people
WHERE doc @? json_filter('{"age": {"$gte": 18}}')
ORDER BY json_sort_key(doc, '{"age": -1, "name": 1}') LIMIT 10 OFFSET 20;
UPDATE people SET doc = json_update(doc, '{"$inc": {"visits": 1}, "$push": {"tags": "new"}}')
WHERE doc @? json_filter('{"name": "ann"}');
UPDATE people SET doc = json_update(doc, '{"name": "ann", "age": 35}') -- a replacement
WHERE doc @? json_filter('{"_id": 7}');
DELETE FROM people WHERE doc @? json_filter('{"status": "gone"}');
INSERT INTO people (doc) SELECT json_upsert_document(f, u)
WHERE NOT EXISTS (SELECT 1 FROM people WHERE doc @? json_filter(f));
json_update(doc, update): an update document’s operators —$set $unset $inc $mul $min $max $rename $push($each,$position,$sort,$slice)$addToSet($each)$pop $pull(a value, a condition on the element{"$gte": 6}or on its fields{"qty": {"$lt": 2}}, compiled as a filter)$pullAll $setOnInsert(only on an insert) — applied in one pass over a tree of the document; or, with no operator, a replacement, the_idkept. Dotted paths, a number in one an array’s position ($setpads withnull); objects made along the way. MongoDB’s rules, each checked: paths of one update apart (“would create a conflict”), the_idunchanged,$inc/$mulof a number, no field made in a scalar or by a name in an array,$pop,$pull,$renamenot going through a scalar or by a name through an array (a missing path: nothing done),$unsetnever an error. Arithmetic is exact (numeric’s:0.1 + 0.2is0.3).json_upsert_document(filter, update): what an upsert inserts when nothing matches — the filter’s equalities (a value or$eq, through$and; a path set twice or within another an error), then the update with$setOnInsert; a replacement takes the filter’s_id.json_project(doc, projection): fields included (1,true;_idtoo unless0) or excluded (0,false), not both; dotted, through arrays of objects;{"_id": 1}alone the_idalone;$slice(n,-n,[skip, n]) of an array, through arrays of objects too.json_sort_key(doc, sort): abyteawhose order is MongoDB’s sort. The sort document is text, read in its order (a json object’s keys are unordered), or[["age", -1], ["name", 1]]. Values compare in MongoDB’s order of types (null and missing, numbers, strings, objects field by field, arrays element by element, booleans; a field that is an empty array before them all); a document’s keys are a compound multikey index’s — one tuple per element of the array the fields go through (fields through two different arrays: “parallel arrays”,22023), an object without the field and an element that is no objectnull— and its key is the least tuple in the sort’s order (an ascending array by its least element, a descending one by its greatest). The sort document is read once a thread while it stays the same; of the document only what the paths reach is read. No index serves it yet: the rows are sorted (aLIMITkeeps the top ones).
Not supported (0A000): positional paths (a.$, a.$[], a.$[x]),
$currentDate, $bit, a $push $sort by several fields (keys are
unordered), projection operators but $slice. Errors (22023): an
unknown operator, operators mixed with fields, an empty update, a sort
value other than 1 / -1. Differences from MongoDB, recorded: one
number type (an $inc of an integer by 0.5 is 0.5 more, not a
double); objects compare by their sorted keys where MongoDB’s compare in
their stored order. Checked against MongoDB 8:
slt/96_json_documents.slt (written by a generator that ran each case
in both — finds, eleven updates one after another, delete, count, an
upsert — and errors), and differential fuzzers outside the repository:
48,000 random updates of random documents (every result or error
MongoDB’s), 2,400 upserts, 6,240 projections and sorts — none
different.
nc_catalog.collections lists them (name, owner, schema,
storage, engine); nc_catalog.definitions gives CREATE COLLECTION … WITH (…), and schema diffs set or reset a changed schema in place
(another storage is a note: the documents would go). ncsql’s \d says
“Collection”. To PostgreSQL’s clients a collection is a table of two
jsonb columns.
Tests: slt/88_collections.slt (nucleus-only; the SQL over the
documents is PostgreSQL’s and checked in 65–68 and 87);
tests/collections.rs — every storage kept whole (check) through
inserts, replacements, upserts, deletes and a field index, ids in the
order the documents came; who may make, change and drop one; the
definition’s options;
tests/schema_diff.rs (a_collections_schema_changed_in_place);
pg-compat’s 01_pg_catalog.slt. Path indexes: the same slt (names,
expressions, plans for both spellings, UNIQUE, missing fields, the
definition, a quoted key, three deep) and 69_expression_indexes.slt
(#> / #>> bound as the chain; integer keys left alone — checked
against PostgreSQL 18); a_path_on_a_table_says_what_a_path_is.