GroupDocumentSource.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. "use strict";
  2. var DocumentSource = require("./DocumentSource"),
  3. Accumulators = require("../accumulators/"),
  4. Document = require("../Document"),
  5. Expression = require("../expressions/Expression"),
  6. ConstantExpression = require("../expressions/ConstantExpression"),
  7. FieldPathExpression = require("../expressions/FieldPathExpression");
  8. var GroupDocumentSource = module.exports = (function(){
  9. // CONSTRUCTOR
  10. /**
  11. * A class for grouping documents together
  12. *
  13. * @class GroupDocumentSource
  14. * @namespace mungedb-aggregate.pipeline.documentSources
  15. * @module mungedb-aggregate
  16. * @constructor
  17. * @param [ctx] {ExpressionContext}
  18. **/
  19. var klass = module.exports = GroupDocumentSource = function GroupDocumentSource(expCtx) {
  20. if(arguments.length > 1) throw new Error("up to one arg expected");
  21. base.call(this, expCtx);
  22. this.populated = false;
  23. this.idExpression = null;
  24. this.groups = {}; // GroupsType Value -> Accumulators[]
  25. this.groupsKeys = []; // This is to faciliate easier look up of groups
  26. this.fieldNames = [];
  27. this.accumulatorFactories = [];
  28. this.expressions = [];
  29. this.currentDocument = null;
  30. this.currentGroupsKeysIndex = 0;
  31. }, base = DocumentSource, proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  32. klass.groupOps = {
  33. "$addToSet": Accumulators.AddToSet,
  34. "$avg": Accumulators.Avg,
  35. "$first": Accumulators.First,
  36. "$last": Accumulators.Last,
  37. "$max": Accumulators.MinMax.createMax,
  38. "$min": Accumulators.MinMax.createMin,
  39. "$push": Accumulators.Push,
  40. "$sum": Accumulators.Sum
  41. };
  42. klass.groupName = "$group";
  43. proto.getSourceName = function getSourceName() {
  44. return klass.groupName;
  45. };
  46. /**
  47. * Create an object that represents the document source. The object
  48. * will have a single field whose name is the source's name. This
  49. * will be used by the default implementation of addToJsonArray()
  50. * to add this object to a pipeline being represented in JSON.
  51. *
  52. * @method sourceToJson
  53. * @param {Object} builder JSONObjBuilder: a blank object builder to write to
  54. * @param {Boolean} explain create explain output
  55. **/
  56. proto.sourceToJson = function sourceToJson(builder, explain) {
  57. var idExp = this.idExpression,
  58. insides = {
  59. _id: idExp ? idExp.toJSON() : {}
  60. },
  61. aFac = this.accumulatorFactories,
  62. aFacLen = aFac.length;
  63. for(var i=0; i < aFacLen; ++i) {
  64. var acc = new aFac[i](/*pExpCtx*/);
  65. acc.addOperand(this.expressions[i]);
  66. insides[this.fieldNames[i]] = acc.toJSON(true);
  67. }
  68. builder[this.getSourceName()] = insides;
  69. };
  70. klass.createFromJson = function createFromJson(groupObj, ctx) {
  71. if (!(groupObj instanceof Object && groupObj.constructor === Object)) throw new Error("a group's fields must be specified in an object");
  72. var idSet = false,
  73. group = new GroupDocumentSource(ctx);
  74. for (var groupFieldName in groupObj) {
  75. if (groupObj.hasOwnProperty(groupFieldName)) {
  76. var groupField = groupObj[groupFieldName];
  77. if (groupFieldName === "_id") {
  78. if(idSet) throw new Error("15948 a group's _id may only be specified once");
  79. if (groupField instanceof Object && groupField.constructor === Object) {
  80. var objCtx = new Expression.ObjectCtx({isDocumentOk:true});
  81. group.idExpression = Expression.parseObject(groupField, objCtx);
  82. idSet = true;
  83. } else if (typeof groupField === "string") {
  84. if (groupField[0] !== "$") {
  85. group.idExpression = new ConstantExpression(groupField);
  86. } else {
  87. var pathString = Expression.removeFieldPrefix(groupField);
  88. group.idExpression = new FieldPathExpression(pathString);
  89. }
  90. idSet = true;
  91. } else {
  92. var typeStr = group._getTypeStr(groupField);
  93. switch (typeStr) {
  94. case "number":
  95. case "string":
  96. case "boolean":
  97. case "Object":
  98. case "object": // null returns "object" Xp
  99. case "Array":
  100. group.idExpression = new ConstantExpression(groupField);
  101. idSet = true;
  102. break;
  103. default:
  104. throw new Error("a group's _id may not include fields of type " + typeStr + "");
  105. }
  106. }
  107. } else {
  108. if (groupFieldName.indexOf(".") !== -1) throw new Error("16414 the group aggregate field name '" + groupFieldName + "' cannot contain '.'");
  109. if (groupFieldName[0] === "$") throw new Error("15950 the group aggregate field name '" + groupFieldName + "' cannot be an operator name");
  110. if (group._getTypeStr(groupFieldName) === "Object") throw new Error("15951 the group aggregate field '" + groupFieldName + "' must be defined as an expression inside an object");
  111. var subFieldCount = 0;
  112. for (var subFieldName in groupField) {
  113. if (groupField.hasOwnProperty(subFieldName)) {
  114. var subField = groupField[subFieldName],
  115. op = klass.groupOps[subFieldName];
  116. if (!op) throw new Error("15952 unknown group operator '" + subFieldName + "'");
  117. var groupExpression,
  118. subFieldTypeStr = group._getTypeStr(subField);
  119. if (subFieldTypeStr === "Object") {
  120. var subFieldObjCtx = new Expression.ObjectCtx({isDocumentOk:true});
  121. groupExpression = Expression.parseObject(subField, subFieldObjCtx);
  122. } else if (subFieldTypeStr === "Array") {
  123. throw new Error("15953 aggregating group operators are unary (" + subFieldName + ")");
  124. } else {
  125. groupExpression = Expression.parseOperand(subField);
  126. }
  127. group.addAccumulator(groupFieldName,op, groupExpression);
  128. ++subFieldCount;
  129. }
  130. }
  131. if (subFieldCount != 1) throw new Error("15954 the computed aggregate '" + groupFieldName + "' must specify exactly one operator");
  132. }
  133. }
  134. }
  135. if (!idSet) throw new Error("15955 a group specification must include an _id");
  136. return group;
  137. };
  138. proto._getTypeStr = function _getTypeStr(obj) {
  139. var typeofStr = typeof obj,
  140. typeStr = (typeofStr == "object" && obj !== null) ? obj.constructor.name : typeofStr;
  141. return typeStr;
  142. };
  143. proto.advance = function advance() {
  144. base.prototype.advance.call(this); // Check for interupts ????
  145. if(!this.populated) this.populate();
  146. //verify(this.currentGroupsKeysIndex < this.groupsKeys.length);
  147. ++this.currentGroupsKeysIndex;
  148. if (this.currentGroupsKeysIndex === this.groupsKeys.length) {
  149. this.currentDocument = null;
  150. return false;
  151. }
  152. this.currentDocument = this.makeDocument(this.currentGroupsKeysIndex);
  153. return true;
  154. };
  155. proto.eof = function eof() {
  156. if (!this.populated) this.populate();
  157. return this.currentGroupsKeysIndex === this.groupsKeys.length;
  158. };
  159. proto.getCurrent = function getCurrent() {
  160. if (!this.populated) this.populate();
  161. return this.currentDocument;
  162. };
  163. proto.getDependencies = function getDependencies(deps) {
  164. var self = this;
  165. // add _id
  166. this.idExpression.addDependencies(deps);
  167. // add the rest
  168. this.fieldNames.forEach(function (field, i) {
  169. self.expressions[i].addDependencies(deps);
  170. });
  171. return DocumentSource.GetDepsReturn.EXHAUSTIVE;
  172. };
  173. proto.addAccumulator = function addAccumulator(fieldName, accumulatorFactory, expression) {
  174. this.fieldNames.push(fieldName);
  175. this.accumulatorFactories.push(accumulatorFactory);
  176. this.expressions.push(expression);
  177. };
  178. proto.populate = function populate() {
  179. for (var hasNext = !this.source.eof(); hasNext; hasNext = this.source.advance()) {
  180. var group,
  181. currentDocument = this.source.getCurrent(),
  182. _id = this.idExpression.evaluate(currentDocument);
  183. if (undefined === _id) _id = null;
  184. var idHash = JSON.stringify(_id); //TODO: USE A REAL HASH. I didn't have time to take collision into account.
  185. if (idHash in this.groups) {
  186. group = this.groups[idHash];
  187. } else {
  188. this.groups[idHash] = group = [];
  189. this.groupsKeys[this.currentGroupsKeysIndex] = idHash;
  190. ++this.currentGroupsKeysIndex;
  191. for (var ai = 0; ai < this.accumulatorFactories.length; ++ai) {
  192. var accumulator = new this.accumulatorFactories[ai]();
  193. accumulator.addOperand(this.expressions[ai]);
  194. group.push(accumulator);
  195. }
  196. }
  197. // tickle all the accumulators for the group we found
  198. for (var gi = 0; gi < group.length; ++gi) {
  199. group[gi].evaluate(currentDocument);
  200. }
  201. }
  202. this.currentGroupsKeysIndex = 0; // Start the group
  203. if (this.groupsKeys.length > 0) {
  204. this.currentDocument = this.makeDocument(this.currentGroupsKeysIndex);
  205. }
  206. this.populated = true;
  207. };
  208. proto.makeDocument = function makeDocument(groupKeyIndex) {
  209. var groupKey = this.groupsKeys[groupKeyIndex],
  210. group = this.groups[groupKey],
  211. doc = {};
  212. doc[Document.ID_PROPERTY_NAME] = JSON.parse(groupKey);
  213. for (var i = 0; i < this.fieldNames.length; ++i) {
  214. var fieldName = this.fieldNames[i],
  215. item = group[i];
  216. if (item !== "null" && item !== undefined) {
  217. doc[fieldName] = item.getValue();
  218. }
  219. }
  220. return doc;
  221. };
  222. return klass;
  223. })();