mingo
Version:
MongoDB query language for in-memory objects
82 lines (81 loc) • 2.45 kB
JavaScript
import { computeValue } from "../../core";
import { Lazy } from "../../lazy";
import {
assert,
compare,
findInsertIndex,
getType,
into,
isNil
} from "../../util";
const $bucket = (collection, expr, options) => {
const boundaries = [...expr.boundaries];
const defaultKey = expr.default;
const lower = boundaries[0];
const upper = boundaries[boundaries.length - 1];
const outputExpr = expr.output || { count: { $sum: 1 } };
assert(
expr.boundaries.length > 2,
"$bucket 'boundaries' expression must have at least 3 elements"
);
const boundType = getType(lower);
for (let i = 0, len = boundaries.length - 1; i < len; i++) {
assert(
boundType === getType(boundaries[i + 1]),
"$bucket 'boundaries' must all be of the same type"
);
assert(
compare(boundaries[i], boundaries[i + 1]) < 0,
"$bucket 'boundaries' must be sorted in ascending order"
);
}
!isNil(defaultKey) && getType(expr.default) === getType(lower) && assert(
compare(expr.default, upper) >= 0 || compare(expr.default, lower) < 0,
"$bucket 'default' expression must be out of boundaries range"
);
const grouped = {};
for (const k of boundaries) {
grouped[k] = [];
}
if (!isNil(defaultKey))
grouped[defaultKey] = [];
let iterator;
return Lazy(() => {
if (!iterator) {
collection.each((obj) => {
const key = computeValue(obj, expr.groupBy, null, options);
if (isNil(key) || compare(key, lower) < 0 || compare(key, upper) >= 0) {
assert(
!isNil(defaultKey),
"$bucket require a default for out of range values"
);
grouped[defaultKey].push(obj);
} else {
assert(
compare(key, lower) >= 0 && compare(key, upper) < 0,
"$bucket 'groupBy' expression must resolve to a value in range of boundaries"
);
const index = findInsertIndex(boundaries, key);
const boundKey = boundaries[Math.max(0, index - 1)];
grouped[boundKey].push(obj);
}
});
boundaries.pop();
if (!isNil(defaultKey))
boundaries.push(defaultKey);
iterator = Lazy(boundaries).map((key) => {
const acc = computeValue(
grouped[key],
outputExpr,
null,
options
);
return into(acc, { _id: key });
});
}
return iterator.next();
});
};
export {
$bucket
};