@atscript/db-mongo 0.1.167 → 0.1.169

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/agg.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_mongo_accumulator = require("./mongo-accumulator-BW-RNFg0.cjs");
2
+ const require_mongo_accumulator = require("./mongo-accumulator-BOwAFmrt.cjs");
3
3
  let _atscript_db = require("@atscript/db");
4
4
  let _uniqu_core = require("@uniqu/core");
5
5
  let _atscript_db_agg = require("@atscript/db/agg");
@@ -11,9 +11,24 @@ let _atscript_db_agg = require("@atscript/db/agg");
11
11
  * Constructs MongoDB aggregation pipelines from translated DbQuery objects
12
12
  * containing $groupBy, $select (with AggregateExpr), $having, $sort, etc.
13
13
  */
14
- /** Maps an AggregateExpr to its MongoDB `$group` accumulator (see `buildAccumulator`). */
15
- function toAccumulator(expr) {
16
- return require_mongo_accumulator.buildAccumulator(expr.$fn, expr.$field === "*" ? "*" : `$${expr.$field}`);
14
+ /** The condition of a conditional aggregate as an aggregation expression, or `undefined`. */
15
+ function conditionOf(where) {
16
+ return where === void 0 ? void 0 : require_mongo_accumulator.whereToExpr(where);
17
+ }
18
+ /**
19
+ * Maps an AggregateExpr to its MongoDB `$group` accumulator (see
20
+ * `buildAccumulator`), restricted to the rows `where` matches. A field list
21
+ * (since 0.1.168) is `countDistinct`'s only.
22
+ */
23
+ function toAccumulator(expr, where) {
24
+ if (typeof expr.$field === "string") return require_mongo_accumulator.buildAccumulator(expr.$fn, expr.$field === "*" ? "*" : `$${expr.$field}`, where);
25
+ (0, _atscript_db_agg.assertAggregateFn)(expr.$fn);
26
+ if (expr.$fn !== "countDistinct") throw new _atscript_db.DbError("INVALID_QUERY", [{
27
+ path: "$select",
28
+ message: `${expr.$fn}() takes one field — only countDistinct takes a list`
29
+ }]);
30
+ const fields = (0, _atscript_db.aggregateColumns)(expr).map((field) => `$${field}`);
31
+ return require_mongo_accumulator.buildAccumulator(expr.$fn, fields, where);
17
32
  }
18
33
  /** An operand of query-time arithmetic: the field as a double (IEEE, like the SQL adapters). */
19
34
  const asDouble = (path) => ({ $toDouble: `$${path}` });
@@ -91,10 +106,27 @@ function bucketExpression(b) {
91
106
  ] };
92
107
  }
93
108
  /**
94
- * Builds the common prefix stages: [search] + $match + $group._id from groupBy
95
- * fields. Shared by both full aggregate and count pipelines.
96
- * `groupKeys` maps each `$groupBy` key (a field path or a calendar-bucket
97
- * alias) to its `_id` sub-key.
109
+ * The stages yielding the rows a grouped level aggregates: `[search →]
110
+ * $match(filter)` — or, for a two-level aggregate (`controls.$from`, since
111
+ * 0.1.168), those followed by the INNER level's grouped stages, whose
112
+ * projected documents (every inner column: `$groupBy` keys at their paths,
113
+ * computed aliases at the top) are the outer level's rows.
114
+ *
115
+ * `searchStage` is the resolved text-search stage (classic `$text` `$match`, or
116
+ * an Atlas `$search`). Both MUST be the pipeline's FIRST stage, hence its
117
+ * position in front of the filter `$match`. Resolving it needs adapter state,
118
+ * so the caller passes it in and this module stays a pure translation.
119
+ */
120
+ function sourceStages(query, searchStage, filterOptions) {
121
+ const filterStages = require_mongo_accumulator.mongoFilterStages(query.filter, filterOptions);
122
+ const rows = searchStage ? [searchStage, ...filterStages] : filterStages;
123
+ const inner = query.controls?.$from;
124
+ return inner ? buildGroupedStages(inner, rows, true) : rows;
125
+ }
126
+ /**
127
+ * The `$group._id` of a level from its `$groupBy`. `groupKeys` maps each
128
+ * `$groupBy` key (a field path or a calendar-bucket alias) to its `_id`
129
+ * sub-key.
98
130
  *
99
131
  * Every key is stored positionally inside `_id` (`k0`, `k1`, …) — internal
100
132
  * names that never collide — and projected back under its own name:
@@ -106,17 +138,9 @@ function bucketExpression(b) {
106
138
  * null value form ONE null group (SQL semantics) that projects back as
107
139
  * `f: null` — a bare `'$f'` would split them into `_id: {}` and
108
140
  * `_id: { f: null }`. A bucket alias is grouped by {@link bucketExpression}.
109
- *
110
- * `searchStage` is the resolved text-search stage (classic `$text` `$match`, or
111
- * an Atlas `$search`). Both MUST be the pipeline's FIRST stage, hence its
112
- * position in front of the filter `$match`. Resolving it needs adapter state,
113
- * so the caller passes it in and this module stays a pure translation.
114
141
  */
