blackhole.db 2.0.1 → 3.0.0
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/collection.js +299 -0
- package/document.js +476 -0
- package/index.js +191 -210
- package/lib/engine.js +861 -0
- package/lib/errors.js +94 -0
- package/lib/objectid.js +50 -0
- package/lib/schema.js +555 -0
- package/model.js +260 -0
- package/package.json +1 -1
- package/query.js +551 -0
package/lib/engine.js
ADDED
|
@@ -0,0 +1,861 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Query, update, projection, sort and aggregation engine. Works on plain, already
|
|
3
|
+
// hydrated documents (Date, ObjectId, Buffer, Map are real instances).
|
|
4
|
+
const ObjectId = require('./objectid');
|
|
5
|
+
|
|
6
|
+
const isObj = (v) => v !== null && typeof v === 'object' && !Array.isArray(v) && !(v instanceof Date) && !(v instanceof ObjectId) && !(v instanceof RegExp) && !(v instanceof Map) && !Buffer.isBuffer(v);
|
|
7
|
+
const isOpObject = (v) => isObj(v) && Object.keys(v).length > 0 && Object.keys(v).every((k) => k[0] === '$');
|
|
8
|
+
const IDX = /^\d+$/;
|
|
9
|
+
|
|
10
|
+
function clone(v) {
|
|
11
|
+
if (v === null || typeof v !== 'object') return v;
|
|
12
|
+
if (Array.isArray(v)) { const out = new Array(v.length); for (let i = 0; i < v.length; i++) out[i] = clone(v[i]); return out; }
|
|
13
|
+
if (v instanceof Date) return new Date(v.getTime());
|
|
14
|
+
if (v instanceof ObjectId) return v;
|
|
15
|
+
if (v instanceof RegExp) return v;
|
|
16
|
+
if (Buffer.isBuffer(v)) return Buffer.from(v);
|
|
17
|
+
if (v instanceof Map) { const m = new Map(); for (const [k, x] of v) m.set(k, clone(x)); return m; }
|
|
18
|
+
if (typeof v.toObject === 'function' && v.$isblackholeDocument) return v.toObject();
|
|
19
|
+
const out = {};
|
|
20
|
+
for (const k of Object.keys(v)) out[k] = clone(v[k]);
|
|
21
|
+
return out;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// ---------- equality and ordering ----------
|
|
25
|
+
function eq(a, b) {
|
|
26
|
+
if (a === b) return true;
|
|
27
|
+
if (a === undefined || a === null) return (b === undefined || b === null) && (a === b || (a == null && b == null));
|
|
28
|
+
if (b === undefined || b === null) return false;
|
|
29
|
+
if (a instanceof ObjectId || b instanceof ObjectId) return String(a) === String(b) && (typeof a === 'string' || a instanceof ObjectId) && (typeof b === 'string' || b instanceof ObjectId);
|
|
30
|
+
if (a instanceof Date || b instanceof Date) {
|
|
31
|
+
const x = a instanceof Date ? a.getTime() : typeof a === 'string' ? Date.parse(a) : NaN;
|
|
32
|
+
const y = b instanceof Date ? b.getTime() : typeof b === 'string' ? Date.parse(b) : NaN;
|
|
33
|
+
return x === y;
|
|
34
|
+
}
|
|
35
|
+
if (typeof a !== 'object' || typeof b !== 'object') return false;
|
|
36
|
+
if (Array.isArray(a)) {
|
|
37
|
+
if (!Array.isArray(b) || a.length !== b.length) return false;
|
|
38
|
+
for (let i = 0; i < a.length; i++) if (!eq(a[i], b[i])) return false;
|
|
39
|
+
return true;
|
|
40
|
+
}
|
|
41
|
+
if (Array.isArray(b)) return false;
|
|
42
|
+
if (Buffer.isBuffer(a) && Buffer.isBuffer(b)) return a.equals(b);
|
|
43
|
+
if (a instanceof RegExp && b instanceof RegExp) return String(a) === String(b);
|
|
44
|
+
if (a instanceof Map) a = Object.fromEntries(a);
|
|
45
|
+
if (b instanceof Map) b = Object.fromEntries(b);
|
|
46
|
+
const ka = Object.keys(a), kb = Object.keys(b);
|
|
47
|
+
if (ka.length !== kb.length) return false;
|
|
48
|
+
for (const k of ka) if (!(k in b) || !eq(a[k], b[k])) return false;
|
|
49
|
+
return true;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function rank(v) {
|
|
53
|
+
if (v === undefined || v === null) return 1;
|
|
54
|
+
switch (typeof v) {
|
|
55
|
+
case 'number': return 2;
|
|
56
|
+
case 'bigint': return 2;
|
|
57
|
+
case 'string': return 3;
|
|
58
|
+
case 'boolean': return 8;
|
|
59
|
+
default:
|
|
60
|
+
}
|
|
61
|
+
if (Array.isArray(v)) return 5;
|
|
62
|
+
if (Buffer.isBuffer(v)) return 6;
|
|
63
|
+
if (v instanceof ObjectId) return 7;
|
|
64
|
+
if (v instanceof Date) return 9;
|
|
65
|
+
if (v instanceof RegExp) return 11;
|
|
66
|
+
return 4;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Total ordering used by sort, $min/$max and $cmp.
|
|
70
|
+
function compare(a, b) {
|
|
71
|
+
const ra = rank(a), rb = rank(b);
|
|
72
|
+
if (ra !== rb) return ra < rb ? -1 : 1;
|
|
73
|
+
switch (ra) {
|
|
74
|
+
case 1: return 0;
|
|
75
|
+
case 2: return a < b ? -1 : a > b ? 1 : 0;
|
|
76
|
+
case 3: return a < b ? -1 : a > b ? 1 : 0;
|
|
77
|
+
case 7: return a._hex < b._hex ? -1 : a._hex > b._hex ? 1 : 0;
|
|
78
|
+
case 8: return a === b ? 0 : a ? 1 : -1;
|
|
79
|
+
case 9: { const x = a.getTime(), y = b.getTime(); return x < y ? -1 : x > y ? 1 : 0; }
|
|
80
|
+
case 5: {
|
|
81
|
+
for (let i = 0; i < Math.min(a.length, b.length); i++) { const c = compare(a[i], b[i]); if (c) return c; }
|
|
82
|
+
return a.length - b.length < 0 ? -1 : a.length > b.length ? 1 : 0;
|
|
83
|
+
}
|
|
84
|
+
case 6: return Buffer.compare(a, b);
|
|
85
|
+
case 4: {
|
|
86
|
+
const ka = Object.keys(a), kb = Object.keys(b);
|
|
87
|
+
for (let i = 0; i < Math.min(ka.length, kb.length); i++) {
|
|
88
|
+
if (ka[i] !== kb[i]) return ka[i] < kb[i] ? -1 : 1;
|
|
89
|
+
const c = compare(a[ka[i]], b[kb[i]]); if (c) return c;
|
|
90
|
+
}
|
|
91
|
+
return ka.length < kb.length ? -1 : ka.length > kb.length ? 1 : 0;
|
|
92
|
+
}
|
|
93
|
+
default: return 0;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Comparison used by $gt/$lt: values of different types never match (type bracketing).
|
|
98
|
+
function cmpBracket(a, b) {
|
|
99
|
+
if (a instanceof ObjectId && typeof b === 'string') b = new ObjectId(b);
|
|
100
|
+
else if (b instanceof ObjectId && typeof a === 'string') a = new ObjectId(a);
|
|
101
|
+
if (a instanceof Date && typeof b === 'string') b = new Date(b);
|
|
102
|
+
else if (b instanceof Date && typeof a === 'string') a = new Date(a);
|
|
103
|
+
const ra = rank(a), rb = rank(b);
|
|
104
|
+
if (ra !== rb || ra === 1 || ra === 4 || ra === 5) return undefined;
|
|
105
|
+
if (ra === 2 && (Number.isNaN(a) || Number.isNaN(b))) return undefined;
|
|
106
|
+
return compare(a, b);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// ---------- paths ----------
|
|
110
|
+
function resolve(cur, parts, i, out) {
|
|
111
|
+
if (i === parts.length) { if (cur !== undefined) out.push(cur); return; }
|
|
112
|
+
if (cur === null || cur === undefined) return;
|
|
113
|
+
const p = parts[i];
|
|
114
|
+
if (Array.isArray(cur)) {
|
|
115
|
+
if (IDX.test(p)) { resolve(cur[+p], parts, i + 1, out); return; }
|
|
116
|
+
for (const el of cur) if (el !== null && typeof el === 'object') resolve(el, parts, i, out);
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
if (cur instanceof Map) { resolve(cur.get(p), parts, i + 1, out); return; }
|
|
120
|
+
if (typeof cur === 'object') resolve(cur[p], parts, i + 1, out);
|
|
121
|
+
}
|
|
122
|
+
const pathCache = new Map();
|
|
123
|
+
function splitPath(path) {
|
|
124
|
+
let parts = pathCache.get(path);
|
|
125
|
+
if (!parts) { parts = path.split('.'); if (pathCache.size < 5000) pathCache.set(path, parts); }
|
|
126
|
+
return parts;
|
|
127
|
+
}
|
|
128
|
+
function values(doc, path) { const out = []; resolve(doc, splitPath(path), 0, out); return out; }
|
|
129
|
+
|
|
130
|
+
function getPath(doc, path) {
|
|
131
|
+
let cur = doc;
|
|
132
|
+
for (const p of splitPath(path)) {
|
|
133
|
+
if (cur === null || cur === undefined) return undefined;
|
|
134
|
+
cur = cur instanceof Map ? cur.get(p) : cur[p];
|
|
135
|
+
}
|
|
136
|
+
return cur;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function setPath(doc, path, value) {
|
|
140
|
+
const parts = splitPath(path);
|
|
141
|
+
let cur = doc;
|
|
142
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
143
|
+
const p = parts[i];
|
|
144
|
+
let next = cur instanceof Map ? cur.get(p) : cur[p];
|
|
145
|
+
if (next === null || next === undefined || typeof next !== 'object') {
|
|
146
|
+
next = IDX.test(parts[i + 1]) ? [] : {};
|
|
147
|
+
if (cur instanceof Map) cur.set(p, next); else cur[p] = next;
|
|
148
|
+
}
|
|
149
|
+
cur = next;
|
|
150
|
+
}
|
|
151
|
+
const last = parts[parts.length - 1];
|
|
152
|
+
if (cur instanceof Map) cur.set(last, value); else cur[last] = value;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function unsetPath(doc, path) {
|
|
156
|
+
const parts = splitPath(path);
|
|
157
|
+
let cur = doc;
|
|
158
|
+
for (let i = 0; i < parts.length - 1; i++) { cur = cur instanceof Map ? cur.get(parts[i]) : cur?.[parts[i]]; if (cur === null || typeof cur !== 'object') return false; }
|
|
159
|
+
const last = parts[parts.length - 1];
|
|
160
|
+
if (Array.isArray(cur)) { if (IDX.test(last) && +last < cur.length) { cur[+last] = null; return true; } return false; }
|
|
161
|
+
if (cur instanceof Map) return cur.delete(last);
|
|
162
|
+
if (last in cur) { delete cur[last]; return true; }
|
|
163
|
+
return false;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// ---------- filter matching ----------
|
|
167
|
+
function regexOf(pattern, options) {
|
|
168
|
+
if (pattern instanceof RegExp) return options ? new RegExp(pattern.source, options.replace(/[^imsux]/g, '')) : pattern;
|
|
169
|
+
return new RegExp(String(pattern), String(options || '').replace(/[^imsux]/g, ''));
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function anyValue(vals, test) {
|
|
173
|
+
if (vals.length === 0) return test(undefined);
|
|
174
|
+
for (const v of vals) {
|
|
175
|
+
if (test(v)) return true;
|
|
176
|
+
if (Array.isArray(v)) for (const el of v) if (test(el)) return true;
|
|
177
|
+
}
|
|
178
|
+
return false;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function testIn(v, list) {
|
|
182
|
+
return list.some((x) => (x instanceof RegExp ? typeof v === 'string' && x.test(v) : eq(v, x)));
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function testOps(vals, ops, outerDoc) {
|
|
186
|
+
for (const op of Object.keys(ops)) {
|
|
187
|
+
const arg = ops[op];
|
|
188
|
+
switch (op) {
|
|
189
|
+
case '$eq': if (!anyValue(vals, (v) => (arg instanceof RegExp ? typeof v === 'string' && arg.test(v) : eq(v, arg)))) return false; break;
|
|
190
|
+
case '$ne': if (anyValue(vals, (v) => eq(v, arg))) return false; break;
|
|
191
|
+
case '$gt': if (!anyValue(vals, (v) => { const c = cmpBracket(v, arg); return c !== undefined && c > 0; })) return false; break;
|
|
192
|
+
case '$gte': if (!anyValue(vals, (v) => { const c = cmpBracket(v, arg); return c !== undefined && c >= 0; })) return false; break;
|
|
193
|
+
case '$lt': if (!anyValue(vals, (v) => { const c = cmpBracket(v, arg); return c !== undefined && c < 0; })) return false; break;
|
|
194
|
+
case '$lte': if (!anyValue(vals, (v) => { const c = cmpBracket(v, arg); return c !== undefined && c <= 0; })) return false; break;
|
|
195
|
+
case '$in': if (!Array.isArray(arg)) throw new Error('$in needs an array'); if (!anyValue(vals, (v) => testIn(v, arg))) return false; break;
|
|
196
|
+
case '$nin': if (!Array.isArray(arg)) throw new Error('$nin needs an array'); if (anyValue(vals, (v) => testIn(v, arg))) return false; break;
|
|
197
|
+
case '$exists': if ((vals.length > 0) !== !!arg) return false; break;
|
|
198
|
+
case '$regex': { const re = regexOf(arg, ops.$options); if (!anyValue(vals, (v) => typeof v === 'string' && re.test(v))) return false; break; }
|
|
199
|
+
case '$options': break;
|
|
200
|
+
case '$not': {
|
|
201
|
+
const inner = arg instanceof RegExp ? { $regex: arg } : arg;
|
|
202
|
+
if (testOps(vals, inner, outerDoc)) return false; break;
|
|
203
|
+
}
|
|
204
|
+
case '$size': if (!vals.some((v) => Array.isArray(v) && v.length === arg)) return false; break;
|
|
205
|
+
case '$all': {
|
|
206
|
+
if (!Array.isArray(arg)) throw new Error('$all needs an array');
|
|
207
|
+
const ok = arg.every((x) => {
|
|
208
|
+
if (isObj(x) && x.$elemMatch) return vals.some((v) => Array.isArray(v) && v.some((el) => elemMatches(el, x.$elemMatch)));
|
|
209
|
+
return anyValue(vals, (v) => (x instanceof RegExp ? typeof v === 'string' && x.test(v) : eq(v, x)));
|
|
210
|
+
});
|
|
211
|
+
if (!ok || arg.length === 0) return false; break;
|
|
212
|
+
}
|
|
213
|
+
case '$elemMatch': if (!vals.some((v) => Array.isArray(v) && v.some((el) => elemMatches(el, arg)))) return false; break;
|
|
214
|
+
case '$mod': if (!anyValue(vals, (v) => typeof v === 'number' && v % arg[0] === arg[1])) return false; break;
|
|
215
|
+
case '$type': if (!anyValue(vals, (v) => typeMatches(v, arg))) return false; break;
|
|
216
|
+
case '$bitsAllSet': if (!anyValue(vals, (v) => (v & arg) === arg)) return false; break;
|
|
217
|
+
case '$comment': break;
|
|
218
|
+
default: throw new Error(`unknown operator: ${op}`);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
return true;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function elemMatches(el, cond) {
|
|
225
|
+
if (isOpObject(cond)) return testOps([el], cond);
|
|
226
|
+
return el !== null && typeof el === 'object' && matches(el, cond);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const TYPE_NAMES = { double: 1, string: 2, object: 3, array: 4, binData: 5, objectId: 7, bool: 8, date: 9, null: 10, regex: 11, int: 16, long: 18, decimal: 19, number: -1 };
|
|
230
|
+
function typeMatches(v, t) {
|
|
231
|
+
const want = Array.isArray(t) ? t : [t];
|
|
232
|
+
return want.some((x) => {
|
|
233
|
+
const code = typeof x === 'string' ? TYPE_NAMES[x] : x;
|
|
234
|
+
switch (code) {
|
|
235
|
+
case -1: return typeof v === 'number';
|
|
236
|
+
case 1: case 16: case 18: case 19: return typeof v === 'number';
|
|
237
|
+
case 2: return typeof v === 'string';
|
|
238
|
+
case 3: return isObj(v);
|
|
239
|
+
case 4: return Array.isArray(v);
|
|
240
|
+
case 5: return Buffer.isBuffer(v);
|
|
241
|
+
case 7: return v instanceof ObjectId;
|
|
242
|
+
case 8: return typeof v === 'boolean';
|
|
243
|
+
case 9: return v instanceof Date;
|
|
244
|
+
case 10: return v === null;
|
|
245
|
+
case 11: return v instanceof RegExp;
|
|
246
|
+
default: return false;
|
|
247
|
+
}
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function matchField(doc, path, cond) {
|
|
252
|
+
const vals = values(doc, path);
|
|
253
|
+
if (cond instanceof RegExp) return anyValue(vals, (v) => typeof v === 'string' && cond.test(v));
|
|
254
|
+
if (isOpObject(cond)) return testOps(vals, cond, doc);
|
|
255
|
+
return anyValue(vals, (v) => eq(v, cond));
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function matches(doc, filter) {
|
|
259
|
+
for (const key of Object.keys(filter)) {
|
|
260
|
+
const cond = filter[key];
|
|
261
|
+
if (key === '$and') { for (const f of cond) if (!matches(doc, f)) return false; }
|
|
262
|
+
else if (key === '$or') { if (!cond.some((f) => matches(doc, f))) return false; }
|
|
263
|
+
else if (key === '$nor') { if (cond.some((f) => matches(doc, f))) return false; }
|
|
264
|
+
else if (key === '$expr') { if (!truthy(evalExpr(cond, newCtx(doc)))) return false; }
|
|
265
|
+
else if (key === '$where') { if (typeof cond !== 'function' ? !new Function(`return (${cond})`).call(doc) : !cond.call(doc)) return false; }
|
|
266
|
+
else if (key === '$comment') continue;
|
|
267
|
+
else if (key[0] === '$') throw new Error(`unknown top level operator: ${key}`);
|
|
268
|
+
else if (!matchField(doc, key, cond)) return false;
|
|
269
|
+
}
|
|
270
|
+
return true;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// ---------- sort / projection ----------
|
|
274
|
+
function normalizeSort(sort) {
|
|
275
|
+
if (!sort) return [];
|
|
276
|
+
let entries;
|
|
277
|
+
if (typeof sort === 'string') {
|
|
278
|
+
entries = sort.split(/\s+/).filter(Boolean).map((s) => (s[0] === '-' ? [s.slice(1), -1] : [s[0] === '+' ? s.slice(1) : s, 1]));
|
|
279
|
+
} else if (Array.isArray(sort)) {
|
|
280
|
+
entries = sort.map((e) => (Array.isArray(e) ? [e[0], e[1]] : [e, 1]));
|
|
281
|
+
} else if (sort instanceof Map) entries = [...sort.entries()];
|
|
282
|
+
else entries = Object.entries(sort);
|
|
283
|
+
return entries.map(([k, d]) => {
|
|
284
|
+
let dir = d;
|
|
285
|
+
if (typeof d === 'string') dir = /^(desc|descending)$/i.test(d) ? -1 : 1;
|
|
286
|
+
else if (isObj(d)) dir = 1;
|
|
287
|
+
return [k, dir < 0 ? -1 : 1];
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function sortKey(doc, path, dir) {
|
|
292
|
+
const vals = values(doc, path);
|
|
293
|
+
if (vals.length === 0) return undefined;
|
|
294
|
+
let best = vals[0];
|
|
295
|
+
if (Array.isArray(best)) {
|
|
296
|
+
if (best.length === 0) return undefined;
|
|
297
|
+
let b = best[0];
|
|
298
|
+
for (const x of best) if (dir > 0 ? compare(x, b) < 0 : compare(x, b) > 0) b = x;
|
|
299
|
+
return b;
|
|
300
|
+
}
|
|
301
|
+
return best;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function sortDocs(docs, sort) {
|
|
305
|
+
const spec = normalizeSort(sort);
|
|
306
|
+
if (spec.length === 0) return docs;
|
|
307
|
+
if (spec.length === 1 && spec[0][0] === '_id') {
|
|
308
|
+
const dir = spec[0][1];
|
|
309
|
+
return docs.sort((a, b) => dir * compare(a._id, b._id));
|
|
310
|
+
}
|
|
311
|
+
// decorate once so the comparator does not walk paths on every compare
|
|
312
|
+
const rows = docs.map((doc, i) => ({ doc, i, keys: spec.map(([p, d]) => sortKey(doc, p, d)) }));
|
|
313
|
+
rows.sort((x, y) => {
|
|
314
|
+
for (let k = 0; k < spec.length; k++) {
|
|
315
|
+
const c = compare(x.keys[k], y.keys[k]);
|
|
316
|
+
if (c) return c * spec[k][1];
|
|
317
|
+
}
|
|
318
|
+
return x.i - y.i;
|
|
319
|
+
});
|
|
320
|
+
for (let i = 0; i < rows.length; i++) docs[i] = rows[i].doc;
|
|
321
|
+
return docs;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function normalizeProjection(p) {
|
|
325
|
+
if (!p) return null;
|
|
326
|
+
if (typeof p === 'string') {
|
|
327
|
+
const o = {};
|
|
328
|
+
for (const f of p.split(/\s+/).filter(Boolean)) { if (f[0] === '-') o[f.slice(1)] = 0; else if (f[0] === '+') o[f.slice(1)] = 1; else o[f] = 1; }
|
|
329
|
+
return o;
|
|
330
|
+
}
|
|
331
|
+
if (Array.isArray(p)) { const o = {}; for (const f of p) o[f] = 1; return o; }
|
|
332
|
+
return Object.keys(p).length ? p : null;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
function omit(obj, parts, i) {
|
|
336
|
+
if (obj === null || typeof obj !== 'object') return obj;
|
|
337
|
+
if (Array.isArray(obj)) return obj.map((el) => omit(el, parts, i));
|
|
338
|
+
const p = parts[i];
|
|
339
|
+
if (!(p in obj)) return obj;
|
|
340
|
+
const out = { ...obj };
|
|
341
|
+
if (i === parts.length - 1) delete out[p]; else out[p] = omit(obj[p], parts, i + 1);
|
|
342
|
+
return out;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function pickInto(src, parts, i, out) {
|
|
346
|
+
if (src === null || src === undefined) return;
|
|
347
|
+
const p = parts[i];
|
|
348
|
+
if (Array.isArray(src)) { return src.map((el) => { const o = {}; pickInto(el, parts, i, o); return o; }); }
|
|
349
|
+
if (!(p in src)) return;
|
|
350
|
+
if (i === parts.length - 1) { out[p] = src[p]; return; }
|
|
351
|
+
const child = src[p];
|
|
352
|
+
if (Array.isArray(child)) {
|
|
353
|
+
const arr = out[p] && Array.isArray(out[p]) ? out[p] : child.map(() => ({}));
|
|
354
|
+
child.forEach((el, idx) => { if (el !== null && typeof el === 'object') pickInto(el, parts, i + 1, arr[idx]); });
|
|
355
|
+
out[p] = arr;
|
|
356
|
+
} else if (child !== null && typeof child === 'object') {
|
|
357
|
+
if (!isObj(out[p])) out[p] = {};
|
|
358
|
+
pickInto(child, parts, i + 1, out[p]);
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
// Returns a new top-level object; nested values are shared with the source until cloned.
|
|
363
|
+
function project(doc, proj) {
|
|
364
|
+
if (!proj) return doc;
|
|
365
|
+
const entries = Object.entries(proj);
|
|
366
|
+
const special = entries.filter(([, v]) => isObj(v));
|
|
367
|
+
const flags = entries.filter(([k, v]) => !isObj(v) && k !== '_id');
|
|
368
|
+
const includeMode = flags.some(([, v]) => v) || (flags.length === 0 && special.length > 0 && !('_id' in proj && !proj._id && entries.length === 1));
|
|
369
|
+
let out;
|
|
370
|
+
if (includeMode && flags.some(([, v]) => v) || (flags.length === 0 && special.length)) {
|
|
371
|
+
out = {};
|
|
372
|
+
if (proj._id === undefined || proj._id) { if (doc._id !== undefined) out._id = doc._id; }
|
|
373
|
+
for (const [k, v] of flags) if (v) pickInto(doc, splitPath(k), 0, out);
|
|
374
|
+
} else {
|
|
375
|
+
out = doc;
|
|
376
|
+
for (const [k] of flags) out = omit(out, splitPath(k), 0);
|
|
377
|
+
if (proj._id !== undefined && !proj._id) out = omit(out, ['_id'], 0);
|
|
378
|
+
if (out === doc) out = { ...doc };
|
|
379
|
+
}
|
|
380
|
+
for (const [k, v] of special) {
|
|
381
|
+
const cur = getPath(doc, k);
|
|
382
|
+
if (v.$slice !== undefined && Array.isArray(cur)) {
|
|
383
|
+
const s = v.$slice;
|
|
384
|
+
const sliced = Array.isArray(s) ? cur.slice(s[0] < 0 ? Math.max(cur.length + s[0], 0) : s[0], (s[0] < 0 ? Math.max(cur.length + s[0], 0) : s[0]) + s[1]) : s >= 0 ? cur.slice(0, s) : cur.slice(s);
|
|
385
|
+
setPath(out, k, sliced);
|
|
386
|
+
} else if (v.$elemMatch && Array.isArray(cur)) {
|
|
387
|
+
const hit = cur.find((el) => elemMatches(el, v.$elemMatch));
|
|
388
|
+
if (hit !== undefined) setPath(out, k, [hit]); else unsetPath(out, k);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
return out;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// ---------- update operators ----------
|
|
395
|
+
function walk(cur, parts, i, fn, ctx) {
|
|
396
|
+
const p = parts[i], last = i === parts.length - 1;
|
|
397
|
+
if (p === '$[]' || (p[0] === '$' && p[1] === '[' && p[p.length - 1] === ']')) {
|
|
398
|
+
if (!Array.isArray(cur)) return;
|
|
399
|
+
const id = p === '$[]' ? null : p.slice(2, -1);
|
|
400
|
+
for (let idx = 0; idx < cur.length; idx++) {
|
|
401
|
+
if (id !== null && !arrayFilterMatches(cur[idx], id, ctx.arrayFilters)) continue;
|
|
402
|
+
if (last) fn(cur, idx); else walk(cur[idx], parts, i + 1, fn, ctx);
|
|
403
|
+
}
|
|
404
|
+
return;
|
|
405
|
+
}
|
|
406
|
+
if (p === '$') {
|
|
407
|
+
const idx = ctx.positional;
|
|
408
|
+
if (!Array.isArray(cur) || idx === undefined) throw new Error('The positional operator did not find the match needed from the query.');
|
|
409
|
+
if (last) fn(cur, idx); else walk(cur[idx], parts, i + 1, fn, ctx);
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
if (last) { fn(cur, p); return; }
|
|
413
|
+
let next = cur instanceof Map ? cur.get(p) : cur[p];
|
|
414
|
+
if (next === null || next === undefined || typeof next !== 'object') {
|
|
415
|
+
if (ctx.noCreate) return;
|
|
416
|
+
next = (IDX.test(parts[i + 1]) || parts[i + 1] === '$[]') && false ? [] : {};
|
|
417
|
+
if (cur instanceof Map) cur.set(p, next); else cur[p] = next;
|
|
418
|
+
}
|
|
419
|
+
walk(next, parts, i + 1, fn, ctx);
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
function arrayFilterMatches(el, id, filters) {
|
|
423
|
+
if (!filters) throw new Error(`No array filter found for identifier '${id}' in path`);
|
|
424
|
+
let found = false;
|
|
425
|
+
for (const f of filters) {
|
|
426
|
+
const keys = Object.keys(f).filter((k) => k === id || k.startsWith(`${id}.`));
|
|
427
|
+
if (!keys.length) continue;
|
|
428
|
+
found = true;
|
|
429
|
+
for (const k of keys) {
|
|
430
|
+
const rest = k === id ? 'v' : `v${k.slice(id.length)}`;
|
|
431
|
+
if (!matchField({ v: el }, rest, f[k])) return false;
|
|
432
|
+
}
|
|
433
|
+
return true;
|
|
434
|
+
}
|
|
435
|
+
if (!found) throw new Error(`No array filter found for identifier '${id}' in path`);
|
|
436
|
+
return false;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function positionalIndex(doc, filter) {
|
|
440
|
+
if (!filter) return undefined;
|
|
441
|
+
for (const key of Object.keys(filter)) {
|
|
442
|
+
if (key[0] === '$') continue;
|
|
443
|
+
const parts = splitPath(key);
|
|
444
|
+
let cur = doc;
|
|
445
|
+
for (let i = 0; i < parts.length; i++) {
|
|
446
|
+
cur = cur?.[parts[i]];
|
|
447
|
+
if (Array.isArray(cur)) {
|
|
448
|
+
const rest = parts.slice(i + 1).join('.');
|
|
449
|
+
const idx = cur.findIndex((el) => (rest ? matchField(el, rest, filter[key]) : matchField({ v: el }, 'v', filter[key])));
|
|
450
|
+
if (idx >= 0) return idx;
|
|
451
|
+
break;
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
return undefined;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
function num(v, op, path) {
|
|
459
|
+
if (typeof v !== 'number') throw new Error(`Cannot apply ${op} to a value of non-numeric type. {_id: ...} has the field '${path}' of non-numeric type ${v === null ? 'null' : typeof v}`);
|
|
460
|
+
return v;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
function applyUpdate(doc, update, opts = {}) {
|
|
464
|
+
const ctx = { arrayFilters: opts.arrayFilters, positional: undefined };
|
|
465
|
+
if (Object.keys(update).some((k) => /\.\$(\.|$)/.test(Object.keys(update[k] || {}).join(' ')) )) ctx.positional = positionalIndex(doc, opts.filter);
|
|
466
|
+
let changed = false;
|
|
467
|
+
const each = (spec, fn) => {
|
|
468
|
+
for (const path of Object.keys(spec)) {
|
|
469
|
+
if (path === '_id' && doc._id !== undefined) { /* _id is immutable */ }
|
|
470
|
+
walk(doc, splitPath(path), 0, (parent, key) => { if (fn(parent, key, spec[path], path)) changed = true; }, ctx);
|
|
471
|
+
}
|
|
472
|
+
};
|
|
473
|
+
const get = (p, k) => (p instanceof Map ? p.get(k) : p[k]);
|
|
474
|
+
const set = (p, k, v) => { if (p instanceof Map) p.set(k, v); else p[k] = v; };
|
|
475
|
+
for (const op of Object.keys(update)) {
|
|
476
|
+
const spec = update[op];
|
|
477
|
+
switch (op) {
|
|
478
|
+
case '$set': each(spec, (p, k, v) => { const old = get(p, k); if (eq(old, v) && old !== undefined) return false; set(p, k, v); return true; }); break;
|
|
479
|
+
case '$setOnInsert': if (opts.inserting) each(spec, (p, k, v) => { set(p, k, v); return true; }); break;
|
|
480
|
+
case '$unset': for (const path of Object.keys(spec)) { if (unsetPath(doc, path)) changed = true; } break;
|
|
481
|
+
case '$inc': each(spec, (p, k, v, path) => { const old = get(p, k); set(p, k, (old === undefined || old === null ? 0 : num(old, '$inc', path)) + num(v, '$inc', path)); return v !== 0; }); break;
|
|
482
|
+
case '$mul': each(spec, (p, k, v, path) => { const old = get(p, k); set(p, k, (old === undefined ? 0 : num(old, '$mul', path)) * num(v, '$mul', path)); return true; }); break;
|
|
483
|
+
case '$min': each(spec, (p, k, v) => { const old = get(p, k); if (old === undefined || compare(v, old) < 0) { set(p, k, v); return true; } return false; }); break;
|
|
484
|
+
case '$max': each(spec, (p, k, v) => { const old = get(p, k); if (old === undefined || compare(v, old) > 0) { set(p, k, v); return true; } return false; }); break;
|
|
485
|
+
case '$currentDate': each(spec, (p, k) => { set(p, k, new Date()); return true; }); break;
|
|
486
|
+
case '$rename':
|
|
487
|
+
for (const from of Object.keys(spec)) {
|
|
488
|
+
const v = getPath(doc, from);
|
|
489
|
+
if (v === undefined) continue;
|
|
490
|
+
unsetPath(doc, from); setPath(doc, spec[from], v); changed = true;
|
|
491
|
+
}
|
|
492
|
+
break;
|
|
493
|
+
case '$push': each(spec, (p, k, v, path) => {
|
|
494
|
+
let arr = get(p, k);
|
|
495
|
+
if (arr === undefined || arr === null) { arr = []; set(p, k, arr); }
|
|
496
|
+
if (!Array.isArray(arr)) throw new Error(`The field '${path}' must be an array but is of type ${typeof arr}`);
|
|
497
|
+
if (isObj(v) && '$each' in v) {
|
|
498
|
+
const items = v.$each;
|
|
499
|
+
if (v.$position !== undefined) arr.splice(v.$position < 0 ? Math.max(arr.length + v.$position, 0) : v.$position, 0, ...items); else arr.push(...items);
|
|
500
|
+
if (v.$sort !== undefined) {
|
|
501
|
+
if (isObj(v.$sort)) sortDocs(arr, v.$sort); else arr.sort((a, b) => v.$sort * compare(a, b));
|
|
502
|
+
}
|
|
503
|
+
if (v.$slice !== undefined) { const s = v.$slice; const kept = s >= 0 ? arr.slice(0, s) : arr.slice(s); arr.length = 0; arr.push(...kept); }
|
|
504
|
+
} else arr.push(v);
|
|
505
|
+
return true;
|
|
506
|
+
}); break;
|
|
507
|
+
case '$addToSet': each(spec, (p, k, v, path) => {
|
|
508
|
+
let arr = get(p, k);
|
|
509
|
+
if (arr === undefined || arr === null) { arr = []; set(p, k, arr); }
|
|
510
|
+
if (!Array.isArray(arr)) throw new Error(`Cannot apply $addToSet to non-array field. Field named '${path}' has non-array type ${typeof arr}`);
|
|
511
|
+
let did = false;
|
|
512
|
+
for (const item of isObj(v) && '$each' in v ? v.$each : [v]) if (!arr.some((x) => eq(x, item))) { arr.push(item); did = true; }
|
|
513
|
+
return did;
|
|
514
|
+
}); break;
|
|
515
|
+
case '$pull': each(spec, (p, k, v) => {
|
|
516
|
+
const arr = get(p, k);
|
|
517
|
+
if (!Array.isArray(arr)) return false;
|
|
518
|
+
const before = arr.length;
|
|
519
|
+
const keep = arr.filter((el) => !(isOpObject(v) ? testOps([el], v) : isObj(v) && isObj(el) ? matches(el, v) : eq(el, v)));
|
|
520
|
+
if (keep.length === before) return false;
|
|
521
|
+
arr.length = 0; arr.push(...keep); return true;
|
|
522
|
+
}); break;
|
|
523
|
+
case '$pullAll': each(spec, (p, k, v) => {
|
|
524
|
+
const arr = get(p, k);
|
|
525
|
+
if (!Array.isArray(arr)) return false;
|
|
526
|
+
const keep = arr.filter((el) => !v.some((x) => eq(el, x)));
|
|
527
|
+
if (keep.length === arr.length) return false;
|
|
528
|
+
arr.length = 0; arr.push(...keep); return true;
|
|
529
|
+
}); break;
|
|
530
|
+
case '$pop': each(spec, (p, k, v) => { const arr = get(p, k); if (!Array.isArray(arr) || !arr.length) return false; if (v < 0) arr.shift(); else arr.pop(); return true; }); break;
|
|
531
|
+
case '$bit': break;
|
|
532
|
+
default: throw new Error(`Unknown modifier: ${op}. Expected a valid update modifier or pipeline-style update specified as an array`);
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
return changed;
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
// Build the starting document for an upsert from the equality parts of the filter.
|
|
539
|
+
function seedFromFilter(filter) {
|
|
540
|
+
const out = {};
|
|
541
|
+
for (const key of Object.keys(filter || {})) {
|
|
542
|
+
const cond = filter[key];
|
|
543
|
+
if (key === '$and') { for (const f of cond) Object.assign(out, seedFromFilter(f)); continue; }
|
|
544
|
+
if (key[0] === '$') continue;
|
|
545
|
+
if (cond instanceof RegExp) continue;
|
|
546
|
+
if (isOpObject(cond)) { if ('$eq' in cond) setPath(out, key, cond.$eq); continue; }
|
|
547
|
+
setPath(out, key, clone(cond));
|
|
548
|
+
}
|
|
549
|
+
return out;
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
// ---------- aggregation expressions ----------
|
|
553
|
+
const truthy = (v) => !(v === false || v === null || v === undefined || v === 0 || Number.isNaN(v));
|
|
554
|
+
function newCtx(root, vars = {}) { return { root, cur: root, vars }; }
|
|
555
|
+
|
|
556
|
+
function fieldPath(ctx, s) {
|
|
557
|
+
if (s[1] === '$') {
|
|
558
|
+
const [name, ...rest] = s.slice(2).split('.');
|
|
559
|
+
let base;
|
|
560
|
+
if (name === 'ROOT') base = ctx.root; else if (name === 'CURRENT') base = ctx.cur; else if (name === 'NOW') base = new Date(); else base = ctx.vars[name];
|
|
561
|
+
return rest.length ? getPathArr(base, rest) : base;
|
|
562
|
+
}
|
|
563
|
+
return getPathArr(ctx.cur, s.slice(1).split('.'));
|
|
564
|
+
}
|
|
565
|
+
// $field paths traverse arrays and collect (aggregation semantics)
|
|
566
|
+
function getPathArr(base, parts) {
|
|
567
|
+
let cur = base;
|
|
568
|
+
for (let i = 0; i < parts.length; i++) {
|
|
569
|
+
if (cur === null || cur === undefined) return undefined;
|
|
570
|
+
if (Array.isArray(cur)) { const rest = parts.slice(i); const out = []; for (const el of cur) { const v = getPathArr(el, rest); if (v !== undefined) out.push(v); } return out; }
|
|
571
|
+
cur = cur instanceof Map ? cur.get(parts[i]) : cur[parts[i]];
|
|
572
|
+
}
|
|
573
|
+
return cur;
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
const toNum = (v) => (v === null || v === undefined ? null : Number(v));
|
|
577
|
+
const arithmetic = (fn) => (args, ctx) => { const v = args.map((a) => evalExpr(a, ctx)); return v.some((x) => x === null || x === undefined) ? null : fn(...v.map((x) => (x instanceof Date ? x.getTime() : x))); };
|
|
578
|
+
const cmp = (fn) => (args, ctx) => fn(compare(evalExpr(args[0], ctx), evalExpr(args[1], ctx)));
|
|
579
|
+
const str = (v) => (v === null || v === undefined ? '' : v instanceof Date ? v.toISOString() : String(v));
|
|
580
|
+
const dateOf = (v) => (v instanceof Date ? v : new Date(v));
|
|
581
|
+
const pad = (n, l = 2) => String(n).padStart(l, '0');
|
|
582
|
+
function fmtDate(d, fmt) {
|
|
583
|
+
return fmt.replace(/%([YmdHMSLjUwzZ%])/g, (_, c) => ({ Y: d.getUTCFullYear(), m: pad(d.getUTCMonth() + 1), d: pad(d.getUTCDate()), H: pad(d.getUTCHours()), M: pad(d.getUTCMinutes()), S: pad(d.getUTCSeconds()), L: pad(d.getUTCMilliseconds(), 3), j: pad(Math.floor((d - Date.UTC(d.getUTCFullYear(), 0, 0)) / 864e5), 3), w: d.getUTCDay() + 1, z: '+0000', Z: '0', U: pad(Math.floor((d - Date.UTC(d.getUTCFullYear(), 0, 1)) / 6048e5)), '%': '%' }[c]));
|
|
584
|
+
}
|
|
585
|
+
const arr = (v) => (Array.isArray(v) ? v : v === null || v === undefined ? null : [v]);
|
|
586
|
+
|
|
587
|
+
const OPS = {
|
|
588
|
+
$literal: (a) => a,
|
|
589
|
+
$add: (args, ctx) => { let total = 0, date = null; for (const a of args) { const v = evalExpr(a, ctx); if (v === null || v === undefined) return null; if (v instanceof Date) date = v; else total += v; } return date ? new Date(date.getTime() + total) : total; },
|
|
590
|
+
$subtract: (args, ctx) => { const [a, b] = args.map((x) => evalExpr(x, ctx)); if (a == null || b == null) return null; if (a instanceof Date && b instanceof Date) return a - b; if (a instanceof Date) return new Date(a.getTime() - b); return a - b; },
|
|
591
|
+
$multiply: arithmetic((...v) => v.reduce((x, y) => x * y, 1)),
|
|
592
|
+
$divide: arithmetic((a, b) => { if (b === 0) throw new Error("can't $divide by zero"); return a / b; }),
|
|
593
|
+
$mod: arithmetic((a, b) => a % b),
|
|
594
|
+
$abs: arithmetic(Math.abs), $ceil: arithmetic(Math.ceil), $floor: arithmetic(Math.floor), $sqrt: arithmetic(Math.sqrt), $exp: arithmetic(Math.exp), $ln: arithmetic(Math.log), $log10: arithmetic(Math.log10), $trunc: arithmetic(Math.trunc),
|
|
595
|
+
$pow: arithmetic(Math.pow),
|
|
596
|
+
$round: (args, ctx) => { const [v, p = 0] = args.map((x) => evalExpr(x, ctx)); if (v == null) return null; const f = 10 ** p; const r = Math.round(Math.abs(v) * f) / f; return v < 0 ? -r : r; },
|
|
597
|
+
$eq: cmp((c) => c === 0), $ne: cmp((c) => c !== 0), $gt: cmp((c) => c > 0), $gte: cmp((c) => c >= 0), $lt: cmp((c) => c < 0), $lte: cmp((c) => c <= 0), $cmp: cmp((c) => c),
|
|
598
|
+
$and: (args, ctx) => args.every((a) => truthy(evalExpr(a, ctx))),
|
|
599
|
+
$or: (args, ctx) => args.some((a) => truthy(evalExpr(a, ctx))),
|
|
600
|
+
$not: (args, ctx) => !truthy(evalExpr(Array.isArray(args) ? args[0] : args, ctx)),
|
|
601
|
+
$cond: (args, ctx) => {
|
|
602
|
+
const [c, t, f] = Array.isArray(args) ? args : [args.if, args.then, args.else];
|
|
603
|
+
return truthy(evalExpr(c, ctx)) ? evalExpr(t, ctx) : evalExpr(f, ctx);
|
|
604
|
+
},
|
|
605
|
+
$ifNull: (args, ctx) => { for (let i = 0; i < args.length - 1; i++) { const v = evalExpr(args[i], ctx); if (v !== null && v !== undefined) return v; } return evalExpr(args[args.length - 1], ctx); },
|
|
606
|
+
$switch: (args, ctx) => {
|
|
607
|
+
for (const b of args.branches) if (truthy(evalExpr(b.case, ctx))) return evalExpr(b.then, ctx);
|
|
608
|
+
if ('default' in args) return evalExpr(args.default, ctx);
|
|
609
|
+
throw new Error('$switch could not find a matching branch for an input, and no default was specified.');
|
|
610
|
+
},
|
|
611
|
+
$concat: (args, ctx) => { const v = args.map((a) => evalExpr(a, ctx)); return v.some((x) => x == null) ? null : v.join(''); },
|
|
612
|
+
$toLower: (a, ctx) => str(evalExpr(Array.isArray(a) ? a[0] : a, ctx)).toLowerCase(),
|
|
613
|
+
$toUpper: (a, ctx) => str(evalExpr(Array.isArray(a) ? a[0] : a, ctx)).toUpperCase(),
|
|
614
|
+
$substr: (args, ctx) => { const [s, st, n] = args.map((x) => evalExpr(x, ctx)); return str(s).substr(st, n < 0 ? undefined : n); },
|
|
615
|
+
$substrCP: (args, ctx) => { const [s, st, n] = args.map((x) => evalExpr(x, ctx)); return [...str(s)].slice(st, st + n).join(''); },
|
|
616
|
+
$strLenCP: (a, ctx) => [...str(evalExpr(Array.isArray(a) ? a[0] : a, ctx))].length,
|
|
617
|
+
$strLenBytes: (a, ctx) => Buffer.byteLength(str(evalExpr(Array.isArray(a) ? a[0] : a, ctx))),
|
|
618
|
+
$split: (args, ctx) => { const [s, d] = args.map((x) => evalExpr(x, ctx)); return s == null ? null : s.split(d); },
|
|
619
|
+
$trim: (a, ctx) => { const s = str(evalExpr(a.input, ctx)); return a.chars ? s.replace(new RegExp(`^[${evalExpr(a.chars, ctx)}]+|[${evalExpr(a.chars, ctx)}]+$`, 'g'), '') : s.trim(); },
|
|
620
|
+
$ltrim: (a, ctx) => str(evalExpr(a.input, ctx)).replace(/^\s+/, ''),
|
|
621
|
+
$rtrim: (a, ctx) => str(evalExpr(a.input, ctx)).replace(/\s+$/, ''),
|
|
622
|
+
$replaceAll: (a, ctx) => str(evalExpr(a.input, ctx)).split(evalExpr(a.find, ctx)).join(evalExpr(a.replacement, ctx)),
|
|
623
|
+
$replaceOne: (a, ctx) => str(evalExpr(a.input, ctx)).replace(evalExpr(a.find, ctx), () => evalExpr(a.replacement, ctx)),
|
|
624
|
+
$indexOfCP: (args, ctx) => { const [s, sub] = args.map((x) => evalExpr(x, ctx)); return s == null ? null : s.indexOf(sub); },
|
|
625
|
+
$regexMatch: (a, ctx) => regexOf(evalExpr(a.regex, ctx), a.options).test(str(evalExpr(a.input, ctx))),
|
|
626
|
+
$size: (a, ctx) => { const v = evalExpr(Array.isArray(a) ? a[0] : a, ctx); if (!Array.isArray(v)) throw new Error('The argument to $size must be an array'); return v.length; },
|
|
627
|
+
$isArray: (a, ctx) => Array.isArray(evalExpr(Array.isArray(a) && a.length === 1 ? a[0] : a, ctx)),
|
|
628
|
+
$arrayElemAt: (args, ctx) => { const [a, i] = args.map((x) => evalExpr(x, ctx)); if (a == null) return null; return a[i < 0 ? a.length + i : i]; },
|
|
629
|
+
$first: (a, ctx) => { const v = evalExpr(Array.isArray(a) ? a[0] : a, ctx); return Array.isArray(v) ? (v.length ? v[0] : undefined) : v; },
|
|
630
|
+
$last: (a, ctx) => { const v = evalExpr(Array.isArray(a) ? a[0] : a, ctx); return Array.isArray(v) ? (v.length ? v[v.length - 1] : undefined) : v; },
|
|
631
|
+
$concatArrays: (args, ctx) => { const v = args.map((x) => evalExpr(x, ctx)); return v.some((x) => x == null) ? null : [].concat(...v); },
|
|
632
|
+
$slice: (args, ctx) => { const [a, x, y] = args.map((e) => evalExpr(e, ctx)); if (a == null) return null; if (y === undefined) return x >= 0 ? a.slice(0, x) : a.slice(x); const st = x < 0 ? Math.max(a.length + x, 0) : x; return a.slice(st, st + y); },
|
|
633
|
+
$reverseArray: (a, ctx) => { const v = evalExpr(Array.isArray(a) ? a[0] : a, ctx); return v == null ? null : [...v].reverse(); },
|
|
634
|
+
$range: (args, ctx) => { const [s, e, st = 1] = args.map((x) => evalExpr(x, ctx)); const out = []; for (let i = s; st > 0 ? i < e : i > e; i += st) out.push(i); return out; },
|
|
635
|
+
$in: (args, ctx) => { const [v, a] = args.map((x) => evalExpr(x, ctx)); if (!Array.isArray(a)) throw new Error('$in requires an array as a second argument'); return a.some((x) => eq(x, v)); },
|
|
636
|
+
$indexOfArray: (args, ctx) => { const [a, v] = args.map((x) => evalExpr(x, ctx)); return a == null ? null : a.findIndex((x) => eq(x, v)); },
|
|
637
|
+
$setUnion: (args, ctx) => { const out = []; for (const a of args) for (const x of evalExpr(a, ctx) || []) if (!out.some((y) => eq(x, y))) out.push(x); return out; },
|
|
638
|
+
$setIntersection: (args, ctx) => { const [first, ...rest] = args.map((x) => evalExpr(x, ctx)); return first.filter((x, i) => first.findIndex((y) => eq(x, y)) === i && rest.every((r) => r.some((y) => eq(x, y)))); },
|
|
639
|
+
$setDifference: (args, ctx) => { const [a, b] = args.map((x) => evalExpr(x, ctx)); return a.filter((x) => !b.some((y) => eq(x, y))); },
|
|
640
|
+
$setEquals: (args, ctx) => { const [a, b] = args.map((x) => evalExpr(x, ctx)); return a.every((x) => b.some((y) => eq(x, y))) && b.every((x) => a.some((y) => eq(x, y))); },
|
|
641
|
+
$setIsSubset: (args, ctx) => { const [a, b] = args.map((x) => evalExpr(x, ctx)); return a.every((x) => b.some((y) => eq(x, y))); },
|
|
642
|
+
$filter: (a, ctx) => {
|
|
643
|
+
const input = evalExpr(a.input, ctx); if (input == null) return null;
|
|
644
|
+
const as = a.as || 'this';
|
|
645
|
+
const out = input.filter((el) => truthy(evalExpr(a.cond, { ...ctx, vars: { ...ctx.vars, [as]: el } })));
|
|
646
|
+
return a.limit !== undefined ? out.slice(0, a.limit) : out;
|
|
647
|
+
},
|
|
648
|
+
$map: (a, ctx) => { const input = evalExpr(a.input, ctx); if (input == null) return null; const as = a.as || 'this'; return input.map((el) => evalExpr(a.in, { ...ctx, vars: { ...ctx.vars, [as]: el } })); },
|
|
649
|
+
$reduce: (a, ctx) => { const input = evalExpr(a.input, ctx); if (input == null) return null; let acc = evalExpr(a.initialValue, ctx); for (const el of input) acc = evalExpr(a.in, { ...ctx, vars: { ...ctx.vars, value: acc, this: el } }); return acc; },
|
|
650
|
+
$let: (a, ctx) => { const vars = { ...ctx.vars }; for (const k of Object.keys(a.vars)) vars[k] = evalExpr(a.vars[k], ctx); return evalExpr(a.in, { ...ctx, vars }); },
|
|
651
|
+
$sum: (a, ctx) => { const v = evalExpr(Array.isArray(a) && a.length === 1 ? a[0] : a, ctx); return Array.isArray(v) ? v.reduce((s, x) => (typeof x === 'number' ? s + x : s), 0) : typeof v === 'number' ? v : 0; },
|
|
652
|
+
$avg: (a, ctx) => { const v = evalExpr(Array.isArray(a) && a.length === 1 ? a[0] : a, ctx); const n = (Array.isArray(v) ? v : [v]).filter((x) => typeof x === 'number'); return n.length ? n.reduce((s, x) => s + x, 0) / n.length : null; },
|
|
653
|
+
$min: (a, ctx) => { const v = evalExpr(Array.isArray(a) && a.length === 1 ? a[0] : a, ctx); const l = (Array.isArray(v) ? v : [v]).filter((x) => x != null); return l.length ? l.reduce((m, x) => (compare(x, m) < 0 ? x : m)) : null; },
|
|
654
|
+
$max: (a, ctx) => { const v = evalExpr(Array.isArray(a) && a.length === 1 ? a[0] : a, ctx); const l = (Array.isArray(v) ? v : [v]).filter((x) => x != null); return l.length ? l.reduce((m, x) => (compare(x, m) > 0 ? x : m)) : null; },
|
|
655
|
+
$mergeObjects: (a, ctx) => Object.assign({}, ...(Array.isArray(a) ? a : [a]).map((x) => evalExpr(x, ctx) || {})),
|
|
656
|
+
$objectToArray: (a, ctx) => Object.entries(evalExpr(a, ctx) || {}).map(([k, v]) => ({ k, v })),
|
|
657
|
+
$arrayToObject: (a, ctx) => Object.fromEntries((evalExpr(a, ctx) || []).map((e) => (Array.isArray(e) ? e : [e.k, e.v]))),
|
|
658
|
+
$getField: (a, ctx) => { const f = typeof a === 'string' ? a : a.field; const input = typeof a === 'string' ? ctx.cur : evalExpr(a.input ?? '$$CURRENT', ctx); return input?.[f]; },
|
|
659
|
+
$type: (a, ctx) => { const v = evalExpr(a, ctx); return v === undefined ? 'missing' : v === null ? 'null' : Array.isArray(v) ? 'array' : typeof v === 'number' ? (Number.isInteger(v) ? 'int' : 'double') : typeof v === 'string' ? 'string' : typeof v === 'boolean' ? 'bool' : v instanceof Date ? 'date' : v instanceof ObjectId ? 'objectId' : 'object'; },
|
|
660
|
+
$toString: (a, ctx) => { const v = evalExpr(a, ctx); return v == null ? null : str(v); },
|
|
661
|
+
$toInt: (a, ctx) => { const v = evalExpr(a, ctx); return v == null ? null : Math.trunc(Number(v)); },
|
|
662
|
+
$toLong: (a, ctx) => { const v = evalExpr(a, ctx); return v == null ? null : Math.trunc(Number(v)); },
|
|
663
|
+
$toDouble: (a, ctx) => { const v = evalExpr(a, ctx); return v == null ? null : Number(v); },
|
|
664
|
+
$toDecimal: (a, ctx) => { const v = evalExpr(a, ctx); return v == null ? null : Number(v); },
|
|
665
|
+
$toBool: (a, ctx) => { const v = evalExpr(a, ctx); return v == null ? null : truthy(v); },
|
|
666
|
+
$toDate: (a, ctx) => { const v = evalExpr(a, ctx); return v == null ? null : new Date(v); },
|
|
667
|
+
$toObjectId: (a, ctx) => { const v = evalExpr(a, ctx); return v == null ? null : new ObjectId(v); },
|
|
668
|
+
$convert: (a, ctx) => { const v = evalExpr(a.input, ctx); if (v == null) return 'onNull' in a ? evalExpr(a.onNull, ctx) : null; try { return OPS[{ int: '$toInt', long: '$toLong', double: '$toDouble', string: '$toString', bool: '$toBool', date: '$toDate', objectId: '$toObjectId' }[a.to]]({ $literal: v }, ctx); } catch (e) { if ('onError' in a) return evalExpr(a.onError, ctx); throw e; } },
|
|
669
|
+
$year: (a, ctx) => dateOf(evalExpr(Array.isArray(a) ? a[0] : a.date ?? a, ctx)).getUTCFullYear(),
|
|
670
|
+
$month: (a, ctx) => dateOf(evalExpr(Array.isArray(a) ? a[0] : a.date ?? a, ctx)).getUTCMonth() + 1,
|
|
671
|
+
$dayOfMonth: (a, ctx) => dateOf(evalExpr(Array.isArray(a) ? a[0] : a.date ?? a, ctx)).getUTCDate(),
|
|
672
|
+
$dayOfWeek: (a, ctx) => dateOf(evalExpr(Array.isArray(a) ? a[0] : a.date ?? a, ctx)).getUTCDay() + 1,
|
|
673
|
+
$dayOfYear: (a, ctx) => { const d = dateOf(evalExpr(Array.isArray(a) ? a[0] : a.date ?? a, ctx)); return Math.floor((d - Date.UTC(d.getUTCFullYear(), 0, 0)) / 864e5); },
|
|
674
|
+
$hour: (a, ctx) => dateOf(evalExpr(Array.isArray(a) ? a[0] : a.date ?? a, ctx)).getUTCHours(),
|
|
675
|
+
$minute: (a, ctx) => dateOf(evalExpr(Array.isArray(a) ? a[0] : a.date ?? a, ctx)).getUTCMinutes(),
|
|
676
|
+
$second: (a, ctx) => dateOf(evalExpr(Array.isArray(a) ? a[0] : a.date ?? a, ctx)).getUTCSeconds(),
|
|
677
|
+
$millisecond: (a, ctx) => dateOf(evalExpr(Array.isArray(a) ? a[0] : a.date ?? a, ctx)).getUTCMilliseconds(),
|
|
678
|
+
$dateToString: (a, ctx) => { const d = evalExpr(a.date, ctx); return d == null ? (a.onNull !== undefined ? evalExpr(a.onNull, ctx) : null) : fmtDate(dateOf(d), a.format || '%Y-%m-%dT%H:%M:%S.%LZ'); },
|
|
679
|
+
$dateFromString: (a, ctx) => new Date(evalExpr(a.dateString, ctx)),
|
|
680
|
+
$dateAdd: (a, ctx) => { const d = dateOf(evalExpr(a.startDate, ctx)); const n = evalExpr(a.amount, ctx); const ms = { millisecond: 1, second: 1e3, minute: 6e4, hour: 36e5, day: 864e5, week: 6048e5 }[a.unit]; if (ms) return new Date(d.getTime() + n * ms); const r = new Date(d); if (a.unit === 'month') r.setUTCMonth(r.getUTCMonth() + n); else if (a.unit === 'year') r.setUTCFullYear(r.getUTCFullYear() + n); return r; },
|
|
681
|
+
$rand: () => Math.random(),
|
|
682
|
+
$sortArray: (a, ctx) => { const input = [...evalExpr(a.input, ctx)]; return isObj(a.sortBy) ? sortDocs(input, a.sortBy) : input.sort((x, y) => a.sortBy * compare(x, y)); },
|
|
683
|
+
$zip: (a, ctx) => { const ins = a.inputs.map((x) => evalExpr(x, ctx)); const n = Math.max(...ins.map((x) => x.length)); return Array.from({ length: n }, (_, i) => ins.map((x) => (x[i] === undefined ? null : x[i]))); },
|
|
684
|
+
};
|
|
685
|
+
|
|
686
|
+
function evalExpr(expr, ctx) {
|
|
687
|
+
if (typeof expr === 'string') return expr[0] === '$' ? fieldPath(ctx, expr) : expr;
|
|
688
|
+
if (expr === null || typeof expr !== 'object') return expr;
|
|
689
|
+
if (Array.isArray(expr)) return expr.map((e) => evalExpr(e, ctx));
|
|
690
|
+
if (expr instanceof Date || expr instanceof ObjectId || expr instanceof RegExp || Buffer.isBuffer(expr)) return expr;
|
|
691
|
+
const keys = Object.keys(expr);
|
|
692
|
+
if (keys.length === 1 && keys[0][0] === '$') {
|
|
693
|
+
const fn = OPS[keys[0]];
|
|
694
|
+
if (!fn) throw new Error(`Unrecognized expression '${keys[0]}'`);
|
|
695
|
+
return fn(expr[keys[0]], ctx);
|
|
696
|
+
}
|
|
697
|
+
const out = {};
|
|
698
|
+
for (const k of keys) { const v = evalExpr(expr[k], ctx); if (v !== undefined) out[k] = v; }
|
|
699
|
+
return out;
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
// ---------- aggregation stages ----------
|
|
703
|
+
const ACCUMULATORS = {
|
|
704
|
+
$sum: { init: () => 0, add: (s, v) => (typeof v === 'number' ? s + v : s) },
|
|
705
|
+
$avg: { init: () => ({ n: 0, t: 0 }), add: (s, v) => { if (typeof v === 'number') { s.n++; s.t += v; } return s; }, done: (s) => (s.n ? s.t / s.n : null) },
|
|
706
|
+
$min: { init: () => undefined, add: (s, v) => (v == null ? s : s === undefined || compare(v, s) < 0 ? v : s), done: (s) => (s === undefined ? null : s) },
|
|
707
|
+
$max: { init: () => undefined, add: (s, v) => (v == null ? s : s === undefined || compare(v, s) > 0 ? v : s), done: (s) => (s === undefined ? null : s) },
|
|
708
|
+
$push: { init: () => [], add: (s, v) => { if (v !== undefined) s.push(v); return s; } },
|
|
709
|
+
$addToSet: { init: () => [], add: (s, v) => { if (v !== undefined && !s.some((x) => eq(x, v))) s.push(v); return s; } },
|
|
710
|
+
$first: { init: () => ({ set: false }), add: (s, v) => (s.set ? s : { set: true, v }), done: (s) => (s.set && s.v !== undefined ? s.v : null) },
|
|
711
|
+
$last: { init: () => ({ v: null }), add: (s, v) => ({ v }), done: (s) => (s.v === undefined ? null : s.v) },
|
|
712
|
+
$count: { init: () => 0, add: (s) => s + 1 },
|
|
713
|
+
$mergeObjects: { init: () => ({}), add: (s, v) => Object.assign(s, v || {}) },
|
|
714
|
+
$stdDevPop: { init: () => [], add: (s, v) => { if (typeof v === 'number') s.push(v); return s; }, done: (s) => { if (!s.length) return null; const m = s.reduce((a, b) => a + b, 0) / s.length; return Math.sqrt(s.reduce((a, b) => a + (b - m) ** 2, 0) / s.length); } },
|
|
715
|
+
$stdDevSamp: { init: () => [], add: (s, v) => { if (typeof v === 'number') s.push(v); return s; }, done: (s) => { if (s.length < 2) return null; const m = s.reduce((a, b) => a + b, 0) / s.length; return Math.sqrt(s.reduce((a, b) => a + (b - m) ** 2, 0) / (s.length - 1)); } },
|
|
716
|
+
};
|
|
717
|
+
|
|
718
|
+
function groupKey(v) { return JSON.stringify(v, (k, x) => (x instanceof Date ? { $d: x.getTime() } : x)); }
|
|
719
|
+
|
|
720
|
+
function aggregate(docs, pipeline, env = {}) {
|
|
721
|
+
let out = docs;
|
|
722
|
+
for (const stage of pipeline) {
|
|
723
|
+
const name = Object.keys(stage)[0];
|
|
724
|
+
const arg = stage[name];
|
|
725
|
+
out = runStage(name, arg, out, env);
|
|
726
|
+
}
|
|
727
|
+
return out;
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
function runStage(name, arg, docs, env) {
|
|
731
|
+
const vars = env.vars || {};
|
|
732
|
+
switch (name) {
|
|
733
|
+
case '$match': return docs.filter((d) => matches(d, arg));
|
|
734
|
+
case '$sort': return sortDocs([...docs], arg);
|
|
735
|
+
case '$limit': return docs.slice(0, arg);
|
|
736
|
+
case '$skip': return docs.slice(arg);
|
|
737
|
+
case '$count': return [{ [arg]: docs.length }];
|
|
738
|
+
case '$sample': { const copy = [...docs]; for (let i = copy.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [copy[i], copy[j]] = [copy[j], copy[i]]; } return copy.slice(0, arg.size); }
|
|
739
|
+
case '$addFields': case '$set':
|
|
740
|
+
return docs.map((d) => { const o = { ...d }; const ctx = newCtx(d, vars); for (const k of Object.keys(arg)) { const v = evalExpr(arg[k], ctx); if (k.includes('.')) { cowSet(o, k, v); } else if (v === undefined) delete o[k]; else o[k] = v; } return o; });
|
|
741
|
+
case '$unset': { const paths = Array.isArray(arg) ? arg : [arg]; return docs.map((d) => paths.reduce((o, p) => omit(o, splitPath(p), 0), d)); }
|
|
742
|
+
case '$project': return projectStage(docs, arg, vars);
|
|
743
|
+
case '$replaceRoot': case '$replaceWith': return docs.map((d) => evalExpr(name === '$replaceRoot' ? arg.newRoot : arg, newCtx(d, vars)));
|
|
744
|
+
case '$unwind': return unwind(docs, arg);
|
|
745
|
+
case '$group': return group(docs, arg, vars);
|
|
746
|
+
case '$sortByCount': { const g = group(docs, { _id: arg, count: { $sum: 1 } }, vars); return sortDocs(g, { count: -1 }); }
|
|
747
|
+
case '$facet': { const o = {}; for (const k of Object.keys(arg)) o[k] = aggregate(docs, arg[k], env); return [o]; }
|
|
748
|
+
case '$lookup': return lookup(docs, arg, env);
|
|
749
|
+
case '$unionWith': { const other = env.collection ? env.collection(typeof arg === 'string' ? arg : arg.coll) : []; const more = typeof arg === 'object' && arg.pipeline ? aggregate(other, arg.pipeline, env) : other; return docs.concat(more); }
|
|
750
|
+
case '$bucket': {
|
|
751
|
+
const buckets = arg.boundaries.slice(0, -1).map((lo, i) => ({ lo, hi: arg.boundaries[i + 1], docs: [] })); const other = [];
|
|
752
|
+
for (const d of docs) { const v = evalExpr(arg.groupBy, newCtx(d, vars)); const b = buckets.find((x) => compare(v, x.lo) >= 0 && compare(v, x.hi) < 0); (b ? b.docs : other).push(d); }
|
|
753
|
+
const outB = buckets.filter((b) => b.docs.length || !arg.output).map((b) => ({ _id: b.lo, ...finishGroup(b.docs, arg.output || { count: { $sum: 1 } }, vars) }));
|
|
754
|
+
if (other.length && 'default' in arg) outB.push({ _id: arg.default, ...finishGroup(other, arg.output || { count: { $sum: 1 } }, vars) });
|
|
755
|
+
return outB;
|
|
756
|
+
}
|
|
757
|
+
case '$redact': return docs.filter((d) => { const r = evalExpr(arg, newCtx(d, { ...vars, DESCEND: 'descend', PRUNE: 'prune', KEEP: 'keep' })); return r !== 'prune' && r !== '$$PRUNE'; });
|
|
758
|
+
case '$out': case '$merge': throw new Error(`${name} is not supported by blackhole.db. Write the results with Model.insertMany instead.`);
|
|
759
|
+
default: throw new Error(`Unrecognized pipeline stage name: '${name}'`);
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
function cowSet(o, path, v) {
|
|
764
|
+
const parts = splitPath(path);
|
|
765
|
+
let cur = o;
|
|
766
|
+
for (let i = 0; i < parts.length - 1; i++) { cur[parts[i]] = isObj(cur[parts[i]]) ? { ...cur[parts[i]] } : {}; cur = cur[parts[i]]; }
|
|
767
|
+
cur[parts[parts.length - 1]] = v;
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
function projectStage(docs, spec, vars) {
|
|
771
|
+
const entries = Object.entries(spec);
|
|
772
|
+
const computed = entries.filter(([k, v]) => !(v === 0 || v === 1 || v === true || v === false));
|
|
773
|
+
const flags = entries.filter(([k, v]) => v === 0 || v === 1 || v === true || v === false);
|
|
774
|
+
const exclusion = flags.length > 0 && flags.every(([k, v]) => !v) && computed.length === 0;
|
|
775
|
+
if (exclusion) return docs.map((d) => flags.reduce((o, [k]) => omit(o, splitPath(k), 0), d));
|
|
776
|
+
return docs.map((d) => {
|
|
777
|
+
const out = {};
|
|
778
|
+
if (!(spec._id === 0 || spec._id === false) && d._id !== undefined) out._id = d._id;
|
|
779
|
+
const ctx = newCtx(d, vars);
|
|
780
|
+
for (const [k, v] of entries) {
|
|
781
|
+
if (k === '_id') { if (!(v === 0 || v === 1 || v === true || v === false)) out._id = evalExpr(v, ctx); continue; }
|
|
782
|
+
if (v === 1 || v === true) pickInto(d, splitPath(k), 0, out);
|
|
783
|
+
else if (v === 0 || v === false) continue;
|
|
784
|
+
else { const val = evalExpr(v, ctx); if (val !== undefined) cowSet(out, k, val); }
|
|
785
|
+
}
|
|
786
|
+
return out;
|
|
787
|
+
});
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
function unwind(docs, arg) {
|
|
791
|
+
const spec = typeof arg === 'string' ? { path: arg } : arg;
|
|
792
|
+
const path = spec.path.slice(1);
|
|
793
|
+
const out = [];
|
|
794
|
+
for (const d of docs) {
|
|
795
|
+
const v = getPath(d, path);
|
|
796
|
+
if (Array.isArray(v) && v.length) {
|
|
797
|
+
v.forEach((el, i) => { const o = { ...d }; cowSet(o, path, el); if (spec.includeArrayIndex) o[spec.includeArrayIndex] = i; out.push(o); });
|
|
798
|
+
} else if (v !== undefined && v !== null && !Array.isArray(v)) {
|
|
799
|
+
const o = { ...d }; if (spec.includeArrayIndex) o[spec.includeArrayIndex] = null; out.push(o);
|
|
800
|
+
} else if (spec.preserveNullAndEmptyArrays) {
|
|
801
|
+
const o = { ...d }; if (Array.isArray(v)) unsetPath(o, path); if (spec.includeArrayIndex) o[spec.includeArrayIndex] = null; out.push(o);
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
return out;
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
function finishGroup(rows, spec, vars) {
|
|
808
|
+
const accs = Object.keys(spec).filter((k) => k !== '_id');
|
|
809
|
+
const out = {};
|
|
810
|
+
for (const k of accs) {
|
|
811
|
+
const op = Object.keys(spec[k])[0];
|
|
812
|
+
const impl = ACCUMULATORS[op];
|
|
813
|
+
if (!impl) throw new Error(`unknown group operator '${op}'`);
|
|
814
|
+
let state = impl.init();
|
|
815
|
+
for (const d of rows) state = impl.add(state, op === '$count' ? 1 : evalExpr(spec[k][op], newCtx(d, vars)));
|
|
816
|
+
out[k] = impl.done ? impl.done(state) : state;
|
|
817
|
+
}
|
|
818
|
+
return out;
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
function group(docs, spec, vars) {
|
|
822
|
+
const groups = new Map();
|
|
823
|
+
for (const d of docs) {
|
|
824
|
+
const id = evalExpr(spec._id, newCtx(d, vars));
|
|
825
|
+
const key = groupKey(id === undefined ? null : id);
|
|
826
|
+
let g = groups.get(key);
|
|
827
|
+
if (!g) { g = { id: id === undefined ? null : id, rows: [] }; groups.set(key, g); }
|
|
828
|
+
g.rows.push(d);
|
|
829
|
+
}
|
|
830
|
+
const out = [];
|
|
831
|
+
for (const g of groups.values()) out.push({ _id: g.id, ...finishGroup(g.rows, spec, vars) });
|
|
832
|
+
return out;
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
function lookup(docs, spec, env) {
|
|
836
|
+
const foreign = env.collection ? env.collection(spec.from) : [];
|
|
837
|
+
if (spec.pipeline) {
|
|
838
|
+
return docs.map((d) => {
|
|
839
|
+
const v = {}; for (const k of Object.keys(spec.let || {})) v[k] = evalExpr(spec.let[k], newCtx(d, env.vars));
|
|
840
|
+
return { ...d, [spec.as]: aggregate(foreign, spec.pipeline, { ...env, vars: { ...env.vars, ...v } }) };
|
|
841
|
+
});
|
|
842
|
+
}
|
|
843
|
+
// hash join on the foreign field
|
|
844
|
+
const index = new Map();
|
|
845
|
+
for (const f of foreign) {
|
|
846
|
+
const ks = values(f, spec.foreignField);
|
|
847
|
+
const flat = []; for (const k of ks) { if (Array.isArray(k)) flat.push(...k); else flat.push(k); }
|
|
848
|
+
if (!flat.length) flat.push(null);
|
|
849
|
+
for (const k of flat) { const key = groupKey(k instanceof ObjectId ? k._hex : k); let l = index.get(key); if (!l) index.set(key, l = []); l.push(f); }
|
|
850
|
+
}
|
|
851
|
+
return docs.map((d) => {
|
|
852
|
+
const ks = values(d, spec.localField);
|
|
853
|
+
const flat = []; for (const k of ks) { if (Array.isArray(k)) flat.push(...k); else flat.push(k); }
|
|
854
|
+
if (!flat.length) flat.push(null);
|
|
855
|
+
const found = []; const seen = new Set();
|
|
856
|
+
for (const k of flat) for (const f of index.get(groupKey(k instanceof ObjectId ? k._hex : k)) || []) if (!seen.has(f)) { seen.add(f); found.push(f); }
|
|
857
|
+
return { ...d, [spec.as]: found };
|
|
858
|
+
});
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
module.exports = { isObj, isOpObject, clone, eq, compare, values, getPath, setPath, unsetPath, matches, matchField, normalizeSort, sortDocs, normalizeProjection, project, applyUpdate, seedFromFilter, evalExpr, aggregate, truthy, splitPath, regexOf, positionalIndex };
|