Skip to content
ModuleM3 — The read side
After this session you canCompile 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.
TimeFacilitated: 54 min · On your own: 54 min
Before you startM3-S1: pointers and resolveValue. Larkspur Lab with the API and record-store windows (workbench).
Go deeperEngine: 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”

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:

TypeNameResolved as
0FixedThe literal value
1Pointer@me, @today('-7d') …, parsed and called as in M3-S1
2Field expressionAn expression evaluated with no record in scope
3DynamicAnother field of the same record: a field-to-field comparison
4ParameterA value the caller supplies when running a parameterised query

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. Contains becomes a case-insensitive, unanchored pattern (.*text.*): the database must look inside every value. Only StartsWith is anchored. On a large collection, Contains is a full scan unless another condition narrows the rows first.
  • References and categories match by id. In on 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, so In with one selected option works.
  • Empty means three things. IsEmpty matches a missing field, null or an empty list; IsNotEmpty requires 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 on bank_account.en counts as one on bank_account. The consequence is that the same filter can work for one caller and fail for another.

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.

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.

  1. Fields to resolve are collected first, so the last step knows what to turn into labels.
  2. The criteria of the request, the view’s source query and any active quick filter are merged into one filter and compiled.
  3. View gating removes filters and fields the view does not allow, so a caller cannot widen a view by sending extra conditions.
  4. 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 search becomes a leading text match; a read by id matches the id.
  5. Virtual (computed) fields are added before the main match, so they can be filtered and sorted.
  6. Relation look-ups are added, and the conditions they satisfy are removed from the main match.
  7. 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.
  8. 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.
  9. 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.

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.

  1. In the record store, on lk-data, switch the profiler on for everything: db.setProfilingLevel(2).

  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)'
  3. Read the last aggregation on work_orders from 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))
  4. Read the stages in order: the store match (store.dataEntry in a list of stores), the non-virtual match, the main match with value.title as 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.

  5. Read the same entry’s planSummary and docsExamined in 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.

  6. 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”
PracticeChoose one answer.

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?

  1. Explanation for A

    ✗ Incorrect

    Not this one: @today is a valid pointer, and a refused pointer is answered with 400. See The criteria tree.

  2. Explanation for B

    ✓ Correct

    Correct: field data lives under value; a wrong path is used verbatim and silently matches nothing. See The criteria tree.

  3. Explanation for C

    ✗ Incorrect

    Not this one: comparisons work on dates; the problem is where the engine looks. See The criteria tree.

Check your answer

The correct answer is B. Open the explanation under each option to see why.

PracticeChoose one answer.

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?

  1. Explanation for A

    ✗ Incorrect

    Not this one: the resolve pass runs on one page of results, not on every row. See The list-read pipeline.

  2. Explanation for B

    ✗ Incorrect

    Not this one: the store match narrows rows and, since 1.10, uses an index. See The list-read pipeline.

  3. Explanation for C

    ✓ Correct

    Correct: a relation condition joins each surviving row; with no selective condition before it, that is every row. See Joining across a relation.

Check your answer

The correct answer is C. Open the explanation under each option to see why.

PracticeChoose one answer.

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?

  1. Explanation for A

    ✓ Correct

    Correct: store scoping is unconditional; an extra condition can only narrow the result further. See The list-read pipeline.

  2. Explanation for B

    ✗ Incorrect

    Not this one: the engine adds its store match on every read; a filter cannot remove it. See The list-read pipeline.

  3. Explanation for C

    ✗ Incorrect

    Not this one: it is not refused; it simply cannot match anything outside the visible stores. See The list-read pipeline.

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

  1. Switch the profiler on (db.setProfilingLevel(2)).
  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

  1. 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.
  2. 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

  1. Write the criteria for “work orders whose asset’s site is Plant North”. Predict the stages you will see, in order.
  2. 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

  1. Write the criteria for “suppliers whose Bank Account starts with GB” on suppliers. Predict the answer.
  2. Run it (id lk-m3s2-q3) and record the status, error.code and serviceName. Check the profiler: did any aggregation on suppliers run?

