@atscript/db-mongo 0.1.181 → 0.1.183
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/index.cjs +243 -64
- package/dist/index.d.cts +31 -0
- package/dist/index.d.mts +31 -0
- package/dist/index.mjs +243 -64
- package/package.json +7 -7
package/dist/index.cjs
CHANGED
|
@@ -155,6 +155,111 @@ function containsAggregationExpr(v) {
|
|
|
155
155
|
return false;
|
|
156
156
|
}
|
|
157
157
|
/**
|
|
158
|
+
* Whether `value` holds a plain object at any depth. Only then can BSON
|
|
159
|
+
* equality (`$in` / `$eq`, which follows stored property order) differ from
|
|
160
|
+
* the comparison of the other adapters, which ignores property order.
|
|
161
|
+
*/
|
|
162
|
+
function holdsObject(value) {
|
|
163
|
+
return Array.isArray(value) ? value.some(holdsObject) : (0, _atscript_db.isPlainObject)(value);
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* The form two operator items are the same by: JSON text with every object's
|
|
167
|
+
* keys sorted (as `stableJson` writes it) — what the other adapters compare
|
|
168
|
+
* elements without key props by — except that a value JSON cannot represent
|
|
169
|
+
* (an `ObjectId`, a `Date`, …) keeps its BSON type, as `$in` / `$eq` compare
|
|
170
|
+
* it: an `ObjectId` never equals its hex string, nor a `Date` its ISO text.
|
|
171
|
+
*/
|
|
172
|
+
function itemForm(item) {
|
|
173
|
+
return JSON.stringify([item], function(key, value) {
|
|
174
|
+
const raw = this[key];
|
|
175
|
+
if (raw !== null && typeof raw === "object" && !Array.isArray(raw) && !(0, _atscript_db.isPlainObject)(raw)) return `\u0000${raw.constructor?.name}:${JSON.stringify(value)}`;
|
|
176
|
+
return (0, _atscript_db.isPlainObject)(value) ? Object.fromEntries(Object.entries(value).toSorted(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) : value;
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* `items` without those the same as an earlier one ({@link itemForm}) — what
|
|
181
|
+
* an operator that skips repeated items drops before it reaches the server.
|
|
182
|
+
*/
|
|
183
|
+
function distinctItems(items) {
|
|
184
|
+
const seen = /* @__PURE__ */ new Set();
|
|
185
|
+
return items.filter((item) => {
|
|
186
|
+
const form = itemForm(item);
|
|
187
|
+
if (seen.has(form)) return false;
|
|
188
|
+
seen.add(form);
|
|
189
|
+
return true;
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
const allOf = (checks) => checks.length === 1 ? checks[0] : { $and: checks };
|
|
193
|
+
const anyOf = (checks) => checks.length === 1 ? checks[0] : { $or: checks };
|
|
194
|
+
/** Whether a property name can follow a variable in a field path (`$$el.<name>`). */
|
|
195
|
+
const isPathSegment = (name) => name !== "" && !name.includes(".") && !name.startsWith("$") && !name.includes("\0");
|
|
196
|
+
/**
|
|
197
|
+
* Appends to `checks` aggregation conditions that all hold exactly when the
|
|
198
|
+
* value of `expr` equals `item` the way the other adapters compare elements
|
|
199
|
+
* without key props: an object whatever the order of its properties, at
|
|
200
|
+
* every depth; an array element by element, in order; a scalar as BSON
|
|
201
|
+
* compares it; a missing property is not `null`. The conditions follow the
|
|
202
|
+
* item's structure — stored structure deeper than the item cannot equal it —
|
|
203
|
+
* and each one is safe to evaluate on any stored value.
|
|
204
|
+
*
|
|
205
|
+
* `depth` names the variables a nested array element is bound to (`v0`,
|
|
206
|
+
* `v1`, … from the outside in). Item values are `$literal`s.
|
|
207
|
+
*/
|
|
208
|
+
function equalityChecks(expr, item, depth, checks = []) {
|
|
209
|
+
if (item === null || item === void 0) checks.push({ $eq: [{ $type: expr }, "null"] });
|
|
210
|
+
else if (!holdsObject(item)) checks.push({ $eq: [expr, { $literal: item }] });
|
|
211
|
+
else if (typeof expr !== "string") {
|
|
212
|
+
const name = `v${depth}`;
|
|
213
|
+
checks.push({ $let: {
|
|
214
|
+
vars: { [name]: expr },
|
|
215
|
+
in: allOf(equalityChecks(`$$${name}`, item, depth + 1))
|
|
216
|
+
} });
|
|
217
|
+
} else if (Array.isArray(item)) {
|
|
218
|
+
const elements = item.flatMap((el, i) => equalityChecks({ $arrayElemAt: [expr, i] }, el, depth));
|
|
219
|
+
checks.push({ $cond: [
|
|
220
|
+
{ $isArray: expr },
|
|
221
|
+
allOf([{ $eq: [{ $size: expr }, item.length] }, ...elements]),
|
|
222
|
+
false
|
|
223
|
+
] });
|
|
224
|
+
} else {
|
|
225
|
+
const entries = Object.entries(item).filter(([, v]) => v !== void 0);
|
|
226
|
+
const isObject = { $eq: [{ $type: expr }, "object"] };
|
|
227
|
+
checks.push({ $eq: [{ $cond: [
|
|
228
|
+
isObject,
|
|
229
|
+
{ $size: { $objectToArray: expr } },
|
|
230
|
+
-1
|
|
231
|
+
] }, entries.length] });
|
|
232
|
+
for (const [name, value] of entries) if (isPathSegment(name)) equalityChecks(`${expr}.${name}`, value, depth, checks);
|
|
233
|
+
else {
|
|
234
|
+
const field = { $getField: {
|
|
235
|
+
field: { $literal: name },
|
|
236
|
+
input: expr
|
|
237
|
+
} };
|
|
238
|
+
checks.push({ $cond: [
|
|
239
|
+
isObject,
|
|
240
|
+
allOf(equalityChecks(field, value, depth)),
|
|
241
|
+
false
|
|
242
|
+
] });
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
return checks;
|
|
246
|
+
}
|
|
247
|
+
/** Condition: the value of `expr` equals `item` (see {@link equalityChecks}). */
|
|
248
|
+
function equalsItem(expr, item) {
|
|
249
|
+
return allOf(equalityChecks(expr, item, 0));
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Condition: array `arr` has an element equal to `item` — BSON `$in` when
|
|
253
|
+
* the item holds no object (it is exact then), else {@link equalsItem}.
|
|
254
|
+
*/
|
|
255
|
+
function holdsItem(arr, item) {
|
|
256
|
+
return holdsObject(item) ? { $anyElementTrue: { $map: {
|
|
257
|
+
input: arr,
|
|
258
|
+
as: "el",
|
|
259
|
+
in: equalsItem("$$el", item)
|
|
260
|
+
} } } : { $in: [{ $literal: item }, arr] };
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
158
263
|
* A field's current value in an aggregation pipeline update — a missing field
|
|
159
264
|
* counts as `0`, like the `$inc` / `$mul` update operators (the pipeline
|
|
160
265
|
* `$add` / `$multiply` would yield `null`) — so a document written before an
|
|
@@ -394,6 +499,32 @@ var CollectionPatcher = class {
|
|
|
394
499
|
} });
|
|
395
500
|
}
|
|
396
501
|
/**
|
|
502
|
+
* Key-less `$upsert` / unique `$insert`: each item is appended, as sent and
|
|
503
|
+
* in the order sent, unless a stored element or an earlier item equals it.
|
|
504
|
+
* One rule for every item (since 0.1.182): an item that holds an object
|
|
505
|
+
* equals whatever the order of the objects' properties, as on the other
|
|
506
|
+
* adapters — before, BSON equality, which follows stored property order,
|
|
507
|
+
* appended a re-ordered item next to the equal element; a scalar as BSON
|
|
508
|
+
* compares it, so an `ObjectId` never equals its hex string (see
|
|
509
|
+
* {@link itemForm}; before, it did when another item held an object).
|
|
510
|
+
* Stored elements stay as they are.
|
|
511
|
+
*/
|
|
512
|
+
_appendAbsent(key, input) {
|
|
513
|
+
if (!input.some(holdsObject)) {
|
|
514
|
+
this._appendUnless(key, input, { $in: ["$$this", "$$value"] });
|
|
515
|
+
return;
|
|
516
|
+
}
|
|
517
|
+
const added = distinctItems(input).map((item) => ({ $cond: [
|
|
518
|
+
holdsItem("$$arr", item),
|
|
519
|
+
[],
|
|
520
|
+
literal([item])
|
|
521
|
+
] }));
|
|
522
|
+
this._set(key, { $let: {
|
|
523
|
+
vars: { arr: { $ifNull: [`$${key}`, []] } },
|
|
524
|
+
in: { $concatArrays: ["$$arr", ...added] }
|
|
525
|
+
} });
|
|
526
|
+
}
|
|
527
|
+
/**
|
|
397
528
|
* `$insert` — what the read-modify-write of the other adapters does (since
|
|
398
529
|
* 0.1.180; before, a keyed or unique insert was an upsert / a set union):
|
|
399
530
|
* - keyed → append, skipping an item whose key is already stored
|
|
@@ -403,7 +534,7 @@ var CollectionPatcher = class {
|
|
|
403
534
|
_insert(key, input, keys, flatType) {
|
|
404
535
|
if (!input?.length) return;
|
|
405
536
|
if (keys.length > 0) this._appendUnless(key, input, this._keyStored(keys));
|
|
406
|
-
else if (flatType.metadata?.has("expect.array.uniqueItems")) this.
|
|
537
|
+
else if (flatType.metadata?.has("expect.array.uniqueItems")) this._appendAbsent(key, input);
|
|
407
538
|
else this._set(key, { $concatArrays: [{ $ifNull: [`$${key}`, []] }, literal(input)] });
|
|
408
539
|
}
|
|
409
540
|
/**
|
|
@@ -417,7 +548,7 @@ var CollectionPatcher = class {
|
|
|
417
548
|
_upsert(key, input, keys, flatType) {
|
|
418
549
|
if (!input?.length) return;
|
|
419
550
|
if (keys.length === 0) {
|
|
420
|
-
this.
|
|
551
|
+
this._appendAbsent(key, input);
|
|
421
552
|
return;
|
|
422
553
|
}
|
|
423
554
|
const mergeStrategy = flatType.metadata?.get("db.patch.strategy") === "merge";
|
|
@@ -477,11 +608,16 @@ var CollectionPatcher = class {
|
|
|
477
608
|
} } } }
|
|
478
609
|
} }
|
|
479
610
|
} });
|
|
480
|
-
else
|
|
481
|
-
input
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
611
|
+
else {
|
|
612
|
+
const scalars = input.filter((item) => !holdsObject(item));
|
|
613
|
+
const equal = distinctItems(input.filter(holdsObject)).map((item) => equalsItem("$$el", item));
|
|
614
|
+
if (scalars.length > 0) equal.unshift({ $in: ["$$el", literal(scalars)] });
|
|
615
|
+
this._set(key, { $filter: {
|
|
616
|
+
input: stored,
|
|
617
|
+
as: "el",
|
|
618
|
+
cond: { $not: anyOf(equal) }
|
|
619
|
+
} });
|
|
620
|
+
}
|
|
485
621
|
}
|
|
486
622
|
};
|
|
487
623
|
/**
|
|
@@ -1232,25 +1368,47 @@ function textRunOptions(plan, query) {
|
|
|
1232
1368
|
defaultSort: RELEVANCE_SORT
|
|
1233
1369
|
} : {};
|
|
1234
1370
|
}
|
|
1371
|
+
/**
|
|
1372
|
+
* Field the `vectorSearchScore` rides in through the pipeline. Renamed to the
|
|
1373
|
+
* public `$score` after fetch — a field name cannot start with `$`.
|
|
1374
|
+
*/
|
|
1375
|
+
const SCORE_FIELD = "__atscript_score";
|
|
1235
1376
|
/** Vector search via $vectorSearch aggregation stage. */
|
|
1236
1377
|
async function vectorSearchImpl(host, vector, query, indexName) {
|
|
1237
1378
|
const controls = query.controls || {};
|
|
1238
1379
|
const plan = buildVectorSearchPlan(host, vector, query, indexName);
|
|
1239
1380
|
const threshold = resolveThreshold(host, controls, indexName);
|
|
1240
|
-
return runSearchPipeline(host, plan.stage, query, "vectorSearch", {
|
|
1241
|
-
threshold,
|
|
1381
|
+
return (await runSearchPipeline(host, plan.stage, query, "vectorSearch", {
|
|
1382
|
+
vector: { threshold },
|
|
1242
1383
|
filterStages: plan.filterStages
|
|
1243
|
-
});
|
|
1384
|
+
})).map((row) => renameComputed(row, SCORE_FIELD, "$score"));
|
|
1244
1385
|
}
|
|
1245
1386
|
/** Vector search with faceted count. */
|
|
1246
1387
|
async function vectorSearchWithCountImpl(host, vector, query, indexName) {
|
|
1247
1388
|
const controls = query.controls || {};
|
|
1248
1389
|
const plan = buildVectorSearchPlan(host, vector, query, indexName);
|
|
1249
1390
|
const threshold = resolveThreshold(host, controls, indexName);
|
|
1250
|
-
|
|
1251
|
-
threshold,
|
|
1391
|
+
const result = await runSearchWithCountPipeline(host, plan.stage, query, "vectorSearchWithCount", {
|
|
1392
|
+
vector: { threshold },
|
|
1252
1393
|
filterStages: plan.filterStages
|
|
1253
1394
|
});
|
|
1395
|
+
return {
|
|
1396
|
+
data: result.data.map((row) => renameComputed(row, SCORE_FIELD, "$score")),
|
|
1397
|
+
count: result.count
|
|
1398
|
+
};
|
|
1399
|
+
}
|
|
1400
|
+
/**
|
|
1401
|
+
* The stages right after `$vectorSearch`: its score into {@link SCORE_FIELD}
|
|
1402
|
+
* (the `$meta` is read here, ahead of any `$facet`) and, with a threshold,
|
|
1403
|
+
* into `_score` — kept for compatibility — with the `$match` on it.
|
|
1404
|
+
*/
|
|
1405
|
+
function vectorScoreStages(threshold) {
|
|
1406
|
+
const score = { $meta: "vectorSearchScore" };
|
|
1407
|
+
if (threshold === void 0) return [{ $addFields: { [SCORE_FIELD]: score } }];
|
|
1408
|
+
return [{ $addFields: {
|
|
1409
|
+
_score: score,
|
|
1410
|
+
[SCORE_FIELD]: score
|
|
1411
|
+
} }, { $match: { _score: { $gte: threshold } } }];
|
|
1254
1412
|
}
|
|
1255
1413
|
/**
|
|
1256
1414
|
* Field name `$geoNear` writes the computed distance into. Renamed to the
|
|
@@ -1264,9 +1422,9 @@ async function geoSearchImpl(host, point, query, indexName) {
|
|
|
1264
1422
|
const pipeline = buildGeoNearStages(host, point, query, indexName);
|
|
1265
1423
|
if (controls.$skip) pipeline.push({ $skip: controls.$skip });
|
|
1266
1424
|
pipeline.push({ $limit: controls.$limit || 1e3 });
|
|
1267
|
-
|
|
1425
|
+
pushProjection(pipeline, query.controls, DISTANCE_FIELD);
|
|
1268
1426
|
host._log("aggregate (geoSearch)", pipeline);
|
|
1269
|
-
return (await wrapInvalidQuery(() => host.collection.aggregate(pipeline, host._getSessionOpts()).toArray())).map((row) =>
|
|
1427
|
+
return (await wrapInvalidQuery(() => host.collection.aggregate(pipeline, host._getSessionOpts()).toArray())).map((row) => renameComputed(row, DISTANCE_FIELD, "$distance"));
|
|
1270
1428
|
}
|
|
1271
1429
|
/** Geo search with faceted count (rows within the distance window). */
|
|
1272
1430
|
async function geoSearchWithCountImpl(host, point, query, indexName) {
|
|
@@ -1274,7 +1432,7 @@ async function geoSearchWithCountImpl(host, point, query, indexName) {
|
|
|
1274
1432
|
const dataStages = [];
|
|
1275
1433
|
if (controls.$skip) dataStages.push({ $skip: controls.$skip });
|
|
1276
1434
|
if (controls.$limit) dataStages.push({ $limit: controls.$limit });
|
|
1277
|
-
|
|
1435
|
+
pushProjection(dataStages, query.controls, DISTANCE_FIELD);
|
|
1278
1436
|
const pipeline = [...buildGeoNearStages(host, point, query, indexName), { $facet: {
|
|
1279
1437
|
data: dataStages,
|
|
1280
1438
|
meta: [{ $count: "count" }]
|
|
@@ -1282,7 +1440,7 @@ async function geoSearchWithCountImpl(host, point, query, indexName) {
|
|
|
1282
1440
|
host._log("aggregate (geoSearchWithCount)", pipeline);
|
|
1283
1441
|
const result = await wrapInvalidQuery(() => host.collection.aggregate(pipeline, host._getSessionOpts()).toArray());
|
|
1284
1442
|
return {
|
|
1285
|
-
data: (result[0]?.data || []).map((row) =>
|
|
1443
|
+
data: (result[0]?.data || []).map((row) => renameComputed(row, DISTANCE_FIELD, "$distance")),
|
|
1286
1444
|
count: result[0]?.meta?.[0]?.count || 0
|
|
1287
1445
|
};
|
|
1288
1446
|
}
|
|
@@ -1323,27 +1481,28 @@ function resolveGeoKeyPath(host, indexName) {
|
|
|
1323
1481
|
return field;
|
|
1324
1482
|
}
|
|
1325
1483
|
/**
|
|
1326
|
-
* Appends
|
|
1327
|
-
*
|
|
1328
|
-
* hand back the caller's own
|
|
1329
|
-
*
|
|
1330
|
-
*
|
|
1484
|
+
* Appends the `$select` `$project` stage, keeping the computed field `keep`
|
|
1485
|
+
* (the geo distance, the vector score) in inclusion mode. That key goes on a
|
|
1486
|
+
* COPY: `asProjection` (and `dedupeProjection`) hand back the caller's own
|
|
1487
|
+
* `$select` map when nothing needs rewriting — an object the caller may share
|
|
1488
|
+
* across queries (moost-db memoizes, and in dev / test deep-freezes, the
|
|
1489
|
+
* projection of a read without `$select`).
|
|
1331
1490
|
*/
|
|
1332
|
-
function
|
|
1491
|
+
function pushProjection(stages, controls, keep) {
|
|
1333
1492
|
const projection = controls?.$select?.asProjection;
|
|
1334
1493
|
if (!projection) return;
|
|
1335
1494
|
const deduped = dedupeProjection(projection);
|
|
1336
|
-
const isInclusion = Object.values(deduped).some((v) => v === 1);
|
|
1495
|
+
const isInclusion = keep !== void 0 && Object.values(deduped).some((v) => v === 1);
|
|
1337
1496
|
stages.push({ $project: isInclusion ? {
|
|
1338
1497
|
...deduped,
|
|
1339
|
-
[
|
|
1498
|
+
[keep]: 1
|
|
1340
1499
|
} : deduped });
|
|
1341
1500
|
}
|
|
1342
|
-
/** Renames
|
|
1343
|
-
function
|
|
1344
|
-
if (
|
|
1345
|
-
row
|
|
1346
|
-
delete row[
|
|
1501
|
+
/** Renames an internal computed field to its public `$`-prefixed name (in place). */
|
|
1502
|
+
function renameComputed(row, field, name) {
|
|
1503
|
+
if (field in row) {
|
|
1504
|
+
row[name] = row[field];
|
|
1505
|
+
delete row[field];
|
|
1347
1506
|
}
|
|
1348
1507
|
return row;
|
|
1349
1508
|
}
|
|
@@ -1639,13 +1798,11 @@ function buildVectorSearchStage(host, vector, indexName, limit, skip) {
|
|
|
1639
1798
|
};
|
|
1640
1799
|
}
|
|
1641
1800
|
/** Runs a search/vector pipeline and returns results. Shared by search + vectorSearch. */
|
|
1642
|
-
async function runSearchPipeline(host, stage, query, label, {
|
|
1801
|
+
async function runSearchPipeline(host, stage, query, label, { vector, classicText = false, defaultSort, filterStages } = {}) {
|
|
1643
1802
|
const controls = query.controls || {};
|
|
1644
1803
|
const pipeline = [stage];
|
|
1645
|
-
if (threshold
|
|
1646
|
-
|
|
1647
|
-
pipeline.push({ $match: { _score: { $gte: threshold } } });
|
|
1648
|
-
} else if (classicText) pipeline.push({ $addFields: { _score: { $meta: "textScore" } } });
|
|
1804
|
+
if (vector) pipeline.push(...vectorScoreStages(vector.threshold));
|
|
1805
|
+
else if (classicText) pipeline.push({ $addFields: { _score: { $meta: "textScore" } } });
|
|
1649
1806
|
pipeline.push(...filterStages ?? require_mongo_accumulator.mongoFilterStages(query.filter, filterOptionsOf(host)));
|
|
1650
1807
|
const { stages: sorted, cleanup } = require_mongo_accumulator.sortStages(controls);
|
|
1651
1808
|
if (sorted.length > 0) pipeline.push(...sorted);
|
|
@@ -1654,10 +1811,7 @@ async function runSearchPipeline(host, stage, query, label, { threshold, classic
|
|
|
1654
1811
|
if (controls.$limit) pipeline.push({ $limit: controls.$limit });
|
|
1655
1812
|
else pipeline.push({ $limit: 1e3 });
|
|
1656
1813
|
if (cleanup) pipeline.push(cleanup);
|
|
1657
|
-
|
|
1658
|
-
const projection = controls.$select.asProjection;
|
|
1659
|
-
if (projection) pipeline.push({ $project: dedupeProjection(projection) });
|
|
1660
|
-
}
|
|
1814
|
+
pushProjection(pipeline, controls, vector ? SCORE_FIELD : void 0);
|
|
1661
1815
|
host._log(`aggregate (${label})`, pipeline);
|
|
1662
1816
|
return wrapInvalidQuery(() => host.collection.aggregate(pipeline, host._getSessionOpts()).toArray());
|
|
1663
1817
|
}
|
|
@@ -1671,22 +1825,17 @@ async function runSearchPipeline(host, stage, query, label, { threshold, classic
|
|
|
1671
1825
|
* `count: total` — the same counts `$$SEARCH_META` reports), concurrently
|
|
1672
1826
|
* outside a transaction.
|
|
1673
1827
|
*/
|
|
1674
|
-
async function runSearchWithCountPipeline(host, stage, query, label, {
|
|
1828
|
+
async function runSearchWithCountPipeline(host, stage, query, label, { vector, classicText = false, defaultSort, filterStages } = {}) {
|
|
1675
1829
|
const controls = query.controls || {};
|
|
1676
1830
|
const preStages = [];
|
|
1677
|
-
if (threshold
|
|
1678
|
-
|
|
1679
|
-
preStages.push({ $match: { _score: { $gte: threshold } } });
|
|
1680
|
-
} else if (classicText) preStages.push({ $addFields: { _score: { $meta: "textScore" } } });
|
|
1831
|
+
if (vector) preStages.push(...vectorScoreStages(vector.threshold));
|
|
1832
|
+
else if (classicText) preStages.push({ $addFields: { _score: { $meta: "textScore" } } });
|
|
1681
1833
|
const { stages: dataStages, cleanup } = require_mongo_accumulator.sortStages(controls);
|
|
1682
1834
|
if (dataStages.length === 0 && defaultSort) dataStages.push(defaultSort);
|
|
1683
1835
|
if (controls.$skip) dataStages.push({ $skip: controls.$skip });
|
|
1684
1836
|
if (controls.$limit) dataStages.push({ $limit: controls.$limit });
|
|
1685
1837
|
if (cleanup) dataStages.push(cleanup);
|
|
1686
|
-
|
|
1687
|
-
const projection = controls.$select.asProjection;
|
|
1688
|
-
if (projection) dataStages.push({ $project: dedupeProjection(projection) });
|
|
1689
|
-
}
|
|
1838
|
+
pushProjection(dataStages, controls, vector ? SCORE_FIELD : void 0);
|
|
1690
1839
|
const stages = filterStages ?? require_mongo_accumulator.mongoFilterStages(query.filter, filterOptionsOf(host));
|
|
1691
1840
|
if ("$search" in stage && preStages.length === 0 && stages.every(isNoopMatch)) return runSearchWithMeta(host, stage, dataStages, label);
|
|
1692
1841
|
const pipeline = [
|
|
@@ -2809,7 +2958,52 @@ var MongoAdapter = class MongoAdapter extends _atscript_db.BaseDbAdapter {
|
|
|
2809
2958
|
matchedCount: 0,
|
|
2810
2959
|
modifiedCount: 0
|
|
2811
2960
|
};
|
|
2812
|
-
const
|
|
2961
|
+
const { updateFilter, updateOptions } = this._patchPipeline(patch, ops, this._versionColumnFor(opts, expectedVersion));
|
|
2962
|
+
if (updateFilter.length === 0) return this._countUnpatched(mongoFilter, { limit: 1 });
|
|
2963
|
+
this._log("updateOne (patch)", mongoFilter, updateFilter);
|
|
2964
|
+
return this._wrapUpdate(() => this.collection.updateOne(mongoFilter, updateFilter, {
|
|
2965
|
+
...updateOptions,
|
|
2966
|
+
...this._getSessionOpts()
|
|
2967
|
+
}));
|
|
2968
|
+
}
|
|
2969
|
+
/**
|
|
2970
|
+
* `updateMany` with array operators (since 0.1.182): the pipeline
|
|
2971
|
+
* {@link nativePatch} builds, in one `updateMany` over every matching
|
|
2972
|
+
* document — per batch of matching `_id`s for a filter holding relational
|
|
2973
|
+
* predicates. Never CAS-checks; bumps the version unless `opts.keepVersion`.
|
|
2974
|
+
*/
|
|
2975
|
+
async nativePatchMany(filter, patch, ops, opts) {
|
|
2976
|
+
const { updateFilter, updateOptions } = this._patchPipeline(patch, ops, this._versionColumnFor(opts));
|
|
2977
|
+
return this._updateMatching(filter, (mongoFilter) => {
|
|
2978
|
+
if (updateFilter.length === 0) return this._countUnpatched(mongoFilter);
|
|
2979
|
+
this._log("updateMany (patch)", mongoFilter, updateFilter);
|
|
2980
|
+
return this._wrapUpdate(() => this.collection.updateMany(mongoFilter, updateFilter, {
|
|
2981
|
+
...updateOptions,
|
|
2982
|
+
...this._getSessionOpts()
|
|
2983
|
+
}));
|
|
2984
|
+
});
|
|
2985
|
+
}
|
|
2986
|
+
/**
|
|
2987
|
+
* A patch with nothing to set: the driver rejects an empty pipeline, so the
|
|
2988
|
+
* matching documents are only counted.
|
|
2989
|
+
*/
|
|
2990
|
+
async _countUnpatched(mongoFilter, opts) {
|
|
2991
|
+
this._log("countDocuments (empty patch)", mongoFilter);
|
|
2992
|
+
return {
|
|
2993
|
+
matchedCount: await this.collection.countDocuments(mongoFilter, {
|
|
2994
|
+
...opts,
|
|
2995
|
+
...this._getSessionOpts()
|
|
2996
|
+
}),
|
|
2997
|
+
modifiedCount: 0
|
|
2998
|
+
};
|
|
2999
|
+
}
|
|
3000
|
+
/**
|
|
3001
|
+
* The update pipeline of a patch (`CollectionPatcher`), with the version
|
|
3002
|
+
* auto-bump injected into `ops.inc` so the patcher emits it as a
|
|
3003
|
+
* `version = version + 1` aggregation expression alongside any
|
|
3004
|
+
* user-supplied `$inc` / `$mul` ops.
|
|
3005
|
+
*/
|
|
3006
|
+
_patchPipeline(patch, ops, versionColumn) {
|
|
2813
3007
|
const effectiveOps = versionColumn !== void 0 ? {
|
|
2814
3008
|
...ops,
|
|
2815
3009
|
inc: {
|
|
@@ -2817,22 +3011,7 @@ var MongoAdapter = class MongoAdapter extends _atscript_db.BaseDbAdapter {
|
|
|
2817
3011
|
[versionColumn]: 1
|
|
2818
3012
|
}
|
|
2819
3013
|
} : ops;
|
|
2820
|
-
|
|
2821
|
-
if (updateFilter.length === 0) {
|
|
2822
|
-
this._log("countDocuments (empty patch)", mongoFilter);
|
|
2823
|
-
return {
|
|
2824
|
-
matchedCount: await this.collection.countDocuments(mongoFilter, {
|
|
2825
|
-
limit: 1,
|
|
2826
|
-
...this._getSessionOpts()
|
|
2827
|
-
}),
|
|
2828
|
-
modifiedCount: 0
|
|
2829
|
-
};
|
|
2830
|
-
}
|
|
2831
|
-
this._log("updateOne (patch)", mongoFilter, updateFilter);
|
|
2832
|
-
return this._wrapUpdate(() => this.collection.updateOne(mongoFilter, updateFilter, {
|
|
2833
|
-
...updateOptions,
|
|
2834
|
-
...this._getSessionOpts()
|
|
2835
|
-
}));
|
|
3014
|
+
return new CollectionPatcher(this.getPatcherContext(), patch, effectiveOps).preparePatch();
|
|
2836
3015
|
}
|
|
2837
3016
|
onBeforeFlatten(_type) {
|
|
2838
3017
|
const typeMeta = _type.metadata;
|
package/dist/index.d.cts
CHANGED
|
@@ -139,6 +139,18 @@ declare class CollectionPatcher {
|
|
|
139
139
|
* array as it is) is the result.
|
|
140
140
|
*/
|
|
141
141
|
private _appendUnless;
|
|
142
|
+
/**
|
|
143
|
+
* Key-less `$upsert` / unique `$insert`: each item is appended, as sent and
|
|
144
|
+
* in the order sent, unless a stored element or an earlier item equals it.
|
|
145
|
+
* One rule for every item (since 0.1.182): an item that holds an object
|
|
146
|
+
* equals whatever the order of the objects' properties, as on the other
|
|
147
|
+
* adapters — before, BSON equality, which follows stored property order,
|
|
148
|
+
* appended a re-ordered item next to the equal element; a scalar as BSON
|
|
149
|
+
* compares it, so an `ObjectId` never equals its hex string (see
|
|
150
|
+
* {@link itemForm}; before, it did when another item held an object).
|
|
151
|
+
* Stored elements stay as they are.
|
|
152
|
+
*/
|
|
153
|
+
private _appendAbsent;
|
|
142
154
|
/**
|
|
143
155
|
* `$insert` — what the read-modify-write of the other adapters does (since
|
|
144
156
|
* 0.1.180; before, a keyed or unique insert was an upsert / a set union):
|
|
@@ -506,6 +518,25 @@ declare class MongoAdapter extends BaseDbAdapter {
|
|
|
506
518
|
*/
|
|
507
519
|
private _patcherFlatMap;
|
|
508
520
|
nativePatch(filter: FilterExpr, patch: unknown, ops?: TFieldOps, expectedVersion?: number, opts?: TDbUpdateOptions): Promise<TDbUpdateResult>;
|
|
521
|
+
/**
|
|
522
|
+
* `updateMany` with array operators (since 0.1.182): the pipeline
|
|
523
|
+
* {@link nativePatch} builds, in one `updateMany` over every matching
|
|
524
|
+
* document — per batch of matching `_id`s for a filter holding relational
|
|
525
|
+
* predicates. Never CAS-checks; bumps the version unless `opts.keepVersion`.
|
|
526
|
+
*/
|
|
527
|
+
nativePatchMany(filter: FilterExpr, patch: unknown, ops?: TFieldOps, opts?: TDbUpdateOptions): Promise<TDbUpdateResult>;
|
|
528
|
+
/**
|
|
529
|
+
* A patch with nothing to set: the driver rejects an empty pipeline, so the
|
|
530
|
+
* matching documents are only counted.
|
|
531
|
+
*/
|
|
532
|
+
private _countUnpatched;
|
|
533
|
+
/**
|
|
534
|
+
* The update pipeline of a patch (`CollectionPatcher`), with the version
|
|
535
|
+
* auto-bump injected into `ops.inc` so the patcher emits it as a
|
|
536
|
+
* `version = version + 1` aggregation expression alongside any
|
|
537
|
+
* user-supplied `$inc` / `$mul` ops.
|
|
538
|
+
*/
|
|
539
|
+
private _patchPipeline;
|
|
509
540
|
onBeforeFlatten(_type: unknown): void;
|
|
510
541
|
onFieldScanned(field: string, _type: unknown, metadata: TMetadataMap<AtscriptMetadata>): void;
|
|
511
542
|
getMetadataOverrides(meta: TableMetadata): TMetadataOverrides;
|
package/dist/index.d.mts
CHANGED
|
@@ -139,6 +139,18 @@ declare class CollectionPatcher {
|
|
|
139
139
|
* array as it is) is the result.
|
|
140
140
|
*/
|
|
141
141
|
private _appendUnless;
|
|
142
|
+
/**
|
|
143
|
+
* Key-less `$upsert` / unique `$insert`: each item is appended, as sent and
|
|
144
|
+
* in the order sent, unless a stored element or an earlier item equals it.
|
|
145
|
+
* One rule for every item (since 0.1.182): an item that holds an object
|
|
146
|
+
* equals whatever the order of the objects' properties, as on the other
|
|
147
|
+
* adapters — before, BSON equality, which follows stored property order,
|
|
148
|
+
* appended a re-ordered item next to the equal element; a scalar as BSON
|
|
149
|
+
* compares it, so an `ObjectId` never equals its hex string (see
|
|
150
|
+
* {@link itemForm}; before, it did when another item held an object).
|
|
151
|
+
* Stored elements stay as they are.
|
|
152
|
+
*/
|
|
153
|
+
private _appendAbsent;
|
|
142
154
|
/**
|
|
143
155
|
* `$insert` — what the read-modify-write of the other adapters does (since
|
|
144
156
|
* 0.1.180; before, a keyed or unique insert was an upsert / a set union):
|
|
@@ -506,6 +518,25 @@ declare class MongoAdapter extends BaseDbAdapter {
|
|
|
506
518
|
*/
|
|
507
519
|
private _patcherFlatMap;
|
|
508
520
|
nativePatch(filter: FilterExpr, patch: unknown, ops?: TFieldOps, expectedVersion?: number, opts?: TDbUpdateOptions): Promise<TDbUpdateResult>;
|
|
521
|
+
/**
|
|
522
|
+
* `updateMany` with array operators (since 0.1.182): the pipeline
|
|
523
|
+
* {@link nativePatch} builds, in one `updateMany` over every matching
|
|
524
|
+
* document — per batch of matching `_id`s for a filter holding relational
|
|
525
|
+
* predicates. Never CAS-checks; bumps the version unless `opts.keepVersion`.
|
|
526
|
+
*/
|
|
527
|
+
nativePatchMany(filter: FilterExpr, patch: unknown, ops?: TFieldOps, opts?: TDbUpdateOptions): Promise<TDbUpdateResult>;
|
|
528
|
+
/**
|
|
529
|
+
* A patch with nothing to set: the driver rejects an empty pipeline, so the
|
|
530
|
+
* matching documents are only counted.
|
|
531
|
+
*/
|
|
532
|
+
private _countUnpatched;
|
|
533
|
+
/**
|
|
534
|
+
* The update pipeline of a patch (`CollectionPatcher`), with the version
|
|
535
|
+
* auto-bump injected into `ops.inc` so the patcher emits it as a
|
|
536
|
+
* `version = version + 1` aggregation expression alongside any
|
|
537
|
+
* user-supplied `$inc` / `$mul` ops.
|
|
538
|
+
*/
|
|
539
|
+
private _patchPipeline;
|
|
509
540
|
onBeforeFlatten(_type: unknown): void;
|
|
510
541
|
onFieldScanned(field: string, _type: unknown, metadata: TMetadataMap<AtscriptMetadata>): void;
|
|
511
542
|
getMetadataOverrides(meta: TableMetadata): TMetadataOverrides;
|
package/dist/index.mjs
CHANGED
|
@@ -154,6 +154,111 @@ function containsAggregationExpr(v) {
|
|
|
154
154
|
return false;
|
|
155
155
|
}
|
|
156
156
|
/**
|
|
157
|
+
* Whether `value` holds a plain object at any depth. Only then can BSON
|
|
158
|
+
* equality (`$in` / `$eq`, which follows stored property order) differ from
|
|
159
|
+
* the comparison of the other adapters, which ignores property order.
|
|
160
|
+
*/
|
|
161
|
+
function holdsObject(value) {
|
|
162
|
+
return Array.isArray(value) ? value.some(holdsObject) : isPlainObject(value);
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* The form two operator items are the same by: JSON text with every object's
|
|
166
|
+
* keys sorted (as `stableJson` writes it) — what the other adapters compare
|
|
167
|
+
* elements without key props by — except that a value JSON cannot represent
|
|
168
|
+
* (an `ObjectId`, a `Date`, …) keeps its BSON type, as `$in` / `$eq` compare
|
|
169
|
+
* it: an `ObjectId` never equals its hex string, nor a `Date` its ISO text.
|
|
170
|
+
*/
|
|
171
|
+
function itemForm(item) {
|
|
172
|
+
return JSON.stringify([item], function(key, value) {
|
|
173
|
+
const raw = this[key];
|
|
174
|
+
if (raw !== null && typeof raw === "object" && !Array.isArray(raw) && !isPlainObject(raw)) return `\u0000${raw.constructor?.name}:${JSON.stringify(value)}`;
|
|
175
|
+
return isPlainObject(value) ? Object.fromEntries(Object.entries(value).toSorted(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) : value;
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* `items` without those the same as an earlier one ({@link itemForm}) — what
|
|
180
|
+
* an operator that skips repeated items drops before it reaches the server.
|
|
181
|
+
*/
|
|
182
|
+
function distinctItems(items) {
|
|
183
|
+
const seen = /* @__PURE__ */ new Set();
|
|
184
|
+
return items.filter((item) => {
|
|
185
|
+
const form = itemForm(item);
|
|
186
|
+
if (seen.has(form)) return false;
|
|
187
|
+
seen.add(form);
|
|
188
|
+
return true;
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
const allOf = (checks) => checks.length === 1 ? checks[0] : { $and: checks };
|
|
192
|
+
const anyOf = (checks) => checks.length === 1 ? checks[0] : { $or: checks };
|
|
193
|
+
/** Whether a property name can follow a variable in a field path (`$$el.<name>`). */
|
|
194
|
+
const isPathSegment = (name) => name !== "" && !name.includes(".") && !name.startsWith("$") && !name.includes("\0");
|
|
195
|
+
/**
|
|
196
|
+
* Appends to `checks` aggregation conditions that all hold exactly when the
|
|
197
|
+
* value of `expr` equals `item` the way the other adapters compare elements
|
|
198
|
+
* without key props: an object whatever the order of its properties, at
|
|
199
|
+
* every depth; an array element by element, in order; a scalar as BSON
|
|
200
|
+
* compares it; a missing property is not `null`. The conditions follow the
|
|
201
|
+
* item's structure — stored structure deeper than the item cannot equal it —
|
|
202
|
+
* and each one is safe to evaluate on any stored value.
|
|
203
|
+
*
|
|
204
|
+
* `depth` names the variables a nested array element is bound to (`v0`,
|
|
205
|
+
* `v1`, … from the outside in). Item values are `$literal`s.
|
|
206
|
+
*/
|
|
207
|
+
function equalityChecks(expr, item, depth, checks = []) {
|
|
208
|
+
if (item === null || item === void 0) checks.push({ $eq: [{ $type: expr }, "null"] });
|
|
209
|
+
else if (!holdsObject(item)) checks.push({ $eq: [expr, { $literal: item }] });
|
|
210
|
+
else if (typeof expr !== "string") {
|
|
211
|
+
const name = `v${depth}`;
|
|
212
|
+
checks.push({ $let: {
|
|
213
|
+
vars: { [name]: expr },
|
|
214
|
+
in: allOf(equalityChecks(`$$${name}`, item, depth + 1))
|
|
215
|
+
} });
|
|
216
|
+
} else if (Array.isArray(item)) {
|
|
217
|
+
const elements = item.flatMap((el, i) => equalityChecks({ $arrayElemAt: [expr, i] }, el, depth));
|
|
218
|
+
checks.push({ $cond: [
|
|
219
|
+
{ $isArray: expr },
|
|
220
|
+
allOf([{ $eq: [{ $size: expr }, item.length] }, ...elements]),
|
|
221
|
+
false
|
|
222
|
+
] });
|
|
223
|
+
} else {
|
|
224
|
+
const entries = Object.entries(item).filter(([, v]) => v !== void 0);
|
|
225
|
+
const isObject = { $eq: [{ $type: expr }, "object"] };
|
|
226
|
+
checks.push({ $eq: [{ $cond: [
|
|
227
|
+
isObject,
|
|
228
|
+
{ $size: { $objectToArray: expr } },
|
|
229
|
+
-1
|
|
230
|
+
] }, entries.length] });
|
|
231
|
+
for (const [name, value] of entries) if (isPathSegment(name)) equalityChecks(`${expr}.${name}`, value, depth, checks);
|
|
232
|
+
else {
|
|
233
|
+
const field = { $getField: {
|
|
234
|
+
field: { $literal: name },
|
|
235
|
+
input: expr
|
|
236
|
+
} };
|
|
237
|
+
checks.push({ $cond: [
|
|
238
|
+
isObject,
|
|
239
|
+
allOf(equalityChecks(field, value, depth)),
|
|
240
|
+
false
|
|
241
|
+
] });
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
return checks;
|
|
245
|
+
}
|
|
246
|
+
/** Condition: the value of `expr` equals `item` (see {@link equalityChecks}). */
|
|
247
|
+
function equalsItem(expr, item) {
|
|
248
|
+
return allOf(equalityChecks(expr, item, 0));
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Condition: array `arr` has an element equal to `item` — BSON `$in` when
|
|
252
|
+
* the item holds no object (it is exact then), else {@link equalsItem}.
|
|
253
|
+
*/
|
|
254
|
+
function holdsItem(arr, item) {
|
|
255
|
+
return holdsObject(item) ? { $anyElementTrue: { $map: {
|
|
256
|
+
input: arr,
|
|
257
|
+
as: "el",
|
|
258
|
+
in: equalsItem("$$el", item)
|
|
259
|
+
} } } : { $in: [{ $literal: item }, arr] };
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
157
262
|
* A field's current value in an aggregation pipeline update — a missing field
|
|
158
263
|
* counts as `0`, like the `$inc` / `$mul` update operators (the pipeline
|
|
159
264
|
* `$add` / `$multiply` would yield `null`) — so a document written before an
|
|
@@ -393,6 +498,32 @@ var CollectionPatcher = class {
|
|
|
393
498
|
} });
|
|
394
499
|
}
|
|
395
500
|
/**
|
|
501
|
+
* Key-less `$upsert` / unique `$insert`: each item is appended, as sent and
|
|
502
|
+
* in the order sent, unless a stored element or an earlier item equals it.
|
|
503
|
+
* One rule for every item (since 0.1.182): an item that holds an object
|
|
504
|
+
* equals whatever the order of the objects' properties, as on the other
|
|
505
|
+
* adapters — before, BSON equality, which follows stored property order,
|
|
506
|
+
* appended a re-ordered item next to the equal element; a scalar as BSON
|
|
507
|
+
* compares it, so an `ObjectId` never equals its hex string (see
|
|
508
|
+
* {@link itemForm}; before, it did when another item held an object).
|
|
509
|
+
* Stored elements stay as they are.
|
|
510
|
+
*/
|
|
511
|
+
_appendAbsent(key, input) {
|
|
512
|
+
if (!input.some(holdsObject)) {
|
|
513
|
+
this._appendUnless(key, input, { $in: ["$$this", "$$value"] });
|
|
514
|
+
return;
|
|
515
|
+
}
|
|
516
|
+
const added = distinctItems(input).map((item) => ({ $cond: [
|
|
517
|
+
holdsItem("$$arr", item),
|
|
518
|
+
[],
|
|
519
|
+
literal([item])
|
|
520
|
+
] }));
|
|
521
|
+
this._set(key, { $let: {
|
|
522
|
+
vars: { arr: { $ifNull: [`$${key}`, []] } },
|
|
523
|
+
in: { $concatArrays: ["$$arr", ...added] }
|
|
524
|
+
} });
|
|
525
|
+
}
|
|
526
|
+
/**
|
|
396
527
|
* `$insert` — what the read-modify-write of the other adapters does (since
|
|
397
528
|
* 0.1.180; before, a keyed or unique insert was an upsert / a set union):
|
|
398
529
|
* - keyed → append, skipping an item whose key is already stored
|
|
@@ -402,7 +533,7 @@ var CollectionPatcher = class {
|
|
|
402
533
|
_insert(key, input, keys, flatType) {
|
|
403
534
|
if (!input?.length) return;
|
|
404
535
|
if (keys.length > 0) this._appendUnless(key, input, this._keyStored(keys));
|
|
405
|
-
else if (flatType.metadata?.has("expect.array.uniqueItems")) this.
|
|
536
|
+
else if (flatType.metadata?.has("expect.array.uniqueItems")) this._appendAbsent(key, input);
|
|
406
537
|
else this._set(key, { $concatArrays: [{ $ifNull: [`$${key}`, []] }, literal(input)] });
|
|
407
538
|
}
|
|
408
539
|
/**
|
|
@@ -416,7 +547,7 @@ var CollectionPatcher = class {
|
|
|
416
547
|
_upsert(key, input, keys, flatType) {
|
|
417
548
|
if (!input?.length) return;
|
|
418
549
|
if (keys.length === 0) {
|
|
419
|
-
this.
|
|
550
|
+
this._appendAbsent(key, input);
|
|
420
551
|
return;
|
|
421
552
|
}
|
|
422
553
|
const mergeStrategy = flatType.metadata?.get("db.patch.strategy") === "merge";
|
|
@@ -476,11 +607,16 @@ var CollectionPatcher = class {
|
|
|
476
607
|
} } } }
|
|
477
608
|
} }
|
|
478
609
|
} });
|
|
479
|
-
else
|
|
480
|
-
input
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
610
|
+
else {
|
|
611
|
+
const scalars = input.filter((item) => !holdsObject(item));
|
|
612
|
+
const equal = distinctItems(input.filter(holdsObject)).map((item) => equalsItem("$$el", item));
|
|
613
|
+
if (scalars.length > 0) equal.unshift({ $in: ["$$el", literal(scalars)] });
|
|
614
|
+
this._set(key, { $filter: {
|
|
615
|
+
input: stored,
|
|
616
|
+
as: "el",
|
|
617
|
+
cond: { $not: anyOf(equal) }
|
|
618
|
+
} });
|
|
619
|
+
}
|
|
484
620
|
}
|
|
485
621
|
};
|
|
486
622
|
/**
|
|
@@ -1231,25 +1367,47 @@ function textRunOptions(plan, query) {
|
|
|
1231
1367
|
defaultSort: RELEVANCE_SORT
|
|
1232
1368
|
} : {};
|
|
1233
1369
|
}
|
|
1370
|
+
/**
|
|
1371
|
+
* Field the `vectorSearchScore` rides in through the pipeline. Renamed to the
|
|
1372
|
+
* public `$score` after fetch — a field name cannot start with `$`.
|
|
1373
|
+
*/
|
|
1374
|
+
const SCORE_FIELD = "__atscript_score";
|
|
1234
1375
|
/** Vector search via $vectorSearch aggregation stage. */
|
|
1235
1376
|
async function vectorSearchImpl(host, vector, query, indexName) {
|
|
1236
1377
|
const controls = query.controls || {};
|
|
1237
1378
|
const plan = buildVectorSearchPlan(host, vector, query, indexName);
|
|
1238
1379
|
const threshold = resolveThreshold(host, controls, indexName);
|
|
1239
|
-
return runSearchPipeline(host, plan.stage, query, "vectorSearch", {
|
|
1240
|
-
threshold,
|
|
1380
|
+
return (await runSearchPipeline(host, plan.stage, query, "vectorSearch", {
|
|
1381
|
+
vector: { threshold },
|
|
1241
1382
|
filterStages: plan.filterStages
|
|
1242
|
-
});
|
|
1383
|
+
})).map((row) => renameComputed(row, SCORE_FIELD, "$score"));
|
|
1243
1384
|
}
|
|
1244
1385
|
/** Vector search with faceted count. */
|
|
1245
1386
|
async function vectorSearchWithCountImpl(host, vector, query, indexName) {
|
|
1246
1387
|
const controls = query.controls || {};
|
|
1247
1388
|
const plan = buildVectorSearchPlan(host, vector, query, indexName);
|
|
1248
1389
|
const threshold = resolveThreshold(host, controls, indexName);
|
|
1249
|
-
|
|
1250
|
-
threshold,
|
|
1390
|
+
const result = await runSearchWithCountPipeline(host, plan.stage, query, "vectorSearchWithCount", {
|
|
1391
|
+
vector: { threshold },
|
|
1251
1392
|
filterStages: plan.filterStages
|
|
1252
1393
|
});
|
|
1394
|
+
return {
|
|
1395
|
+
data: result.data.map((row) => renameComputed(row, SCORE_FIELD, "$score")),
|
|
1396
|
+
count: result.count
|
|
1397
|
+
};
|
|
1398
|
+
}
|
|
1399
|
+
/**
|
|
1400
|
+
* The stages right after `$vectorSearch`: its score into {@link SCORE_FIELD}
|
|
1401
|
+
* (the `$meta` is read here, ahead of any `$facet`) and, with a threshold,
|
|
1402
|
+
* into `_score` — kept for compatibility — with the `$match` on it.
|
|
1403
|
+
*/
|
|
1404
|
+
function vectorScoreStages(threshold) {
|
|
1405
|
+
const score = { $meta: "vectorSearchScore" };
|
|
1406
|
+
if (threshold === void 0) return [{ $addFields: { [SCORE_FIELD]: score } }];
|
|
1407
|
+
return [{ $addFields: {
|
|
1408
|
+
_score: score,
|
|
1409
|
+
[SCORE_FIELD]: score
|
|
1410
|
+
} }, { $match: { _score: { $gte: threshold } } }];
|
|
1253
1411
|
}
|
|
1254
1412
|
/**
|
|
1255
1413
|
* Field name `$geoNear` writes the computed distance into. Renamed to the
|
|
@@ -1263,9 +1421,9 @@ async function geoSearchImpl(host, point, query, indexName) {
|
|
|
1263
1421
|
const pipeline = buildGeoNearStages(host, point, query, indexName);
|
|
1264
1422
|
if (controls.$skip) pipeline.push({ $skip: controls.$skip });
|
|
1265
1423
|
pipeline.push({ $limit: controls.$limit || 1e3 });
|
|
1266
|
-
|
|
1424
|
+
pushProjection(pipeline, query.controls, DISTANCE_FIELD);
|
|
1267
1425
|
host._log("aggregate (geoSearch)", pipeline);
|
|
1268
|
-
return (await wrapInvalidQuery(() => host.collection.aggregate(pipeline, host._getSessionOpts()).toArray())).map((row) =>
|
|
1426
|
+
return (await wrapInvalidQuery(() => host.collection.aggregate(pipeline, host._getSessionOpts()).toArray())).map((row) => renameComputed(row, DISTANCE_FIELD, "$distance"));
|
|
1269
1427
|
}
|
|
1270
1428
|
/** Geo search with faceted count (rows within the distance window). */
|
|
1271
1429
|
async function geoSearchWithCountImpl(host, point, query, indexName) {
|
|
@@ -1273,7 +1431,7 @@ async function geoSearchWithCountImpl(host, point, query, indexName) {
|
|
|
1273
1431
|
const dataStages = [];
|
|
1274
1432
|
if (controls.$skip) dataStages.push({ $skip: controls.$skip });
|
|
1275
1433
|
if (controls.$limit) dataStages.push({ $limit: controls.$limit });
|
|
1276
|
-
|
|
1434
|
+
pushProjection(dataStages, query.controls, DISTANCE_FIELD);
|
|
1277
1435
|
const pipeline = [...buildGeoNearStages(host, point, query, indexName), { $facet: {
|
|
1278
1436
|
data: dataStages,
|
|
1279
1437
|
meta: [{ $count: "count" }]
|
|
@@ -1281,7 +1439,7 @@ async function geoSearchWithCountImpl(host, point, query, indexName) {
|
|
|
1281
1439
|
host._log("aggregate (geoSearchWithCount)", pipeline);
|
|
1282
1440
|
const result = await wrapInvalidQuery(() => host.collection.aggregate(pipeline, host._getSessionOpts()).toArray());
|
|
1283
1441
|
return {
|
|
1284
|
-
data: (result[0]?.data || []).map((row) =>
|
|
1442
|
+
data: (result[0]?.data || []).map((row) => renameComputed(row, DISTANCE_FIELD, "$distance")),
|
|
1285
1443
|
count: result[0]?.meta?.[0]?.count || 0
|
|
1286
1444
|
};
|
|
1287
1445
|
}
|
|
@@ -1322,27 +1480,28 @@ function resolveGeoKeyPath(host, indexName) {
|
|
|
1322
1480
|
return field;
|
|
1323
1481
|
}
|
|
1324
1482
|
/**
|
|
1325
|
-
* Appends
|
|
1326
|
-
*
|
|
1327
|
-
* hand back the caller's own
|
|
1328
|
-
*
|
|
1329
|
-
*
|
|
1483
|
+
* Appends the `$select` `$project` stage, keeping the computed field `keep`
|
|
1484
|
+
* (the geo distance, the vector score) in inclusion mode. That key goes on a
|
|
1485
|
+
* COPY: `asProjection` (and `dedupeProjection`) hand back the caller's own
|
|
1486
|
+
* `$select` map when nothing needs rewriting — an object the caller may share
|
|
1487
|
+
* across queries (moost-db memoizes, and in dev / test deep-freezes, the
|
|
1488
|
+
* projection of a read without `$select`).
|
|
1330
1489
|
*/
|
|
1331
|
-
function
|
|
1490
|
+
function pushProjection(stages, controls, keep) {
|
|
1332
1491
|
const projection = controls?.$select?.asProjection;
|
|
1333
1492
|
if (!projection) return;
|
|
1334
1493
|
const deduped = dedupeProjection(projection);
|
|
1335
|
-
const isInclusion = Object.values(deduped).some((v) => v === 1);
|
|
1494
|
+
const isInclusion = keep !== void 0 && Object.values(deduped).some((v) => v === 1);
|
|
1336
1495
|
stages.push({ $project: isInclusion ? {
|
|
1337
1496
|
...deduped,
|
|
1338
|
-
[
|
|
1497
|
+
[keep]: 1
|
|
1339
1498
|
} : deduped });
|
|
1340
1499
|
}
|
|
1341
|
-
/** Renames
|
|
1342
|
-
function
|
|
1343
|
-
if (
|
|
1344
|
-
row
|
|
1345
|
-
delete row[
|
|
1500
|
+
/** Renames an internal computed field to its public `$`-prefixed name (in place). */
|
|
1501
|
+
function renameComputed(row, field, name) {
|
|
1502
|
+
if (field in row) {
|
|
1503
|
+
row[name] = row[field];
|
|
1504
|
+
delete row[field];
|
|
1346
1505
|
}
|
|
1347
1506
|
return row;
|
|
1348
1507
|
}
|
|
@@ -1638,13 +1797,11 @@ function buildVectorSearchStage(host, vector, indexName, limit, skip) {
|
|
|
1638
1797
|
};
|
|
1639
1798
|
}
|
|
1640
1799
|
/** Runs a search/vector pipeline and returns results. Shared by search + vectorSearch. */
|
|
1641
|
-
async function runSearchPipeline(host, stage, query, label, {
|
|
1800
|
+
async function runSearchPipeline(host, stage, query, label, { vector, classicText = false, defaultSort, filterStages } = {}) {
|
|
1642
1801
|
const controls = query.controls || {};
|
|
1643
1802
|
const pipeline = [stage];
|
|
1644
|
-
if (threshold
|
|
1645
|
-
|
|
1646
|
-
pipeline.push({ $match: { _score: { $gte: threshold } } });
|
|
1647
|
-
} else if (classicText) pipeline.push({ $addFields: { _score: { $meta: "textScore" } } });
|
|
1803
|
+
if (vector) pipeline.push(...vectorScoreStages(vector.threshold));
|
|
1804
|
+
else if (classicText) pipeline.push({ $addFields: { _score: { $meta: "textScore" } } });
|
|
1648
1805
|
pipeline.push(...filterStages ?? mongoFilterStages(query.filter, filterOptionsOf(host)));
|
|
1649
1806
|
const { stages: sorted, cleanup } = sortStages(controls);
|
|
1650
1807
|
if (sorted.length > 0) pipeline.push(...sorted);
|
|
@@ -1653,10 +1810,7 @@ async function runSearchPipeline(host, stage, query, label, { threshold, classic
|
|
|
1653
1810
|
if (controls.$limit) pipeline.push({ $limit: controls.$limit });
|
|
1654
1811
|
else pipeline.push({ $limit: 1e3 });
|
|
1655
1812
|
if (cleanup) pipeline.push(cleanup);
|
|
1656
|
-
|
|
1657
|
-
const projection = controls.$select.asProjection;
|
|
1658
|
-
if (projection) pipeline.push({ $project: dedupeProjection(projection) });
|
|
1659
|
-
}
|
|
1813
|
+
pushProjection(pipeline, controls, vector ? SCORE_FIELD : void 0);
|
|
1660
1814
|
host._log(`aggregate (${label})`, pipeline);
|
|
1661
1815
|
return wrapInvalidQuery(() => host.collection.aggregate(pipeline, host._getSessionOpts()).toArray());
|
|
1662
1816
|
}
|
|
@@ -1670,22 +1824,17 @@ async function runSearchPipeline(host, stage, query, label, { threshold, classic
|
|
|
1670
1824
|
* `count: total` — the same counts `$$SEARCH_META` reports), concurrently
|
|
1671
1825
|
* outside a transaction.
|
|
1672
1826
|
*/
|
|
1673
|
-
async function runSearchWithCountPipeline(host, stage, query, label, {
|
|
1827
|
+
async function runSearchWithCountPipeline(host, stage, query, label, { vector, classicText = false, defaultSort, filterStages } = {}) {
|
|
1674
1828
|
const controls = query.controls || {};
|
|
1675
1829
|
const preStages = [];
|
|
1676
|
-
if (threshold
|
|
1677
|
-
|
|
1678
|
-
preStages.push({ $match: { _score: { $gte: threshold } } });
|
|
1679
|
-
} else if (classicText) preStages.push({ $addFields: { _score: { $meta: "textScore" } } });
|
|
1830
|
+
if (vector) preStages.push(...vectorScoreStages(vector.threshold));
|
|
1831
|
+
else if (classicText) preStages.push({ $addFields: { _score: { $meta: "textScore" } } });
|
|
1680
1832
|
const { stages: dataStages, cleanup } = sortStages(controls);
|
|
1681
1833
|
if (dataStages.length === 0 && defaultSort) dataStages.push(defaultSort);
|
|
1682
1834
|
if (controls.$skip) dataStages.push({ $skip: controls.$skip });
|
|
1683
1835
|
if (controls.$limit) dataStages.push({ $limit: controls.$limit });
|
|
1684
1836
|
if (cleanup) dataStages.push(cleanup);
|
|
1685
|
-
|
|
1686
|
-
const projection = controls.$select.asProjection;
|
|
1687
|
-
if (projection) dataStages.push({ $project: dedupeProjection(projection) });
|
|
1688
|
-
}
|
|
1837
|
+
pushProjection(dataStages, controls, vector ? SCORE_FIELD : void 0);
|
|
1689
1838
|
const stages = filterStages ?? mongoFilterStages(query.filter, filterOptionsOf(host));
|
|
1690
1839
|
if ("$search" in stage && preStages.length === 0 && stages.every(isNoopMatch)) return runSearchWithMeta(host, stage, dataStages, label);
|
|
1691
1840
|
const pipeline = [
|
|
@@ -2808,7 +2957,52 @@ var MongoAdapter = class MongoAdapter extends BaseDbAdapter {
|
|
|
2808
2957
|
matchedCount: 0,
|
|
2809
2958
|
modifiedCount: 0
|
|
2810
2959
|
};
|
|
2811
|
-
const
|
|
2960
|
+
const { updateFilter, updateOptions } = this._patchPipeline(patch, ops, this._versionColumnFor(opts, expectedVersion));
|
|
2961
|
+
if (updateFilter.length === 0) return this._countUnpatched(mongoFilter, { limit: 1 });
|
|
2962
|
+
this._log("updateOne (patch)", mongoFilter, updateFilter);
|
|
2963
|
+
return this._wrapUpdate(() => this.collection.updateOne(mongoFilter, updateFilter, {
|
|
2964
|
+
...updateOptions,
|
|
2965
|
+
...this._getSessionOpts()
|
|
2966
|
+
}));
|
|
2967
|
+
}
|
|
2968
|
+
/**
|
|
2969
|
+
* `updateMany` with array operators (since 0.1.182): the pipeline
|
|
2970
|
+
* {@link nativePatch} builds, in one `updateMany` over every matching
|
|
2971
|
+
* document — per batch of matching `_id`s for a filter holding relational
|
|
2972
|
+
* predicates. Never CAS-checks; bumps the version unless `opts.keepVersion`.
|
|
2973
|
+
*/
|
|
2974
|
+
async nativePatchMany(filter, patch, ops, opts) {
|
|
2975
|
+
const { updateFilter, updateOptions } = this._patchPipeline(patch, ops, this._versionColumnFor(opts));
|
|
2976
|
+
return this._updateMatching(filter, (mongoFilter) => {
|
|
2977
|
+
if (updateFilter.length === 0) return this._countUnpatched(mongoFilter);
|
|
2978
|
+
this._log("updateMany (patch)", mongoFilter, updateFilter);
|
|
2979
|
+
return this._wrapUpdate(() => this.collection.updateMany(mongoFilter, updateFilter, {
|
|
2980
|
+
...updateOptions,
|
|
2981
|
+
...this._getSessionOpts()
|
|
2982
|
+
}));
|
|
2983
|
+
});
|
|
2984
|
+
}
|
|
2985
|
+
/**
|
|
2986
|
+
* A patch with nothing to set: the driver rejects an empty pipeline, so the
|
|
2987
|
+
* matching documents are only counted.
|
|
2988
|
+
*/
|
|
2989
|
+
async _countUnpatched(mongoFilter, opts) {
|
|
2990
|
+
this._log("countDocuments (empty patch)", mongoFilter);
|
|
2991
|
+
return {
|
|
2992
|
+
matchedCount: await this.collection.countDocuments(mongoFilter, {
|
|
2993
|
+
...opts,
|
|
2994
|
+
...this._getSessionOpts()
|
|
2995
|
+
}),
|
|
2996
|
+
modifiedCount: 0
|
|
2997
|
+
};
|
|
2998
|
+
}
|
|
2999
|
+
/**
|
|
3000
|
+
* The update pipeline of a patch (`CollectionPatcher`), with the version
|
|
3001
|
+
* auto-bump injected into `ops.inc` so the patcher emits it as a
|
|
3002
|
+
* `version = version + 1` aggregation expression alongside any
|
|
3003
|
+
* user-supplied `$inc` / `$mul` ops.
|
|
3004
|
+
*/
|
|
3005
|
+
_patchPipeline(patch, ops, versionColumn) {
|
|
2812
3006
|
const effectiveOps = versionColumn !== void 0 ? {
|
|
2813
3007
|
...ops,
|
|
2814
3008
|
inc: {
|
|
@@ -2816,22 +3010,7 @@ var MongoAdapter = class MongoAdapter extends BaseDbAdapter {
|
|
|
2816
3010
|
[versionColumn]: 1
|
|
2817
3011
|
}
|
|
2818
3012
|
} : ops;
|
|
2819
|
-
|
|
2820
|
-
if (updateFilter.length === 0) {
|
|
2821
|
-
this._log("countDocuments (empty patch)", mongoFilter);
|
|
2822
|
-
return {
|
|
2823
|
-
matchedCount: await this.collection.countDocuments(mongoFilter, {
|
|
2824
|
-
limit: 1,
|
|
2825
|
-
...this._getSessionOpts()
|
|
2826
|
-
}),
|
|
2827
|
-
modifiedCount: 0
|
|
2828
|
-
};
|
|
2829
|
-
}
|
|
2830
|
-
this._log("updateOne (patch)", mongoFilter, updateFilter);
|
|
2831
|
-
return this._wrapUpdate(() => this.collection.updateOne(mongoFilter, updateFilter, {
|
|
2832
|
-
...updateOptions,
|
|
2833
|
-
...this._getSessionOpts()
|
|
2834
|
-
}));
|
|
3013
|
+
return new CollectionPatcher(this.getPatcherContext(), patch, effectiveOps).preparePatch();
|
|
2835
3014
|
}
|
|
2836
3015
|
onBeforeFlatten(_type) {
|
|
2837
3016
|
const typeMeta = _type.metadata;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@atscript/db-mongo",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.183",
|
|
4
4
|
"description": "Mongodb plugin for atscript.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"atscript",
|
|
@@ -46,19 +46,19 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"devDependencies": {
|
|
49
|
-
"@atscript/core": "^0.2.
|
|
50
|
-
"@atscript/typescript": "^0.2.
|
|
49
|
+
"@atscript/core": "^0.2.13",
|
|
50
|
+
"@atscript/typescript": "^0.2.13",
|
|
51
51
|
"@uniqu/core": "^0.2.2",
|
|
52
52
|
"mongodb": "^6.17.0",
|
|
53
53
|
"mongodb-memory-server-core": "^10.0.0",
|
|
54
|
-
"unplugin-atscript": "^0.2.
|
|
54
|
+
"unplugin-atscript": "^0.2.13"
|
|
55
55
|
},
|
|
56
56
|
"peerDependencies": {
|
|
57
|
-
"@atscript/core": "^0.2.
|
|
58
|
-
"@atscript/typescript": "^0.2.
|
|
57
|
+
"@atscript/core": "^0.2.13",
|
|
58
|
+
"@atscript/typescript": "^0.2.13",
|
|
59
59
|
"@uniqu/core": "^0.2.2",
|
|
60
60
|
"mongodb": "^6.17.0",
|
|
61
|
-
"@atscript/db": "^0.1.
|
|
61
|
+
"@atscript/db": "^0.1.183"
|
|
62
62
|
},
|
|
63
63
|
"scripts": {
|
|
64
64
|
"build": "vp pack",
|