Pipeline.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. "use strict";
  2. /**
  3. * mongodb "commands" (sent via db.$cmd.findOne(...)) subclass to make a command. define a singleton object for it.
  4. * @class Pipeline
  5. * @namespace mungedb-aggregate.pipeline
  6. * @module mungedb-aggregate
  7. * @constructor
  8. **/
  9. // CONSTRUCTOR
  10. var Pipeline = module.exports = function Pipeline(theCtx){
  11. this.sources = null;
  12. this.explain = false;
  13. this.splitMongodPipeline = false;
  14. this.ctx = theCtx;
  15. this.SYNC_MODE = false;
  16. }, klass = Pipeline, base = Object, proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  17. var DepsTracker = require("./DepsTracker");
  18. var DocumentSource = require("./documentSources/DocumentSource"),
  19. LimitDocumentSource = require('./documentSources/LimitDocumentSource'),
  20. MatchDocumentSource = require('./documentSources/MatchDocumentSource'),
  21. ProjectDocumentSource = require('./documentSources/ProjectDocumentSource'),
  22. SkipDocumentSource = require('./documentSources/SkipDocumentSource'),
  23. UnwindDocumentSource = require('./documentSources/UnwindDocumentSource'),
  24. GroupDocumentSource = require('./documentSources/GroupDocumentSource'),
  25. OutDocumentSource = require('./documentSources/OutDocumentSource'),
  26. GeoNearDocumentSource = require('./documentSources/GeoNearDocumentSource'),
  27. RedactDocumentSource = require('./documentSources/RedactDocumentSource'),
  28. SortDocumentSource = require('./documentSources/SortDocumentSource'),
  29. DepsTracker = require('./DepsTracker');
  30. klass.COMMAND_NAME = "aggregate";
  31. klass.PIPELINE_NAME = "pipeline";
  32. klass.EXPLAIN_NAME = "explain";
  33. klass.FROM_ROUTER_NAME = "fromRouter";
  34. klass.SERVER_PIPELINE_NAME = "serverPipeline";
  35. klass.MONGOS_PIPELINE_NAME = "mongosPipeline";
  36. klass.stageDesc = {};//attaching this to the class for test cases
  37. klass.stageDesc[GeoNearDocumentSource.geoNearName] = GeoNearDocumentSource.createFromJson;
  38. klass.stageDesc[GroupDocumentSource.groupName] = GroupDocumentSource.createFromJson;
  39. klass.stageDesc[LimitDocumentSource.limitName] = LimitDocumentSource.createFromJson;
  40. klass.stageDesc[MatchDocumentSource.matchName] = MatchDocumentSource.createFromJson;
  41. klass.stageDesc[OutDocumentSource.outName] = OutDocumentSource.createFromJson;
  42. klass.stageDesc[ProjectDocumentSource.projectName] = ProjectDocumentSource.createFromJson;
  43. klass.stageDesc[RedactDocumentSource.redactName] = ProjectDocumentSource.createFromJson;
  44. klass.stageDesc[SkipDocumentSource.skipName] = SkipDocumentSource.createFromJson;
  45. klass.stageDesc[SortDocumentSource.sortName] = SortDocumentSource.createFromJson;
  46. klass.stageDesc[UnwindDocumentSource.unwindName] = UnwindDocumentSource.createFromJson;
  47. klass.nStageDesc = Object.keys(klass.stageDesc).length;
  48. klass.optimizations = {};
  49. klass.optimizations.local = {};
  50. klass.optimizations.sharded = {};
  51. /**
  52. * Moves $match before $sort when they are placed next to one another
  53. * @static
  54. * @method moveMatchBeforeSort
  55. * @param pipelineInst An instance of a Pipeline
  56. */
  57. klass.optimizations.local.moveMatchBeforeSort = function moveMatchBeforeSort(pipelineInst) {
  58. var sources = pipelineInst.sources;
  59. for(var srcn = sources.length, srci = 1; srci < srcn; ++srci) {
  60. var source = sources[srci];
  61. if(source.constructor === MatchDocumentSource) {
  62. var previous = sources[srci - 1];
  63. if(previous && previous.constructor === SortDocumentSource) { //Added check that previous exists
  64. /* swap this item with the previous */
  65. sources[srci] = previous;
  66. sources[srci-1] = source;
  67. }
  68. }
  69. }
  70. };
  71. /**
  72. * Moves $limit before $skip when they are placed next to one another
  73. * @static
  74. * @method moveLimitBeforeSkip
  75. * @param pipelineInst An instance of a Pipeline
  76. */
  77. klass.optimizations.local.moveLimitBeforeSkip = function moveLimitBeforeSkip(pipelineInst) {
  78. var sources = pipelineInst.sources;
  79. if(sources.length === 0) return;
  80. for(var i = sources.length - 1; i >= 1 /* not looking at 0 */; i--) {
  81. var limit = sources[i].constructor === LimitDocumentSource ? sources[i] : undefined,
  82. skip = sources[i-1].constructor === SkipDocumentSource ? sources[i-1] : undefined;
  83. if(limit && skip) {
  84. limit.setLimit(limit.getLimit() + skip.getSkip());
  85. sources[i-1] = limit;
  86. sources[i] = skip;
  87. // Start at back again. This is needed to handle cases with more than 1 $limit
  88. // (S means skip, L means limit)
  89. //
  90. // These two would work without second pass (assuming back to front ordering)
  91. // SL -> LS
  92. // SSL -> LSS
  93. //
  94. // The following cases need a second pass to handle the second limit
  95. // SLL -> LLS
  96. // SSLL -> LLSS
  97. // SLSL -> LLSS
  98. i = sources.length; // decremented before next pass
  99. }
  100. }
  101. };
  102. /**
  103. * Attempts to coalesce every pipeline stage into the previous pipeline stage, starting after the first
  104. * @static
  105. * @method coalesceAdjacent
  106. * @param pipelineInst An instance of a Pipeline
  107. */
  108. klass.optimizations.local.coalesceAdjacent = function coalesceAdjacent(pipelineInst) {
  109. var sources = pipelineInst.sources;
  110. if(sources.length === 0) return;
  111. // move all sources to a temporary list
  112. var moveSrc = sources.pop(),
  113. tempSources = [];
  114. while(moveSrc) {
  115. tempSources.unshift(moveSrc);
  116. moveSrc = sources.pop();
  117. }
  118. // move the first one to the final list
  119. sources.push(tempSources[0]);
  120. // run through the sources, coalescing them or keeping them
  121. for(var tempn = tempSources.length, tempi = 1; tempi < tempn; ++tempi) {
  122. // If we can't coalesce the source with the last, then move it
  123. // to the final list, and make it the new last. (If we succeeded,
  124. // then we're still on the same last, and there's no need to move
  125. // or do anything with the source -- the destruction of tempSources
  126. // will take care of the rest.)
  127. var lastSource = sources[sources.length-1],
  128. tempSrc = tempSources[tempi];
  129. if(!(lastSource && tempSrc)) {
  130. throw new Error('Must have a last and current source'); // verify(lastSource && tempSrc);
  131. }
  132. if(!lastSource.coalesce(tempSrc)) sources.push(tempSrc);
  133. }
  134. };
  135. /**
  136. * Iterates over sources in the pipelineInst, optimizing each
  137. * @static
  138. * @method optimizeEachDocumentSource
  139. * @param pipelineInst An instance of a Pipeline
  140. */
  141. klass.optimizations.local.optimizeEachDocumentSource = function optimizeEachDocumentSource(pipelineInst) {
  142. var sources = pipelineInst.sources;
  143. for(var srci = 0, srcn = sources.length; srci < srcn; ++srci) {
  144. sources[srci].optimize();
  145. }
  146. };
  147. /**
  148. * Auto-places a $match before a $redact when the $redact is the first item in a pipeline
  149. * @static
  150. * @method duplicateMatchBeforeInitalRedact
  151. * @param pipelineInst An instance of a Pipeline
  152. */
  153. klass.optimizations.local.duplicateMatchBeforeInitalRedact = function duplicateMatchBeforeInitalRedact(pipelineInst) {
  154. var sources = pipelineInst.sources;
  155. if(sources.length >= 2 && sources[0].constructor === RedactDocumentSource) {
  156. if(sources[1].constructor === MatchDocumentSource) {
  157. var match = sources[1],
  158. redactSafePortion = match.redactSafePortion();
  159. if(Object.keys(redactSafePortion).length > 0) {
  160. sources.shift(MatchDocumentSource.createFromJson(redactSafePortion, pipelineInst.ctx));
  161. }
  162. }
  163. }
  164. };
  165. //SKIPPED: addRequiredPrivileges
  166. /**
  167. * Perform optimizations for a pipeline through sharding
  168. * @method splitForSharded
  169. */
  170. proto.splitForSharded = function splitForSharded() {
  171. var shardPipeline = new Pipeline({});
  172. shardPipeline.explain = this.explain;
  173. klass.optimizations.sharded.findSplitPoint(shardPipeline, this);
  174. klass.optimizations.sharded.moveFinalUnwindFromShardsToMerger(shardPipeline, this);
  175. //klass.optimizations.sharded.limitFieldsSentFromShardsToMerger(shardPipeline, this);
  176. };
  177. /**
  178. * Split the source into Merge sources and Shard sources
  179. * @static
  180. * @method findSplitPoint
  181. * @param shardPipe Shard sources
  182. * @param mergePipe Merge sources
  183. */
  184. klass.optimizations.sharded.findSplitPoint = function findSplitPoint(shardPipe, mergePipe) {
  185. while(mergePipe.sources.length > 0) {
  186. var current = mergePipe.sources[0];
  187. mergePipe.sources.splice(0, 1);
  188. if (typeof current.isSplittable != "undefined") {
  189. shardPipe.sources.push(current);
  190. }
  191. else {
  192. var shardSource = current.getShardSource(),
  193. mergeSource = current.getMergeSource();
  194. if (typeof shardSource != "undefined") { shardPipe.sources.push(shardSource); } //push_back
  195. if (typeof mergeSource != "undefined") { mergePipe.sources.unshift(mergeSource); } //push_front
  196. break;
  197. }
  198. }
  199. };
  200. /**
  201. * Optimize pipeline through moving unwind to the end
  202. * @static
  203. * @method moveFinalUnwindFromShardsToMerger
  204. * @param shardPipe shard sources
  205. * @param mergePipe merge sources
  206. */
  207. klass.optimizations.sharded.moveFinalUnwindFromShardsToMerger = function moveFinalUnwindFromShardsToMerger(shardPipe, mergePipe) {
  208. while((shardPipe.sources != null) && (!shardPipe.sources.length > 0
  209. && shardPipe.sources[length-1].constructor === UnwindDocumentSource)) {
  210. mergePipe.sources.unshift(shardPipe.sources[length-1]);
  211. shardPipe.sources.pop();
  212. }
  213. };
  214. //SKIPPED: optimizations.sharded.limitFieldsSentFromShardsToMerger. Somehow what this produces is not handled by Expression.js (err 16404)
  215. /**
  216. * Optimize pipeline by adding $project stage if shard fields are not exhaustive
  217. * @static
  218. * @method limitFieldsSentFromShardsToMerger
  219. * @param shardPipe shard sources
  220. * @param mergePipe merge sources
  221. */
  222. // klass.optimizations.sharded.limitFieldsSentFromShardsToMerger = function limitFieldsSentFromShardsToMerger(shardPipe, mergePipe) {
  223. // var mergeDeps = mergePipe.getDependencies(shardPipe.getInitialQuery());
  224. // if (mergeDeps.needWholeDocument) {
  225. // return;
  226. // }
  227. // if (mergeDeps.fields == null) {
  228. // mergeDeps.fields = {};
  229. // }
  230. // if (mergeDeps.fields.length == 0) {
  231. // mergeDeps.fields["_id"] = 0;
  232. // }
  233. // if (shardPipe.sources == null) {
  234. // shardPipe.sources = {};
  235. // }
  236. // //NOTE: Deviation from Mongo: not setting mergeDeps.needTextScore because we aren't handling that (Document meta stuff)
  237. // // HEURISTIC: only apply optimization if none of the shard stages have an exhaustive list of
  238. // // field dependencies. While this may not be 100% ideal in all cases, it is simple and
  239. // // avoids the worst cases by ensuring that:
  240. // // 1) Optimization IS applied when the shards wouldn't have known their exhaustive list of
  241. // // dependencies. This situation can happen when a $sort is before the first $project or
  242. // // $group. Without the optimization, the shards would have to reify and transmit full
  243. // // objects even though only a subset of fields are needed.
  244. // // 2) Optimization IS NOT applied immediately following a $project or $group since it would
  245. // // add an unnecessary project (and therefore a deep-copy).
  246. // for (var i = 0; i < shardPipe.sources.length; i++) {
  247. // if (shardPipe.sources.getDependencies() & DocumentSource.GetDepsReturn.EXHAUSTIVE_FIELDS)
  248. // return;
  249. // }
  250. // // if we get here, add the project.
  251. // shardPipe.sources.push(ProjectDocumentSource.createFromJson({$project: mergeDeps.toProjection()[0]}, shardPipe.ctx));
  252. // };
  253. /**
  254. * Create an `Array` of `DocumentSource`s from the given JSON pipeline
  255. * // NOTE: DEVIATION FROM MONGO: split out into a separate function to better allow extensions (was in parseCommand)
  256. * @static
  257. * @method parseDocumentSources
  258. * @param pipeline {Array} The JSON pipeline
  259. * @returns {Array} The parsed `DocumentSource`s
  260. */
  261. klass.parseDocumentSources = function parseDocumentSources(pipeline, ctx){
  262. var sources = [];
  263. for (var nSteps = pipeline.length, iStep = 0; iStep < nSteps; ++iStep) {
  264. // pull out the pipeline element as an object
  265. var pipeElement = pipeline[iStep];
  266. if (!(pipeElement instanceof Object)) throw new Error("pipeline element " + iStep + " is not an object; code 15942");
  267. var obj = pipeElement;
  268. // Parse a pipeline stage from 'obj'.
  269. if (Object.keys(obj).length !== 1) throw new Error("A pipeline stage specification object must contain exactly one field; code 16435");
  270. var stageName = Object.keys(obj)[0],
  271. stageSpec = obj[stageName];
  272. // Create a DocumentSource pipeline stage from 'stageSpec'.
  273. var desc = klass.stageDesc[stageName];
  274. if (!desc) throw new Error("Unrecognized pipeline stage name: '" + stageName + "'; code 16436");
  275. // Parse the stage
  276. var stage = desc(stageSpec, ctx);
  277. if (!stage) throw new Error("Stage must not be undefined!"); // verify(stage)
  278. sources.push(stage);
  279. if(stage.constructor === OutDocumentSource && iStep !== nSteps - 1) {
  280. throw new Error("$out can only be the final stage in the pipeline; code 16991");
  281. }
  282. }
  283. return sources;
  284. };
  285. /**
  286. * Create a pipeline from the command.
  287. * @static
  288. * @method parseCommand
  289. * @param cmdObj {Object} The command object sent from the client
  290. * @param cmdObj.aggregate {Array} the thing to aggregate against; // NOTE: DEVIATION FROM MONGO: expects an Array of inputs rather than a collection name
  291. * @param cmdObj.pipeline {Object} the JSON pipeline of `DocumentSource` specs
  292. * @param cmdObj.explain {Boolean} should explain?
  293. * @param cmdObj.fromRouter {Boolean} is from router?
  294. * @param cmdObj.splitMongodPipeline {Boolean} should split?
  295. * @param ctx {Object} Not used yet in mungedb-aggregate
  296. * @returns {Array} the pipeline, if created, otherwise a NULL reference
  297. */
  298. klass.parseCommand = function parseCommand(cmdObj, ctx){
  299. var pipelineNamespace = require("./"),
  300. Pipeline = pipelineNamespace.Pipeline, // using require in case Pipeline gets replaced with an extension
  301. pipelineInst = new Pipeline(ctx);
  302. //gather the specification for the aggregation
  303. var pipeline;
  304. for(var fieldName in cmdObj){
  305. var cmdElement = cmdObj[fieldName];
  306. if(fieldName[0] == "$") continue;
  307. else if(fieldName == "cursor") continue;
  308. else if(fieldName == klass.COMMAND_NAME) continue; //look for the aggregation command
  309. else if(fieldName == klass.PIPELINE_NAME) pipeline = cmdElement; //check for the pipeline of JSON doc srcs
  310. else if(fieldName == klass.EXPLAIN_NAME) pipelineInst.explain = cmdElement; //check for explain option
  311. else if(fieldName == klass.FROM_ROUTER_NAME) ctx.inShard = cmdElement; //if the request came from the router, we're in a shard
  312. else if(fieldName == "allowDiskUsage") {
  313. if(typeof cmdElement !== 'boolean') throw new Error("allowDiskUsage must be a bool, not a " + typeof allowDiskUsage+ "; uassert code 16949");
  314. }
  315. else throw new Error("unrecognized field " + JSON.stringify(fieldName));
  316. }
  317. /**
  318. * If we get here, we've harvested the fields we expect for a pipeline
  319. * Set up the specified document source pipeline.
  320. */
  321. // NOTE: DEVIATION FROM MONGO: split this into a separate function to simplify and better allow for extensions (now in parseDocumentSources)
  322. pipelineInst.sources = Pipeline.parseDocumentSources(pipeline, ctx);
  323. klass.optimizations.local.moveMatchBeforeSort(pipelineInst);
  324. klass.optimizations.local.moveLimitBeforeSkip(pipelineInst);
  325. klass.optimizations.local.coalesceAdjacent(pipelineInst);
  326. klass.optimizations.local.optimizeEachDocumentSource(pipelineInst);
  327. klass.optimizations.local.duplicateMatchBeforeInitalRedact(pipelineInst);
  328. return pipelineInst;
  329. };
  330. // sync callback for Pipeline#run if omitted
  331. klass.SYNC_CALLBACK = function(err, results){
  332. if (err) throw err;
  333. return results.result;
  334. };
  335. function ifError(err) {
  336. if (err) throw err;
  337. }
  338. /**
  339. * Gets the initial $match query when $match is the first pipeline stage
  340. * @method run
  341. * @param inputSource {DocumentSource} The input document source for the pipeline
  342. * @param [callback] {Function} Optional callback function if using async extensions
  343. * @return {Object} An empty object or the match spec
  344. */
  345. proto.getInitialQuery = function getInitialQuery() {
  346. var sources = this.sources;
  347. if((sources == null) || (sources.length === 0)) {
  348. return {};
  349. }
  350. /* look for an initial $match */
  351. var match = sources[0].constructor === MatchDocumentSource ? sources[0] : undefined;
  352. if(!match) return {};
  353. return match.getQuery();
  354. };
  355. /**
  356. * Creates the JSON representation of the pipeline
  357. * @method run
  358. * @param inputSource {DocumentSource} The input document source for the pipeline
  359. * @param [callback] {Function} Optional callback function if using async extensions
  360. * @return {Object} An empty object or the match spec
  361. */
  362. proto.serialize = function serialize() {
  363. var serialized = {},
  364. array = [];
  365. // create an array out of the pipeline operations
  366. this.sources.forEach(function(source) {
  367. source.serializeToArray(array);
  368. });
  369. serialized[klass.COMMAND_NAME] = this.ctx && this.ctx.ns && this.ctx.ns.coll ? this.ctx.ns.coll : '';
  370. serialized[klass.PIPELINE_NAME] = array;
  371. if(this.explain) serialized[klass.EXPLAIN_NAME] = this.explain;
  372. return serialized;
  373. };
  374. /**
  375. * Points each source at its previous source
  376. * @method stitch
  377. */
  378. proto.stitch = function stitch() {
  379. if(this.sources.length <= 0) throw new Error("should not have an empty pipeline; massert code 16600");
  380. /* chain together the sources we found */
  381. var prevSource = this.sources[0];
  382. for(var srci = 1, srcn = this.sources.length; srci < srcn; srci++) {
  383. var tempSource = this.sources[srci];
  384. tempSource.setSource(prevSource);
  385. prevSource = tempSource;
  386. }
  387. };
  388. /**
  389. * Run the pipeline
  390. * @method run
  391. * @param callback {Function} Optional. Run the pipeline in async mode; callback(err, result)
  392. * @return result {Object} The result of executing the pipeline
  393. */
  394. proto.run = function run(callback) {
  395. // should not get here in the explain case
  396. if(this.explain) throw new Error("Should not be running a pipeline in explain mode!");
  397. /* NOTE: DEVIATION FROM MONGO SOURCE. WE'RE SUPPORTING SYNC AND ASYNC */
  398. if(this.SYNC_MODE) {
  399. callback();
  400. return this._runSync();
  401. } else {
  402. return this._runAsync(callback);
  403. }
  404. };
  405. /**
  406. * Get the last document source in the pipeline
  407. * @method _getFinalSource
  408. * @return {Object} The DocumentSource at the end of the pipeline
  409. * @private
  410. */
  411. proto._getFinalSource = function _getFinalSource() {
  412. return this.sources[this.sources.length - 1];
  413. };
  414. /**
  415. * Run the pipeline synchronously
  416. * @method _runSync
  417. * @return {Object} The results object {result:resultArray}
  418. * @private
  419. */
  420. proto._runSync = function _runSync(callback) {
  421. var resultArray = [],
  422. finalSource = this._getFinalSource(),
  423. handleErr = function(err) {
  424. if(err) throw err;
  425. },
  426. next;
  427. while((next = finalSource.getNext(handleErr)) !== DocumentSource.EOF) {
  428. resultArray.push(next);
  429. }
  430. return {result:resultArray};
  431. };
  432. /**
  433. * Run the pipeline asynchronously
  434. * @method _runAsync
  435. * @param callback {Function} callback(err, resultObject)
  436. * @private
  437. */
  438. proto._runAsync = function _runAsync(callback) {
  439. var resultArray = [],
  440. finalSource = this._getFinalSource(),
  441. gotNext = function(err, doc) {
  442. if(err) return callback(err);
  443. if(doc !== DocumentSource.EOF) {
  444. resultArray.push(doc);
  445. return setImmediate(function() { //setImmediate to avoid callstack size issues
  446. finalSource.getNext(gotNext);
  447. });
  448. } else {
  449. return callback(null, {result:resultArray});
  450. }
  451. };
  452. finalSource.getNext(gotNext);
  453. };
  454. /**
  455. * Get the pipeline explanation
  456. * @method writeExplainOps
  457. * @return {Array} An array of source explanations
  458. */
  459. proto.writeExplainOps = function writeExplainOps() {
  460. var array = [];
  461. this.sources.forEach(function(source) {
  462. source.serializeToArray(array, /*explain=*/true);
  463. });
  464. return array;
  465. };
  466. /**
  467. * Set the source of documents for the pipeline
  468. * @method addInitialSource
  469. * @param source {DocumentSource}
  470. */
  471. proto.addInitialSource = function addInitialSource(source) {
  472. this.sources.unshift(source);
  473. };
  474. //SKIPPED: canRunInMongos
  475. proto.getDependencies = function getDependencies (initialQuery) {
  476. var deps = new DepsTracker(),
  477. knowAllFields = false;
  478. if (this.sources == null || this.sources.length == 0)
  479. return new DepsTracker();
  480. //NOTE: Deviation from Mongo -- We aren't using Meta and textscore
  481. for (var i=0; i < this.sources.length && !knowAllFields; i++) {
  482. var localDeps = new DepsTracker(),
  483. status = this.sources[i].getDependencies(localDeps);
  484. if (status === DocumentSource.GetDepsReturn.NOT_SUPPORTED) {
  485. // Assume this stage needs everything. We may still know something about our
  486. // dependencies if an earlier stage returned either EXHAUSTIVE_FIELDS or
  487. // EXHAUSTIVE_META.
  488. break;
  489. }
  490. if (!knowAllFields) {
  491. //C++ insert this range: deps.fields.insert(localDeps.fields.begin(), localDeps.fields.end());
  492. var keys = Object.keys(localDeps.fields);
  493. for (var j = 0; j < keys.length; j++) {
  494. var key = keys[j];
  495. deps.fields[key] = localDeps.fields[key];
  496. }
  497. if (localDeps.needWholeDocument)
  498. deps.needWholeDocument = true;
  499. knowAllFields = status & DocumentSource.GetDepsReturn.EXHAUSTIVE_FIELDS;
  500. }
  501. }
  502. if (!knowAllFields)
  503. deps.needWholeDocument = true; // don't know all fields we need
  504. return deps;
  505. };