UNPKG

mingo

Version:

MongoDB query language for in-memory objects

38 lines (37 loc) 1.13 kB
import { ComputeOptions, computeValue } from "../../core/_internal"; import { assert, groupBy, has } from "../../util"; const ID_KEY = "_id"; const $group = (collection, expr, options) => { assert(has(expr, ID_KEY), "$group specification must include an '_id'"); const idExpr = expr[ID_KEY]; const copts = ComputeOptions.init(options); const newFields = Object.keys(expr).filter((k) => k != ID_KEY); return collection.transform(((coll) => { const partitions = groupBy( coll, (obj) => computeValue(obj, idExpr, null, options) ); let i = -1; const partitionKeys = Array.from(partitions.keys()); return () => { if (++i === partitions.size) return { done: true }; const groupId = partitionKeys[i]; const obj = {}; if (groupId !== void 0) { obj[ID_KEY] = groupId; } for (const key of newFields) { obj[key] = computeValue( partitions.get(groupId), expr[key], null, copts.update({ root: null, groupId }) ); } return { value: obj, done: false }; }; })); }; export { $group };