A silent failure on purpose

  1. Repeat query 1 with the path planned_date (no value.). Record the answer.

Conclude

  1. Switch the profiler off (db.setProfilingLevel(0)).
  2. For each query, mark your prediction right or wrong, and name the Concept section that explains any difference.
  3. 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.
  4. Find lk-m3s2-q3 in 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 $lookup into assets with the site condition inside, followed by a match on a non-empty join.
  • Query 3 was refused with 400 and the protected-field code, and no aggregation on suppliers was profiled for it.
  • The silent failure returned success: true with 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 seeWhat to do
curl answers 400 UNKNOWN_OPERATOR_ERRORAn operator name is misspelled; operators are words such as LessThan, case as shown.
The profiler shows nothing for work_ordersYou are on another database, or the profiler is off: db.getProfilingStatus() on lk-data.
Query 2 returns every work orderThe 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 succeedsThe workbench user has been given access to the protected field in your lab; check Administration › Access Management › Sensitive Permissions.
--data-urlencode is not acceptedUse -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.”

PracticeChoose one answer.

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?

  1. Explanation for A

    ✗ Incorrect

    Not this one: long text is stored in the record like any other text. See Compiling a node.

  2. Explanation for B

    ✓ Correct

    Correct: only the anchored form can narrow the search quickly; the unanchored one scans. See Compiling a node.

  3. Explanation for C

    ✗ Incorrect

    Not this one: quick filters are merged into the same filter, and the store match always applies. See The list-read pipeline.

Check your answer

The correct answer is B. Open the explanation under each option to see why.

PracticePut the items in the right order.

Put these stages of a list read in the order the engine assembles them.

  1. Explanation for A

    Belongs in position 1 of 5

    First: the request’s filter, the view’s source query and any quick filter become one compiled filter. See The list-read pipeline.

  2. Explanation for B

    Belongs in position 4 of 5

    Fourth: the main match, the sort ending in the record id, and the page are the last database stages. See The list-read pipeline.

  3. Explanation for C

    Belongs in position 5 of 5

    Last: after the database answers, the service turns ids into titles and labels and masks protected values. See Two guards, two behaviours.

  4. Explanation for D

    Belongs in position 2 of 5

    Second: the store match is added on every read, whatever the filter, so other spaces’ records never match. See The list-read pipeline.

  5. Explanation for E

    Belongs in position 3 of 5

    Third: joins for relation paths are added, and the conditions they satisfy leave the main match. See Joining across a relation.

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.

PracticeChoose one answer.

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?

  1. Explanation for A

    ✗ Incorrect

    Not this one: the issue is comparing two fields, not the type of either. See Compiling a node.

  2. Explanation for B

    ✗ Incorrect

    Not this one: since 1.10 the store and order indexes match the collation. See The list-read pipeline.

  3. Explanation for C

    ✓ Correct

    Correct: a Dynamic argument compiles to a comparison of two fields per document. See Compiling a node.

Check your answer

The correct answer is C. Open the explanation under each option to see why.

PracticeChoose one answer.

An integration asks for 50,000 work orders in one call through a view. How many does it receive, and why?

  1. Explanation for A

    ✓ Correct

    Correct: a large page would be held in memory whole, so view reads are clamped. See The list-read pipeline.

  2. Explanation for B

    ✗ Incorrect

    Not this one: reads through a view are capped since 1.8. See The list-read pipeline.

  3. Explanation for C

    ✗ Incorrect

    Not this one: the default applies only when no limit is sent; this call sent one. See The list-read pipeline.

Check your answer

The correct answer is A. Open the explanation under each option to see why.

PracticeChoose one answer.

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?

  1. Explanation for A

    ✗ Incorrect

    Not this one: access to a protected field is per caller, and so is the right to filter on it. See Two guards, two behaviours.

  2. Explanation for B

    ✓ Correct

    Correct: the query guard refuses the condition; the resolve pass separately masks values. See Two guards, two behaviours.

  3. Explanation for C

    ✗ Incorrect

    Not this one: an expired token is a 401 at the gateway, not a 400 from the engine. See M2-S1: the 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.