115
- function buildPrefix(query, searchStage, filterOptions) {
116
- const controls = query.controls || {};
142
+ function groupIdOf(controls) {
117
143
  const groupBy = controls.$groupBy ?? [];
118
- const filterStages = require_mongo_accumulator.mongoFilterStages(query.filter, filterOptions);
119
- const pipeline = searchStage ? [searchStage, ...filterStages] : filterStages;
120
144
  const groupId = {};
121
145
  const groupKeys = [];
122
146
  for (const [index, key] of groupBy.entries()) {
@@ -126,46 +150,39 @@ function buildPrefix(query, searchStage, filterOptions) {
126
150
  groupKeys.push([key, idKey]);
127
151
  }
128
152
  return {
129
- pipeline,
130
153
  groupId,
131
- groupKeys,
132
- controls
154
+ groupKeys
133
155
  };
134
156
  }
135
157
  /**
136
- * The stages every grouped query shares: `[search →] $match(filter)` →
158
+ * The stages of one grouped level, appended to `pipeline` — a fresh array of
159
+ * its source rows' stages ({@link sourceStages}), returned:
137
160
  * `$group` (dimensions + accumulators) → `$project` (flatten `_id`, keep
138
161
  * aliases) → `$match($having)`. The row pipeline appends sort/skip/limit, the
139
162
  * count pipeline appends `$count`, so both see exactly the same group set —
140
163
  * including the same `$search` narrowing, which is why the stage is threaded
141
- * through this single seam instead of being appended by each caller.
164
+ * through this single seam instead of being appended by each caller. The
165
+ * inner level of a two-level aggregate is built here too.
142
166
  *
143
167
  * With `accumulators: false` only the `$group._id` dimensions are emitted
144
168
  * (no accumulators, no `$project`, no `$having`) — the cheapest shape for a
145
169
  * plain group count, where no alias has to be resolvable.
146
170
  */
147
- function buildGroupedStages(query, { accumulators, searchStage, filterOptions }) {
148
- const { pipeline, groupId, groupKeys, controls } = buildPrefix(query, searchStage, filterOptions);
171
+ function buildGroupedStages(controls, pipeline, accumulators) {
172
+ const { groupId, groupKeys } = groupIdOf(controls);
149
173
  const groupStage = { _id: groupId };
150
174
  if (!accumulators) {
151
175
  pipeline.push({ $group: groupStage });
152
- return {
153
- pipeline,
154
- controls
155
- };
176
+ return pipeline;
156
177
  }
157
178
  const firstLast = controls.$select?.firstLast ?? [];
158
179
  const rowOrder = controls.$select?.rowOrder ?? [];
159
180
  if (firstLast.length > 0 && rowOrder.length > 0) pipeline.push(...require_mongo_accumulator.rowOrderStages(rowOrder));
160
181
  const project = { _id: 0 };
161
182
  for (const [field, idKey] of groupKeys) project[field] = `$_id.${idKey}`;
162
- const nullWhenEmpty = (alias, nonNull) => {
183
+ const nullWhenEmpty = (alias, value, where) => {
163
184
  const count = `${NON_NULL_PREFIX}${alias}`;
164
- groupStage[count] = { $sum: { $cond: [
165
- nonNull,
166
- 1,
167
- 0
168
- ] } };
185
+ groupStage[count] = require_mongo_accumulator.buildAccumulator("count", value, where);
169
186
  return { $cond: [
170
187
  { $eq: [`$${count}`, 0] },
171
188
  null,
@@ -174,13 +191,15 @@ function buildGroupedStages(query, { accumulators, searchStage, filterOptions })
174
191
  };
175
192
  for (const expr of controls.$select?.aggregates ?? []) {
176
193
  const alias = (0, _atscript_db_agg.resolveAlias)(expr);
177
- groupStage[alias] = toAccumulator(expr);
178
- project[alias] = expr.$fn === "countDistinct" ? require_mongo_accumulator.distinctCountExpr(`$${alias}`) : expr.$fn === "sum" ? nullWhenEmpty(alias, require_mongo_accumulator.notNullExpr(`$${expr.$field}`)) : 1;
194
+ const where = conditionOf(expr.$where);
195
+ groupStage[alias] = toAccumulator(expr, where);
196
+ project[alias] = expr.$fn === "countDistinct" ? require_mongo_accumulator.distinctCountExpr(`$${alias}`) : expr.$fn === "sum" ? nullWhenEmpty(alias, `$${expr.$field}`, where) : 1;
179
197
  }
180
198
  for (const e of controls.$select?.exprAggregates ?? []) {
181
199
  const value = require_mongo_accumulator.exprToMongo(e.expr, asDouble);
182
- groupStage[e.alias] = { [`$${e.fn}`]: value };
183
- project[e.alias] = e.fn === "sum" ? nullWhenEmpty(e.alias, require_mongo_accumulator.notNullExpr(value)) : 1;
200
+ const where = conditionOf(e.where);
201
+ groupStage[e.alias] = require_mongo_accumulator.buildAccumulator(e.fn, value, where);
202
+ project[e.alias] = e.fn === "sum" ? nullWhenEmpty(e.alias, value, where) : 1;
184
203
  }
185
204
  for (const fl of firstLast) {
186
205
  groupStage[fl.alias] = { [`$${fl.fn}`]: require_mongo_accumulator.orNull(`$${fl.column}`) };
@@ -190,16 +209,15 @@ function buildGroupedStages(query, { accumulators, searchStage, filterOptions })
190
209
  pipeline.push({ $project: project });
191
210
  for (const e of controls.$select?.exprs ?? []) pipeline.push({ $addFields: { [e.alias]: require_mongo_accumulator.exprToMongo(e.expr, asDouble) } });
192
211
  if (controls.$having) pipeline.push({ $match: require_mongo_accumulator.buildMongoFilter(controls.$having) });
193
- return {
194
- pipeline,
195
- controls
196
- };
212
+ return pipeline;
197
213
  }
198
214
  /**
199
215
  * Builds a full MongoDB aggregation pipeline for GROUP BY queries.
200
216
  *
201
217
  * Pipeline: [search →] $match → $group → $project → $match(having) → $sort →
202
- * $skip → $limit
218
+ * $skip → $limit. A two-level aggregate (`controls.$from`, since 0.1.168)
219
+ * runs the inner level's `$group` → `$project` → `$match(having)` first; the
220
+ * outer stages group its documents (no filter, no search of their own).
203
221
  *
204
222
  * `searchStage` is the resolved `$search` / `$text` stage (see
205
223
  * `buildAggregateSearchStage`); unlike the leaf runner this path adds no
@@ -207,11 +225,8 @@ function buildGroupedStages(query, { accumulators, searchStage, filterOptions })
207
225
  * filter with relational predicates (`mongoFilterStages`).
208
226
  */
209
227
  function buildAggregatePipeline(query, searchStage, filterOptions) {
210
- const { pipeline, controls } = buildGroupedStages(query, {
211
- accumulators: true,
212
- searchStage,
213
- filterOptions
214
- });
228
+ const controls = query.controls ?? {};
229
+ const pipeline = buildGroupedStages(controls, sourceStages(query, searchStage, filterOptions), true);
215
230
  const { stages, cleanup } = require_mongo_accumulator.sortStages(controls);
216
231
  pipeline.push(...stages);
217
232
  if (controls.$skip) pipeline.push({ $skip: controls.$skip });
@@ -245,9 +260,11 @@ function emptyGroupRow(query) {
245
260
  * one empty group exists) from "the real group was removed by `$having`".
246
261
  */
247
262
  function buildMatchedProbe(query, searchStage, filterOptions) {
248
- const { pipeline } = buildPrefix(query, searchStage, filterOptions);
249
- pipeline.push({ $limit: 1 }, { $project: { _id: 1 } });
250
- return pipeline;
263
+ return [
264
+ ...sourceStages(query, searchStage, filterOptions),
265
+ { $limit: 1 },
266
+ { $project: { _id: 1 } }
267
+ ];
251
268
  }
252
269
  /**
253
270
  * The pipeline that applies the query's `$having` (and, for the row query, `$skip`
@@ -276,11 +293,13 @@ function emptyGroupStages(query, row, forCount) {
276
293
  /**
277
294
  * `allowDiskUse` for a pipeline that sorts before it groups (`first` / `last`
278
295
  * order every matching row by `$rowOrder` first, which may exceed the
279
- * in-memory sort limit); `undefined` otherwise.
296
+ * in-memory sort limit), and for a two-level aggregate (two `$group` stages:
297
+ * the outer one groups every inner group, since 0.1.168); `undefined`
298
+ * otherwise.
280
299
  */
281
300
  function aggregateOptions(pipeline) {
282
301
  const group = pipeline.findIndex((stage) => "$group" in stage);
283
- return pipeline.slice(0, group < 0 ? 0 : group).some((stage) => "$sort" in stage) ? { allowDiskUse: true } : void 0;
302
+ return pipeline.findLastIndex((stage) => "$group" in stage) > group || pipeline.slice(0, group < 0 ? 0 : group).some((stage) => "$sort" in stage) ? { allowDiskUse: true } : void 0;
284
303
  }
285
304
  /**
286
305
  * Builds a count-only pipeline: the number of groups that survive `$having`
@@ -295,11 +314,8 @@ function aggregateOptions(pipeline) {
295
314
  * the same query — the counted groups are exactly the rows the search matched.
296
315
  */
297
316
  function buildCountPipeline(query, searchStage, filterOptions) {
298
- const { pipeline } = buildGroupedStages(query, {
299
- accumulators: Boolean(query.controls?.$having),
300
- searchStage,
301
- filterOptions
302
- });
317
+ const controls = query.controls ?? {};
318
+ const pipeline = buildGroupedStages(controls, sourceStages(query, searchStage, filterOptions), Boolean(controls.$having));
303
319
  pipeline.push({ $count: "count" });
304
320
  return pipeline;
305
321
  }
package/dist/agg.d.cts CHANGED
@@ -25,7 +25,9 @@ declare function bucketExpression(b: TResolvedBucket): Document;
25
25
  * Builds a full MongoDB aggregation pipeline for GROUP BY queries.
26
26
  *
27
27
  * Pipeline: [search →] $match → $group → $project → $match(having) → $sort →
28
- * $skip → $limit
28
+ * $skip → $limit. A two-level aggregate (`controls.$from`, since 0.1.168)
29
+ * runs the inner level's `$group` → `$project` → `$match(having)` first; the
30
+ * outer stages group its documents (no filter, no search of their own).
29
31
  *
30
32
  * `searchStage` is the resolved `$search` / `$text` stage (see
31
33
  * `buildAggregateSearchStage`); unlike the leaf runner this path adds no
@@ -60,7 +62,9 @@ declare function emptyGroupStages(query: DbQuery, row: Document, forCount: boole
60
62
  /**
61
63
  * `allowDiskUse` for a pipeline that sorts before it groups (`first` / `last`
62
64
  * order every matching row by `$rowOrder` first, which may exceed the
63
- * in-memory sort limit); `undefined` otherwise.
65
+ * in-memory sort limit), and for a two-level aggregate (two `$group` stages:
66
+ * the outer one groups every inner group, since 0.1.168); `undefined`
67
+ * otherwise.
64
68
  */
65
69
  declare function aggregateOptions(pipeline: Document[]): {
66
70
  allowDiskUse: true;
package/dist/agg.d.mts CHANGED
@@ -25,7 +25,9 @@ declare function bucketExpression(b: TResolvedBucket): Document;
25
25
  * Builds a full MongoDB aggregation pipeline for GROUP BY queries.
26
26
  *
27
27
  * Pipeline: [search →] $match → $group → $project → $match(having) → $sort →
28
- * $skip → $limit
28
+ * $skip → $limit. A two-level aggregate (`controls.$from`, since 0.1.168)
29
+ * runs the inner level's `$group` → `$project` → `$match(having)` first; the
30
+ * outer stages group its documents (no filter, no search of their own).
29
31
  *
30
32
  * `searchStage` is the resolved `$search` / `$text` stage (see
31
33
  * `buildAggregateSearchStage`); unlike the leaf runner this path adds no
@@ -60,7 +62,9 @@ declare function emptyGroupStages(query: DbQuery, row: Document, forCount: boole
60
62
  /**
61
63
  * `allowDiskUse` for a pipeline that sorts before it groups (`first` / `last`
62
64
  * order every matching row by `$rowOrder` first, which may exceed the
63
- * in-memory sort limit); `undefined` otherwise.
65
+ * in-memory sort limit), and for a two-level aggregate (two `$group` stages:
66
+ * the outer one groups every inner group, since 0.1.168); `undefined`
67
+ * otherwise.
64
68
  */
65
69
  declare function aggregateOptions(pipeline: Document[]): {
66
70
  allowDiskUse: true;
package/dist/agg.mjs CHANGED
@@ -1,7 +1,7 @@
1
- import { d as rowOrderStages, f as sortStages, h as orNull, i as buildMongoFilter, m as notNullExpr, n as distinctCountExpr, p as exprToMongo, s as mongoFilterStages, t as buildAccumulator } from "./mongo-accumulator-DMPFOscc.mjs";
2
- import { evaluateExpr } from "@atscript/db";
1
+ import { d as rowOrderStages, f as sortStages, g as whereToExpr, i as buildMongoFilter, m as orNull, n as distinctCountExpr, p as exprToMongo, s as mongoFilterStages, t as buildAccumulator } from "./mongo-accumulator-D4drEz0-.mjs";
2
+ import { DbError, aggregateColumns, evaluateExpr } from "@atscript/db";
3
3
  import { BUCKET_MAX_INSTANT, BUCKET_MIN_INSTANT } from "@uniqu/core";
4
- import { resolveAlias } from "@atscript/db/agg";
4
+ import { assertAggregateFn, resolveAlias } from "@atscript/db/agg";
5
5
  //#region src/agg.ts
6
6
  /**
7
7
  * MongoDB aggregation pipeline builder.
@@ -10,9 +10,24 @@ import { resolveAlias } from "@atscript/db/agg";
10
10
  * Constructs MongoDB aggregation pipelines from translated DbQuery objects
11
11
  * containing $groupBy, $select (with AggregateExpr), $having, $sort, etc.
12
12
  */
13
- /** Maps an AggregateExpr to its MongoDB `$group` accumulator (see `buildAccumulator`). */
14
- function toAccumulator(expr) {
15
- return buildAccumulator(expr.$fn, expr.$field === "*" ? "*" : `$${expr.$field}`);
13
+ /** The condition of a conditional aggregate as an aggregation expression, or `undefined`. */
14
+ function conditionOf(where) {
15
+ return where === void 0 ? void 0 : whereToExpr(where);
16
+ }
17
+ /**
18
+ * Maps an AggregateExpr to its MongoDB `$group` accumulator (see
19
+ * `buildAccumulator`), restricted to the rows `where` matches. A field list
20
+ * (since 0.1.168) is `countDistinct`'s only.
21
+ */
22
+ function toAccumulator(expr, where) {
23
+ if (typeof expr.$field === "string") return buildAccumulator(expr.$fn, expr.$field === "*" ? "*" : `$${expr.$field}`, where);
24
+ assertAggregateFn(expr.$fn);
25
+ if (expr.$fn !== "countDistinct") throw new DbError("INVALID_QUERY", [{
26
+ path: "$select",
27
+ message: `${expr.$fn}() takes one field — only countDistinct takes a list`
28
+ }]);
29
+ const fields = aggregateColumns(expr).map((field) => `$${field}`);
30
+ return buildAccumulator(expr.$fn, fields, where);
16
31
  }
17
32
  /** An operand of query-time arithmetic: the field as a double (IEEE, like the SQL adapters). */
18
33
  const asDouble = (path) => ({ $toDouble: `$${path}` });
@@ -90,10 +105,27 @@ function bucketExpression(b) {
90
105
  ] };
91
106
  }
92
107
  /**
93
- * Builds the common prefix stages: [search] + $match + $group._id from groupBy
94
- * fields. Shared by both full aggregate and count pipelines.
95
- * `groupKeys` maps each `$groupBy` key (a field path or a calendar-bucket
96
- * alias) to its `_id` sub-key.
108
+ * The stages yielding the rows a grouped level aggregates: `[search →]
109
+ * $match(filter)` — or, for a two-level aggregate (`controls.$from`, since
110
+ * 0.1.168), those followed by the INNER level's grouped stages, whose
111
+ * projected documents (every inner column: `$groupBy` keys at their paths,
112
+ * computed aliases at the top) are the outer level's rows.
113
+ *
114
+ * `searchStage` is the resolved text-search stage (classic `$text` `$match`, or
115
+ * an Atlas `$search`). Both MUST be the pipeline's FIRST stage, hence its
116
+ * position in front of the filter `$match`. Resolving it needs adapter state,
117
+ * so the caller passes it in and this module stays a pure translation.
118
+ */
119
+ function sourceStages(query, searchStage, filterOptions) {
120
+ const filterStages = mongoFilterStages(query.filter, filterOptions);
121
+ const rows = searchStage ? [searchStage, ...filterStages] : filterStages;
122
+ const inner = query.controls?.$from;
123
+ return inner ? buildGroupedStages(inner, rows, true) : rows;
124
+ }
125
+ /**
126
+ * The `$group._id` of a level from its `$groupBy`. `groupKeys` maps each
127
+ * `$groupBy` key (a field path or a calendar-bucket alias) to its `_id`
128
+ * sub-key.
97
129
  *
98
130
  * Every key is stored positionally inside `_id` (`k0`, `k1`, …) — internal
99
131
  * names that never collide — and projected back under its own name:
@@ -105,17 +137,9 @@ function bucketExpression(b) {
105
137
  * null value form ONE null group (SQL semantics) that projects back as
106
138
  * `f: null` — a bare `'$f'` would split them into `_id: {}` and
107
139
  * `_id: { f: null }`. A bucket alias is grouped by {@link bucketExpression}.
108
- *
109
- * `searchStage` is the resolved text-search stage (classic `$text` `$match`, or
110
- * an Atlas `$search`). Both MUST be the pipeline's FIRST stage, hence its
111
- * position in front of the filter `$match`. Resolving it needs adapter state,
112
- * so the caller passes it in and this module stays a pure translation.
113
140
  */
114
- function buildPrefix(query, searchStage, filterOptions) {
115
- const controls = query.controls || {};
141
+ function groupIdOf(controls) {
116
142
  const groupBy = controls.$groupBy ?? [];
117
- const filterStages = mongoFilterStages(query.filter, filterOptions);
118
- const pipeline = searchStage ? [searchStage, ...filterStages] : filterStages;
119
143
  const groupId = {};
120
144
  const groupKeys = [];
121
145
  for (const [index, key] of groupBy.entries()) {
@@ -125,46 +149,39 @@ function buildPrefix(query, searchStage, filterOptions) {
125
149
  groupKeys.push([key, idKey]);
126
150
  }
127
151
  return {
128
- pipeline,
129
152
  groupId,
130
- groupKeys,
131
- controls
153
+ groupKeys
132
154
  };
133
155
  }
134
156
  /**
135
- * The stages every grouped query shares: `[search →] $match(filter)` →
157
+ * The stages of one grouped level, appended to `pipeline` — a fresh array of
158
+ * its source rows' stages ({@link sourceStages}), returned:
136
159
  * `$group` (dimensions + accumulators) → `$project` (flatten `_id`, keep
137
160
  * aliases) → `$match($having)`. The row pipeline appends sort/skip/limit, the
138
161
  * count pipeline appends `$count`, so both see exactly the same group set —
139
162
  * including the same `$search` narrowing, which is why the stage is threaded
140
- * through this single seam instead of being appended by each caller.
163
+ * through this single seam instead of being appended by each caller. The
164
+ * inner level of a two-level aggregate is built here too.
141
165
  *
142
166
  * With `accumulators: false` only the `$group._id` dimensions are emitted
143
167
  * (no accumulators, no `$project`, no `$having`) — the cheapest shape for a
144
168
  * plain group count, where no alias has to be resolvable.
145
169
  */
146
- function buildGroupedStages(query, { accumulators, searchStage, filterOptions }) {
147
- const { pipeline, groupId, groupKeys, controls } = buildPrefix(query, searchStage, filterOptions);
170
+ function buildGroupedStages(controls, pipeline, accumulators) {
171
+ const { groupId, groupKeys } = groupIdOf(controls);
148
172
  const groupStage = { _id: groupId };
149
173
  if (!accumulators) {
150
174
  pipeline.push({ $group: groupStage });
151
- return {
152
- pipeline,
153
- controls
154
- };
175
+ return pipeline;
155
176
  }
156
177
  const firstLast = controls.$select?.firstLast ?? [];
157
178
  const rowOrder = controls.$select?.rowOrder ?? [];
158
179
  if (firstLast.length > 0 && rowOrder.length > 0) pipeline.push(...rowOrderStages(rowOrder));
159
180
  const project = { _id: 0 };
160
181
  for (const [field, idKey] of groupKeys) project[field] = `$_id.${idKey}`;
161
- const nullWhenEmpty = (alias, nonNull) => {
182
+ const nullWhenEmpty = (alias, value, where) => {
162
183
  const count = `${NON_NULL_PREFIX}${alias}`;
163
- groupStage[count] = { $sum: { $cond: [
164
- nonNull,
165
- 1,
166
- 0
167
- ] } };
184
+ groupStage[count] = buildAccumulator("count", value, where);
168
185
  return { $cond: [
169
186
  { $eq: [`$${count}`, 0] },
170
187
  null,
@@ -173,13 +190,15 @@ function buildGroupedStages(query, { accumulators, searchStage, filterOptions })
173
190
  };
174
191
  for (const expr of controls.$select?.aggregates ?? []) {
175
192
  const alias = resolveAlias(expr);
176
- groupStage[alias] = toAccumulator(expr);
177
- project[alias] = expr.$fn === "countDistinct" ? distinctCountExpr(`$${alias}`) : expr.$fn === "sum" ? nullWhenEmpty(alias, notNullExpr(`$${expr.$field}`)) : 1;
193
+ const where = conditionOf(expr.$where);
194
+ groupStage[alias] = toAccumulator(expr, where);
195
+ project[alias] = expr.$fn === "countDistinct" ? distinctCountExpr(`$${alias}`) : expr.$fn === "sum" ? nullWhenEmpty(alias, `$${expr.$field}`, where) : 1;
178
196
  }
179
197
  for (const e of controls.$select?.exprAggregates ?? []) {
180
198
  const value = exprToMongo(e.expr, asDouble);
181
- groupStage[e.alias] = { [`$${e.fn}`]: value };
182
- project[e.alias] = e.fn === "sum" ? nullWhenEmpty(e.alias, notNullExpr(value)) : 1;
199
+ const where = conditionOf(e.where);
200
+ groupStage[e.alias] = buildAccumulator(e.fn, value, where);
201
+ project[e.alias] = e.fn === "sum" ? nullWhenEmpty(e.alias, value, where) : 1;
183
202
  }
184
203
  for (const fl of firstLast) {
185
204
  groupStage[fl.alias] = { [`$${fl.fn}`]: orNull(`$${fl.column}`) };
@@ -189,16 +208,15 @@ function buildGroupedStages(query, { accumulators, searchStage, filterOptions })
189
208
  pipeline.push({ $project: project });
190
209
  for (const e of controls.$select?.exprs ?? []) pipeline.push({ $addFields: { [e.alias]: exprToMongo(e.expr, asDouble) } });
191
210
  if (controls.$having) pipeline.push({ $match: buildMongoFilter(controls.$having) });
192
- return {
193
- pipeline,
194
- controls
195
- };
211
+ return pipeline;
196
212
  }
197
213
  /**
198
214
  * Builds a full MongoDB aggregation pipeline for GROUP BY queries.
199
215
  *
200
216
  * Pipeline: [search →] $match → $group → $project → $match(having) → $sort →
201
- * $skip → $limit
217
+ * $skip → $limit. A two-level aggregate (`controls.$from`, since 0.1.168)
218
+ * runs the inner level's `$group` → `$project` → `$match(having)` first; the
219
+ * outer stages group its documents (no filter, no search of their own).
202
220
  *
203
221
  * `searchStage` is the resolved `$search` / `$text` stage (see
204
222
  * `buildAggregateSearchStage`); unlike the leaf runner this path adds no
@@ -206,11 +224,8 @@ function buildGroupedStages(query, { accumulators, searchStage, filterOptions })
206
224
  * filter with relational predicates (`mongoFilterStages`).
207
225
  */
208
226
  function buildAggregatePipeline(query, searchStage, filterOptions) {
209
- const { pipeline, controls } = buildGroupedStages(query, {
210
- accumulators: true,
211
- searchStage,
212
- filterOptions
213
- });
227
+ const controls = query.controls ?? {};
228
+ const pipeline = buildGroupedStages(controls, sourceStages(query, searchStage, filterOptions), true);
214
229
  const { stages, cleanup } = sortStages(controls);
215
230
  pipeline.push(...stages);
216
231
  if (controls.$skip) pipeline.push({ $skip: controls.$skip });
@@ -244,9 +259,11 @@ function emptyGroupRow(query) {
244
259
  * one empty group exists) from "the real group was removed by `$having`".
245
260
  */
246
261
  function buildMatchedProbe(query, searchStage, filterOptions) {
247
- const { pipeline } = buildPrefix(query, searchStage, filterOptions);
248
- pipeline.push({ $limit: 1 }, { $project: { _id: 1 } });
249
- return pipeline;
262
+ return [
263
+ ...sourceStages(query, searchStage, filterOptions),
264
+ { $limit: 1 },
265
+ { $project: { _id: 1 } }
266
+ ];
250
267
  }
251
268
  /**
252
269
  * The pipeline that applies the query's `$having` (and, for the row query, `$skip`
@@ -275,11 +292,13 @@ function emptyGroupStages(query, row, forCount) {
275
292
  /**
276
293
  * `allowDiskUse` for a pipeline that sorts before it groups (`first` / `last`
277
294
  * order every matching row by `$rowOrder` first, which may exceed the
278
- * in-memory sort limit); `undefined` otherwise.
295
+ * in-memory sort limit), and for a two-level aggregate (two `$group` stages:
296
+ * the outer one groups every inner group, since 0.1.168); `undefined`
297
+ * otherwise.
279
298
  */
280
299
  function aggregateOptions(pipeline) {
281
300
  const group = pipeline.findIndex((stage) => "$group" in stage);
282
- return pipeline.slice(0, group < 0 ? 0 : group).some((stage) => "$sort" in stage) ? { allowDiskUse: true } : void 0;
301
+ return pipeline.findLastIndex((stage) => "$group" in stage) > group || pipeline.slice(0, group < 0 ? 0 : group).some((stage) => "$sort" in stage) ? { allowDiskUse: true } : void 0;
283
302
  }
284
303
  /**
285
304
  * Builds a count-only pipeline: the number of groups that survive `$having`
@@ -294,11 +313,8 @@ function aggregateOptions(pipeline) {
294
313
  * the same query — the counted groups are exactly the rows the search matched.
295
314
  */
296
315
  function buildCountPipeline(query, searchStage, filterOptions) {
297
- const { pipeline } = buildGroupedStages(query, {
298
- accumulators: Boolean(query.controls?.$having),
299
- searchStage,
300
- filterOptions
301
- });
316
+ const controls = query.controls ?? {};
317
+ const pipeline = buildGroupedStages(controls, sourceStages(query, searchStage, filterOptions), Boolean(controls.$having));
302
318
  pipeline.push({ $count: "count" });
303
319
  return pipeline;
304
320
  }