aggregation_cursor.js 11 KB

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