Source: lib/aggregation_cursor.js

  1. "use strict";
  2. var inherits = require('util').inherits
  3. , MongoError = require('mongodb-core').MongoError
  4. , Readable = require('stream').Readable || require('readable-stream').Readable
  5. , Define = require('./metadata')
  6. , CoreCursor = require('./cursor');
  7. /**
  8. * @fileOverview The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB
  9. * allowing for iteration over the results returned from the underlying query. It supports
  10. * one by one document iteration, conversion to an array or can be iterated as a Node 0.10.X
  11. * or higher stream
  12. *
  13. * **AGGREGATIONCURSOR Cannot directly be instantiated**
  14. * @example
  15. * var MongoClient = require('mongodb').MongoClient,
  16. * test = require('assert');
  17. * // Connection url
  18. * var url = 'mongodb://localhost:27017/test';
  19. * // Connect using MongoClient
  20. * MongoClient.connect(url, function(err, db) {
  21. * // Create a collection we want to drop later
  22. * var col = db.collection('createIndexExample1');
  23. * // Insert a bunch of documents
  24. * col.insert([{a:1, b:1}
  25. * , {a:2, b:2}, {a:3, b:3}
  26. * , {a:4, b:4}], {w:1}, function(err, result) {
  27. * test.equal(null, err);
  28. * // Show that duplicate records got dropped
  29. * col.aggregation({}, {cursor: {}}).toArray(function(err, items) {
  30. * test.equal(null, err);
  31. * test.equal(4, items.length);
  32. * db.close();
  33. * });
  34. * });
  35. * });
  36. */
  37. /**
  38. * Namespace provided by the browser.
  39. * @external Readable
  40. */
  41. /**
  42. * Creates a new Aggregation Cursor instance (INTERNAL TYPE, do not instantiate directly)
  43. * @class AggregationCursor
  44. * @extends external:Readable
  45. * @fires AggregationCursor#data
  46. * @fires AggregationCursor#end
  47. * @fires AggregationCursor#close
  48. * @fires AggregationCursor#readable
  49. * @return {AggregationCursor} an AggregationCursor instance.
  50. */
  51. var AggregationCursor = function(bson, ns, cmd, options, topology, topologyOptions) {
  52. CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0));
  53. var state = AggregationCursor.INIT;
  54. var streamOptions = {};
  55. // MaxTimeMS
  56. var maxTimeMS = null;
  57. // Get the promiseLibrary
  58. var promiseLibrary = options.promiseLibrary;
  59. // No promise library selected fall back
  60. if(!promiseLibrary) {
  61. promiseLibrary = typeof global.Promise == 'function' ?
  62. global.Promise : require('es6-promise').Promise;
  63. }
  64. // Set up
  65. Readable.call(this, {objectMode: true});
  66. // Internal state
  67. this.s = {
  68. // MaxTimeMS
  69. maxTimeMS: maxTimeMS
  70. // State
  71. , state: state
  72. // Stream options
  73. , streamOptions: streamOptions
  74. // BSON
  75. , bson: bson
  76. // Namespace
  77. , ns: ns
  78. // Command
  79. , cmd: cmd
  80. // Options
  81. , options: options
  82. // Topology
  83. , topology: topology
  84. // Topology Options
  85. , topologyOptions: topologyOptions
  86. // Promise library
  87. , promiseLibrary: promiseLibrary
  88. }
  89. }
  90. /**
  91. * AggregationCursor stream data event, fired for each document in the cursor.
  92. *
  93. * @event AggregationCursor#data
  94. * @type {object}
  95. */
  96. /**
  97. * AggregationCursor stream end event
  98. *
  99. * @event AggregationCursor#end
  100. * @type {null}
  101. */
  102. /**
  103. * AggregationCursor stream close event
  104. *
  105. * @event AggregationCursor#close
  106. * @type {null}
  107. */
  108. /**
  109. * AggregationCursor stream readable event
  110. *
  111. * @event AggregationCursor#readable
  112. * @type {null}
  113. */
  114. // Inherit from Readable
  115. inherits(AggregationCursor, Readable);
  116. // Extend the Cursor
  117. for(var name in CoreCursor.prototype) {
  118. AggregationCursor.prototype[name] = CoreCursor.prototype[name];
  119. }
  120. var define = AggregationCursor.define = new Define('AggregationCursor', AggregationCursor, true);
  121. /**
  122. * Set the batch size for the cursor.
  123. * @method
  124. * @param {number} value The batchSize for the cursor.
  125. * @throws {MongoError}
  126. * @return {AggregationCursor}
  127. */
  128. AggregationCursor.prototype.batchSize = function(value) {
  129. if(this.s.state == AggregationCursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true });
  130. if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", driver:true });
  131. if(this.s.cmd.cursor) this.s.cmd.cursor.batchSize = value;
  132. this.setCursorBatchSize(value);
  133. return this;
  134. }
  135. define.classMethod('batchSize', {callback: false, promise:false, returns: [AggregationCursor]});
  136. /**
  137. * Add a geoNear stage to the aggregation pipeline
  138. * @method
  139. * @param {object} document The geoNear stage document.
  140. * @return {AggregationCursor}
  141. */
  142. AggregationCursor.prototype.geoNear = function(document) {
  143. this.s.cmd.pipeline.push({$geoNear: document});
  144. return this;
  145. }
  146. define.classMethod('geoNear', {callback: false, promise:false, returns: [AggregationCursor]});
  147. /**
  148. * Add a group stage to the aggregation pipeline
  149. * @method
  150. * @param {object} document The group stage document.
  151. * @return {AggregationCursor}
  152. */
  153. AggregationCursor.prototype.group = function(document) {
  154. this.s.cmd.pipeline.push({$group: document});
  155. return this;
  156. }
  157. define.classMethod('group', {callback: false, promise:false, returns: [AggregationCursor]});
  158. /**
  159. * Add a limit stage to the aggregation pipeline
  160. * @method
  161. * @param {number} value The state limit value.
  162. * @return {AggregationCursor}
  163. */
  164. AggregationCursor.prototype.limit = function(value) {
  165. this.s.cmd.pipeline.push({$limit: value});
  166. return this;
  167. }
  168. define.classMethod('limit', {callback: false, promise:false, returns: [AggregationCursor]});
  169. /**
  170. * Add a match stage to the aggregation pipeline
  171. * @method
  172. * @param {object} document The match stage document.
  173. * @return {AggregationCursor}
  174. */
  175. AggregationCursor.prototype.match = function(document) {
  176. this.s.cmd.pipeline.push({$match: document});
  177. return this;
  178. }
  179. define.classMethod('match', {callback: false, promise:false, returns: [AggregationCursor]});
  180. /**
  181. * Add a maxTimeMS stage to the aggregation pipeline
  182. * @method
  183. * @param {number} value The state maxTimeMS value.
  184. * @return {AggregationCursor}
  185. */
  186. AggregationCursor.prototype.maxTimeMS = function(value) {
  187. if(this.s.topology.lastIsMaster().minWireVersion > 2) {
  188. this.s.cmd.maxTimeMS = value;
  189. }
  190. return this;
  191. }
  192. define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [AggregationCursor]});
  193. /**
  194. * Add a out stage to the aggregation pipeline
  195. * @method
  196. * @param {number} destination The destination name.
  197. * @return {AggregationCursor}
  198. */
  199. AggregationCursor.prototype.out = function(destination) {
  200. this.s.cmd.pipeline.push({$out: destination});
  201. return this;
  202. }
  203. define.classMethod('out', {callback: false, promise:false, returns: [AggregationCursor]});
  204. /**
  205. * Add a project stage to the aggregation pipeline
  206. * @method
  207. * @param {object} document The project stage document.
  208. * @return {AggregationCursor}
  209. */
  210. AggregationCursor.prototype.project = function(document) {
  211. this.s.cmd.pipeline.push({$project: document});
  212. return this;
  213. }
  214. define.classMethod('project', {callback: false, promise:false, returns: [AggregationCursor]});
  215. /**
  216. * Add a lookup stage to the aggregation pipeline
  217. * @method
  218. * @param {object} document The lookup stage document.
  219. * @return {AggregationCursor}
  220. */
  221. AggregationCursor.prototype.lookup = function(document) {
  222. this.s.cmd.pipeline.push({$lookup: document});
  223. return this;
  224. }
  225. define.classMethod('lookup', {callback: false, promise:false, returns: [AggregationCursor]});
  226. /**
  227. * Add a redact stage to the aggregation pipeline
  228. * @method
  229. * @param {object} document The redact stage document.
  230. * @return {AggregationCursor}
  231. */
  232. AggregationCursor.prototype.redact = function(document) {
  233. this.s.cmd.pipeline.push({$redact: document});
  234. return this;
  235. }
  236. define.classMethod('redact', {callback: false, promise:false, returns: [AggregationCursor]});
  237. /**
  238. * Add a skip stage to the aggregation pipeline
  239. * @method
  240. * @param {number} value The state skip value.
  241. * @return {AggregationCursor}
  242. */
  243. AggregationCursor.prototype.skip = function(value) {
  244. this.s.cmd.pipeline.push({$skip: value});
  245. return this;
  246. }
  247. define.classMethod('skip', {callback: false, promise:false, returns: [AggregationCursor]});
  248. /**
  249. * Add a sort stage to the aggregation pipeline
  250. * @method
  251. * @param {object} document The sort stage document.
  252. * @return {AggregationCursor}
  253. */
  254. AggregationCursor.prototype.sort = function(document) {
  255. this.s.cmd.pipeline.push({$sort: document});
  256. return this;
  257. }
  258. define.classMethod('sort', {callback: false, promise:false, returns: [AggregationCursor]});
  259. /**
  260. * Add a unwind stage to the aggregation pipeline
  261. * @method
  262. * @param {number} field The unwind field name.
  263. * @return {AggregationCursor}
  264. */
  265. AggregationCursor.prototype.unwind = function(field) {
  266. this.s.cmd.pipeline.push({$unwind: field});
  267. return this;
  268. }
  269. define.classMethod('unwind', {callback: false, promise:false, returns: [AggregationCursor]});
  270. AggregationCursor.prototype.get = AggregationCursor.prototype.toArray;
  271. // Inherited methods
  272. define.classMethod('toArray', {callback: true, promise:true});
  273. define.classMethod('each', {callback: true, promise:false});
  274. define.classMethod('forEach', {callback: true, promise:false});
  275. define.classMethod('hasNext', {callback: true, promise:true});
  276. define.classMethod('next', {callback: true, promise:true});
  277. define.classMethod('close', {callback: true, promise:true});
  278. define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]});
  279. define.classMethod('rewind', {callback: false, promise:false});
  280. define.classMethod('bufferedCount', {callback: false, promise:false, returns: [Number]});
  281. define.classMethod('readBufferedDocuments', {callback: false, promise:false, returns: [Array]});
  282. /**
  283. * Get the next available document from the cursor, returns null if no more documents are available.
  284. * @function AggregationCursor.prototype.next
  285. * @param {AggregationCursor~resultCallback} [callback] The result callback.
  286. * @throws {MongoError}
  287. * @return {Promise} returns Promise if no callback passed
  288. */
  289. /**
  290. * Check if there is any document still available in the cursor
  291. * @function AggregationCursor.prototype.hasNext
  292. * @param {AggregationCursor~resultCallback} [callback] The result callback.
  293. * @throws {MongoError}
  294. * @return {Promise} returns Promise if no callback passed
  295. */
  296. /**
  297. * The callback format for results
  298. * @callback AggregationCursor~toArrayResultCallback
  299. * @param {MongoError} error An error instance representing the error during the execution.
  300. * @param {object[]} documents All the documents the satisfy the cursor.
  301. */
  302. /**
  303. * Returns an array of documents. The caller is responsible for making sure that there
  304. * is enough memory to store the results. Note that the array only contain partial
  305. * results when this cursor had been previously accessed. In that case,
  306. * cursor.rewind() can be used to reset the cursor.
  307. * @method AggregationCursor.prototype.toArray
  308. * @param {AggregationCursor~toArrayResultCallback} [callback] The result callback.
  309. * @throws {MongoError}
  310. * @return {Promise} returns Promise if no callback passed
  311. */
  312. /**
  313. * The callback format for results
  314. * @callback AggregationCursor~resultCallback
  315. * @param {MongoError} error An error instance representing the error during the execution.
  316. * @param {(object|null)} result The result object if the command was executed successfully.
  317. */
  318. /**
  319. * Iterates over all the documents for this cursor. As with **{cursor.toArray}**,
  320. * not all of the elements will be iterated if this cursor had been previously accessed.
  321. * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike
  322. * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements
  323. * at any given time if batch size is specified. Otherwise, the caller is responsible
  324. * for making sure that the entire result can fit the memory.
  325. * @method AggregationCursor.prototype.each
  326. * @param {AggregationCursor~resultCallback} callback The result callback.
  327. * @throws {MongoError}
  328. * @return {null}
  329. */
  330. /**
  331. * Close the cursor, sending a AggregationCursor command and emitting close.
  332. * @method AggregationCursor.prototype.close
  333. * @param {AggregationCursor~resultCallback} [callback] The result callback.
  334. * @return {Promise} returns Promise if no callback passed
  335. */
  336. /**
  337. * Is the cursor closed
  338. * @method AggregationCursor.prototype.isClosed
  339. * @return {boolean}
  340. */
  341. /**
  342. * Execute the explain for the cursor
  343. * @method AggregationCursor.prototype.explain
  344. * @param {AggregationCursor~resultCallback} [callback] The result callback.
  345. * @return {Promise} returns Promise if no callback passed
  346. */
  347. /**
  348. * Clone the cursor
  349. * @function AggregationCursor.prototype.clone
  350. * @return {AggregationCursor}
  351. */
  352. /**
  353. * Resets the cursor
  354. * @function AggregationCursor.prototype.rewind
  355. * @return {AggregationCursor}
  356. */
  357. /**
  358. * The callback format for the forEach iterator method
  359. * @callback AggregationCursor~iteratorCallback
  360. * @param {Object} doc An emitted document for the iterator
  361. */
  362. /**
  363. * The callback error format for the forEach iterator method
  364. * @callback AggregationCursor~endCallback
  365. * @param {MongoError} error An error instance representing the error during the execution.
  366. */
  367. /*
  368. * Iterates over all the documents for this cursor using the iterator, callback pattern.
  369. * @method AggregationCursor.prototype.forEach
  370. * @param {AggregationCursor~iteratorCallback} iterator The iteration callback.
  371. * @param {AggregationCursor~endCallback} callback The end callback.
  372. * @throws {MongoError}
  373. * @return {null}
  374. */
  375. AggregationCursor.INIT = 0;
  376. AggregationCursor.OPEN = 1;
  377. AggregationCursor.CLOSED = 2;
  378. module.exports = AggregationCursor;