M3-S2 — The query engine
Section titled “M3-S2 — The query engine”| Module | M3 — The read side |
| After this session you can | Compile a criteria tree to the database query it becomes, order the stages of a list read, and explain why a filter across a relation is slow or refused. |
| Time | Facilitated: 54 min · On your own: 54 min |
| Before you start | M3-S1: pointers and resolveValue. Larkspur Lab with the API and record-store windows (workbench). |
| Go deeper | Engine: query and aggregation · Criteria and field-path dialects · Reading data |
◆ Orientation (1 min) — Every list is a query
Section titled “◆ Orientation (1 min) — Every list is a query”Every list, board, filter, quick filter, view source, reaction criterion and API read you have built
runs through one engine. A builder in ACD composed queries in the designer; an integrator in ACE sent
them as filterCriteria (ACE M5-S1). Neither saw what they become:
a MongoDB aggregation pipeline, assembled in a fixed order, executed, then finished in the service’s
own memory. Once you can read that pipeline, three of the commonest complaints a master hears stop
being mysteries: “the filter returns nothing”, “the list is slow” and “it works for me but not for
him”. This session also gives you the tool to see a query as the database received it.
▤ Concept (8 min) — From a criteria tree to a pipeline
Section titled “▤ Concept (8 min) — From a criteria tree to a pipeline”The criteria tree
Section titled “The criteria tree”A stored query, a view’s filter or a filterCriteria parameter holds its condition as a criteria
tree: each node has an operator, and either child nodes (And, Or) or a field and its
arguments.
{ "operator": "And", "args": [ { "field": "value.priority", "operator": "In", "args": [ { "type": 0, "value": { "id": "opt-high" } }, { "type": 0, "value": { "id": "opt-urgent" } } ] }, { "field": "value.planned_date", "operator": "LessThan", "args": [ { "type": 1, "value": "@today" } ] }] }The operators are a closed list: And, Or, the comparisons (Equal, NotEqual, LessThan,
GreaterThan and their or equal forms), In, NotIn, the text ones (Contains, StartsWith and
their negations), IsEmpty, IsNotEmpty, ElemMatch for arrays, and Under for trees. An unknown
operator is refused with 400 UNKNOWN_OPERATOR_ERROR. An unknown field path is not refused: the
engine uses the path verbatim, so a path that misses the stored shape (planned_date instead of
value.planned_date) matches nothing and returns a successful, empty answer.
Each argument has a type that tells the engine how to get its value at the moment the query runs:
| Type | Name | Resolved as |
|---|---|---|
0 | Fixed | The literal value |
1 | Pointer | @me, @today('-7d') …, parsed and called as in M3-S1 |
2 | Field expression | An expression evaluated with no record in scope |
3 | Dynamic | Another field of the same record: a field-to-field comparison |
4 | Parameter | A value the caller supplies when running a parameterised query |
Compiling a node
Section titled “Compiling a node”The engine walks the tree and turns each node into a MongoDB condition. A few compilation rules explain most surprises.
- Text operators are regular expressions.
Containsbecomes a case-insensitive, unanchored pattern (.*text.*): the database must look inside every value. OnlyStartsWithis anchored. On a large collection,Containsis a full scan unless another condition narrows the rows first. - References and categories match by id.
Inon a reference field compares<field>.dataEntry; on a category field<field>.id. The engine decides by looking at the argument’s shape, so a filter must use the option id, never the label (M2-S3). Since 1.10 a single object is wrapped in a list first, soInwith one selected option works. - Empty means three things.
IsEmptymatches a missing field,nullor an empty list;IsNotEmptyrequires all three to be false. - Field-to-field comparisons (
Dynamic) become a database expression that compares two fields of the same document, which cannot use an ordinary index. - Protected fields are refused, not dropped. When the caller is a person or an application user,
every condition that names a protected (sensitive) field is checked against that caller’s access to
the field. Without it, the whole query is refused with
400 SENSITIVE_FIELD_QUERY_NOT_ALLOWED. Sub-paths do not help: a condition onbank_account.encounts as one onbank_account. The consequence is that the same filter can work for one caller and fail for another.
Joining across a relation
Section titled “Joining across a relation”A document database has no joins, so the engine builds them. A path containing .:relation., such as
value.asset.:relation.value.site, means “follow the reference field asset to the record it points
at, then test site there”. The engine compiles it to a $lookup: for every candidate work order,
fetch the asset whose id is in value.asset.dataEntry from the assets collection, run the condition
inside that look-up, and drop the work orders whose look-up came back empty. A second hop adds a
second, nested look-up (with an $unwind between them). Each relation path is joined only once per
query, however many conditions use it.
That is why a filter across a relation is the most expensive kind of filter: the database joins every row that survived the conditions before it, so a relation condition on an unfiltered entity of 300,000 work orders makes 300,000 look-ups. There is no limit on how deep a chain of relations may go. The cure is order and selectivity: put a selective condition on the entity’s own fields in the same filter (a status, a date range), so fewer rows reach the join.
The list-read pipeline
Section titled “The list-read pipeline”When a list is read (a view, a grid, GET /api/v2/entities/{entity}/entries), the data service
assembles one aggregation in a fixed order, runs it, and then finishes the result in its own
memory:
flowchart TD A["1. Collect the fields to resolve later<br/>(references, categories, switches)"] --> B["2. Compile the criteria<br/>(request + view source + quick filters)"] B --> C["3. View gating: only what the view allows"] C --> D["4. Store scoping and text or id match<br/>(always present)"] D --> E["5. Virtual-field stages"] E --> F["6. Relation look-ups"] F --> G["7. Main match, project, sort, page"] G --> H["8. Execute: the whole page into memory"] H --> I["9. Resolve pass: labels, owners,<br/>mask protected fields"]
What to notice: steps 4 and 9 run on every read whatever the filter says. They are the engine’s invariants, and they are why a list never shows another space’s records or an unmasked protected value.
- Fields to resolve are collected first, so the last step knows what to turn into labels.
- The criteria of the request, the view’s source query and any active quick filter are merged into one filter and compiled.
- View gating removes filters and fields the view does not allow, so a caller cannot widen a view by sending extra conditions.
- Store scoping is unconditional: a match on the stores visible from the current space (M2-S4),
and, unless asked otherwise, on non-virtual records. A text
searchbecomes a leading text match; a read by id matches the id. - Virtual (computed) fields are added before the main match, so they can be filtered and sorted.
- Relation look-ups are added, and the conditions they satisfy are removed from the main match.
- The main match, projection, sort and paging. The engine always appends the record id to the sort as a tie-breaker, so pages are stable. If you sort on a computed field, the sort waits until after the look-ups, which is slower.
- Execution reads the whole requested page into the service’s memory: there is no streaming. Since 1.8, reads through a view are capped (10,000 records by default) even if the caller asks for more.
- The resolve pass turns references into titles, categories into labels and colours, step owners into names, and masks protected fields the caller may not see. It reads the platform’s title index for every referenced value, so a page with many references costs more here than in the database. If this pass fails, the raw records are returned rather than an error.
A count (…/entries/count) runs the same pipeline up to the match and ends with a count. A Kanban
board and a tree have their own variants. All reads of an entity’s collection run with a
case-insensitive collation, which makes every text match case-insensitive and, since 1.10, is
matched by special store and order indexes (M2-S4), so the store match and the default order use an
index instead of scanning.
Two guards, two behaviours
Section titled “Two guards, two behaviours”Notice that protected fields meet two guards. At step 2 a condition on a protected field is refused (the caller learns the filter is not allowed). At step 9 a protected value in the results is masked (the caller sees the record, without that value). Refusing a condition matters because a filter is a question: “bank accounts starting with GB” would reveal information about values the caller cannot see, one yes-or-no at a time. You will meet the access decision itself in M5-S2.
▶ Guided demo (10 min) — See the pipeline the database received
Section titled “▶ Guided demo (10 min) — See the pipeline the database received”MongoDB’s profiler records every operation a database runs, with its full command. Switched on
briefly in your lab, it shows you the exact pipeline the engine built. It writes only to its own
system.profile collection; switch it off when you are done.
-
In the record store, on
lk-data, switch the profiler on for everything:db.setProfilingLevel(2). -
In your terminal, read urgent work orders through the API with a tracking id:
Terminal window curl -s -G -H "x-app-token: $TOKEN" -H "x-correlation-id: lk-m3s2-demo" \"$BASE/api/v2/entities/work_orders/entries" \--data-urlencode 'filterCriteria={"limit":10,"criteria":{"field":"value.title","operator":"Contains","args":[{"type":0,"value":"bearing"}]}}' \| jq '.success, (.result | length)' -
Read the last aggregation on
work_ordersfrom the profiler:db.system.profile.find({ns: "lk-data.work_orders", "command.aggregate": "work_orders"}).sort({ts: -1}).limit(1).forEach(p => printjson(p.command.pipeline)) -
Read the stages in order: the store match (
store.dataEntryin a list of stores), the non-virtual match, the main match withvalue.titleas a case-insensitive regular expression (.*bearing.*), the sort ending in_id, the skip and limit.Screenshot pending The mongosh output of the profiled pipeline for the bearing search, with the store match, the regex match, the sort and the limit stages visible What to notice: the store match comes first even though you never asked for it, and the text condition became an unanchored regular expression.
-
Read the same entry’s
planSummaryanddocsExaminedin the profile document:db.system.profile.find({ns: "lk-data.work_orders"}).sort({ts: -1}).limit(1).forEach(p => printjson({plan: p.planSummary, examined: p.docsExamined, returned: p.nreturned})). On a small lab collection the numbers are tiny; you will scale them in M3-S3 and M9-S1. -
Switch the profiler off:
db.setProfilingLevel(0).
✓ Practice (4 min) — Compile it in your head
Section titled “✓ Practice (4 min) — Compile it in your head”An integration sends {"field": "planned_date", "operator": "LessThan", "args": [{"type": 1, "value": "@today"}]}
to a work-order list and gets success: true with an empty list, although many work orders are late.
Why?
Check your answer
The correct answer is B. Open the explanation under each option to see why.
A view of 300,000 work orders has a single filter, “asset’s site is Plant North”. Which part of the pipeline makes it slow?
Check your answer
The correct answer is C. Open the explanation under each option to see why.
A caller adds {"field": "store.dataEntry", "operator": "In", "args": [{"type": 0, "value": "PRIVATE_<another space>"}]}
to a list request, hoping to read another space’s private records. What happens?
Check your answer
The correct answer is A. Open the explanation under each option to see why.
⛏ Lab (24 min) — Three Larkspur queries, predicted then observed
Section titled “⛏ Lab (24 min) — Three Larkspur queries, predicted then observed”Goal. Three queries written by you, each predicted (answer and pipeline) before it runs, then observed through the API and the profiler; plus one silent failure demonstrated on purpose.
Before you start. Larkspur Lab; BASE, TOKEN; the record store on lk-data. A file
m3-s2-queries.md. The workbench application user has no access to the suppliers’ Bank
Account, which is protected for the Procurement and Finance groups.
Prepare
- Switch the profiler on (
db.setProfilingLevel(2)). - Count the work orders with a past planned date, by hand, for later comparison:
db.work_orders.countDocuments({state: 1, "value.planned_date": {$lt: new Date().toISOString().slice(0,10)}}).
Query 1: a pointer
- Write in your file the criteria for “work orders planned before today”, using the pointer
@today. Predict the number of records and the condition you expect in the pipeline’s main match. - Run it (as in the demo, with your criteria and the id
lk-m3s2-q1), read the count of results, and read the profiled pipeline. Find the date the pointer became.
Query 2: a relation
- Write the criteria for “work orders whose asset’s site is Plant North”. Predict the stages you will see, in order.
- Run it (id
lk-m3s2-q2) and read the profiled pipeline. Find the$lookup, its source collection, the condition inside it, and the match that drops work orders with no matching asset.
Query 3: a protected field
- Write the criteria for “suppliers whose Bank Account starts with GB” on
suppliers. Predict the answer. - Run it (id
lk-m3s2-q3) and record the status,error.codeandserviceName. Check the profiler: did any aggregation onsuppliersrun?
A silent failure on purpose
- Repeat query 1 with the path
planned_date(novalue.). Record the answer.
Conclude
- Switch the profiler off (
db.setProfilingLevel(0)). - For each query, mark your prediction right or wrong, and name the Concept section that explains any difference.
- Write two lines for Larkspur’s builders: how to make query 2 fast on 300,000 work orders, and why a filter that works for Sara Qasim can fail for an integration.
- Find
lk-m3s2-q3in the logs window and note which service refused it.
Check.
- Query 1’s count matches your manual count, and you quoted the literal date the pointer became.
- Query 2’s pipeline shows a
$lookupintoassetswith the site condition inside, followed by a match on a non-empty join. - Query 3 was refused with
400and the protected-field code, and no aggregation onsupplierswas profiled for it. - The silent failure returned
success: truewith no records. - Your two lines for builders name a selective condition before the join, and the caller-specific protected-field check.
Pass condition. All five checks hold.
If something goes wrong
| What you see | What to do |
|---|---|
curl answers 400 UNKNOWN_OPERATOR_ERROR | An operator name is misspelled; operators are words such as LessThan, case as shown. |
The profiler shows nothing for work_orders | You are on another database, or the profiler is off: db.getProfilingStatus() on lk-data. |
| Query 2 returns every work order | The path is missing .:relation.; without it the engine compares value.asset.value.site, which exists nowhere, so check for the reverse case too (an empty answer). |
| Query 3 succeeds | The workbench user has been given access to the protected field in your lab; check Administration › Access Management › Sensitive Permissions. |
--data-urlencode is not accepted | Use -G with it (as in the demo), so curl puts the parameter on the query string. |
Model answer
Query 1.
{"limit": 100, "criteria": {"field": "value.planned_date", "operator": "LessThan", "args": [{"type": 1, "value": "@today"}]}}The count equals your manual count. In the profiled pipeline the main match reads
{"value.planned_date": {"$lt": "2026-11-23"}} (today’s date as a literal): the pointer was resolved
before compilation, so the database never sees @today.
Query 2.
{"limit": 100, "criteria": {"field": "value.asset.:relation.value.site", "operator": "Equal", "args": [{"type": 0, "value": "Plant North"}]}}Stages: store match and non-virtual match; a $lookup from assets with localField
value.asset.dataEntry and a pipeline containing the match on value.site; then a match that keeps
only work orders whose joined array is not empty; then project, sort (ending in _id), skip, limit.
Query 3. 400, SENSITIVE_FIELD_QUERY_NOT_ALLOWED, serviceName naming the data service. No
aggregation on suppliers appears in the profiler: the condition was refused while compiling, before
anything ran.
Silent failure. {"success": true, "result": []}: the path planned_date exists in no stored
record.
For builders. “To make the site filter fast, combine it with a condition on the work orders themselves, such as status not Completed or planned this month, so only those rows are joined; or copy the site onto the work order as a mapped field and filter on it directly.” “A filter on a protected field is checked against the person or program running it, so it works for someone who may see the field and is refused for anyone who may not.”
✓ Practice (6 min) — Diagnose a read
Section titled “✓ Practice (6 min) — Diagnose a read”A quick filter “Description contains seal” makes a 300,000-row work-order list slow, while “Title starts with Replace” is fast. Why the difference?
Check your answer
The correct answer is B. Open the explanation under each option to see why.
Put these stages of a list read in the order the engine assembles them.
Check your answer
The correct order is A → D → E → B → C. Open the explanation under each item to see why it sits where it does.
A view’s filter compares two fields of the same work order: Completed On after Planned Date. A DBA notices it never uses the date indexes. Why?
Check your answer
The correct answer is C. Open the explanation under each option to see why.
An integration asks for 50,000 work orders in one call through a view. How many does it receive, and why?
Check your answer
The correct answer is A. Open the explanation under each option to see why.
A filter on Bank Account works for Sara Qasim and fails with 400 for the ERP integration. A
colleague calls it a bug. What do you answer?
Check your answer
The correct answer is B. Open the explanation under each option to see why.
↺ Recap (1 min) — Reading the read side
Section titled “↺ Recap (1 min) — Reading the read side”You can now compile a criteria tree to the condition the database runs, explain why relation filters are expensive and wrong paths are silent, list the stages of a list read with its two invariants (store scoping and the resolve pass), tell the refused condition from the masked value, and prove all of it with the profiler.
Next. M3-S3 builds on this pipeline for aggregation: statistics, counters and the composite read models behind Spend by Supplier and the Supplier Scorecard.