aggregation_cursor.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. 'use strict';
  2. const MongoError = require('./core').MongoError;
  3. const Cursor = require('./cursor');
  4. const CursorState = require('./core/cursor').CursorState;
  5. /**
  6. * @fileOverview The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB
  7. * allowing for iteration over the results returned from the underlying query. It supports
  8. * one by one document iteration, conversion to an array or can be iterated as a Node 4.X
  9. * or higher stream
  10. *
  11. * **AGGREGATIONCURSOR Cannot directly be instantiated**
  12. * @example
  13. * const MongoClient = require('mongodb').MongoClient;
  14. * const test = require('assert');
  15. * // Connection url
  16. * const url = 'mongodb://localhost:27017';
  17. * // Database Name
  18. * const dbName = 'test';
  19. * // Connect using MongoClient
  20. * MongoClient.connect(url, function(err, client) {
  21. * // Create a collection we want to drop later
  22. * const col = client.db(dbName).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. * client.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. class AggregationCursor extends Cursor {
  52. constructor(topology, operation, options) {
  53. super(topology, operation, options);
  54. }
  55. /**
  56. * Set the batch size for the cursor.
  57. * @method
  58. * @param {number} value The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.
  59. * @throws {MongoError}
  60. * @return {AggregationCursor}
  61. */
  62. batchSize(value) {
  63. if (this.s.state === CursorState.CLOSED || this.isDead()) {
  64. throw MongoError.create({ message: 'Cursor is closed', driver: true });
  65. }
  66. if (typeof value !== 'number') {
  67. throw MongoError.create({ message: 'batchSize requires an integer', driver: true });
  68. }
  69. this.operation.options.batchSize = value;
  70. this.setCursorBatchSize(value);
  71. return this;
  72. }
  73. /**
  74. * Add a geoNear stage to the aggregation pipeline
  75. * @method
  76. * @param {object} document The geoNear stage document.
  77. * @return {AggregationCursor}
  78. */
  79. geoNear(document) {
  80. this.operation.addToPipeline({ $geoNear: document });
  81. return this;
  82. }
  83. /**
  84. * Add a group stage to the aggregation pipeline
  85. * @method
  86. * @param {object} document The group stage document.
  87. * @return {AggregationCursor}
  88. */
  89. group(document) {
  90. this.operation.addToPipeline({ $group: document });
  91. return this;
  92. }
  93. /**
  94. * Add a limit stage to the aggregation pipeline
  95. * @method
  96. * @param {number} value The state limit value.
  97. * @return {AggregationCursor}
  98. */
  99. limit(value) {
  100. this.operation.addToPipeline({ $limit: value });
  101. return this;
  102. }
  103. /**
  104. * Add a match stage to the aggregation pipeline
  105. * @method
  106. * @param {object} document The match stage document.
  107. * @return {AggregationCursor}
  108. */
  109. match(document) {
  110. this.operation.addToPipeline({ $match: document });
  111. return this;
  112. }
  113. /**
  114. * Add a maxTimeMS stage to the aggregation pipeline
  115. * @method
  116. * @param {number} value The state maxTimeMS value.
  117. * @return {AggregationCursor}
  118. */
  119. maxTimeMS(value) {
  120. this.operation.options.maxTimeMS = value;
  121. return this;
  122. }
  123. /**
  124. * Add a out stage to the aggregation pipeline
  125. * @method
  126. * @param {number} destination The destination name.
  127. * @return {AggregationCursor}
  128. */
  129. out(destination) {
  130. this.operation.addToPipeline({ $out: destination });
  131. return this;
  132. }
  133. /**
  134. * Add a project stage to the aggregation pipeline
  135. * @method
  136. * @param {object} document The project stage document.
  137. * @return {AggregationCursor}
  138. */
  139. project(document) {
  140. this.operation.addToPipeline({ $project: document });
  141. return this;
  142. }
  143. /**
  144. * Add a lookup stage to the aggregation pipeline
  145. * @method
  146. * @param {object} document The lookup stage document.
  147. * @return {AggregationCursor}
  148. */
  149. lookup(document) {
  150. this.operation.addToPipeline({ $lookup: document });
  151. return this;
  152. }
  153. /**
  154. * Add a redact stage to the aggregation pipeline
  155. * @method
  156. * @param {object} document The redact stage document.
  157. * @return {AggregationCursor}
  158. */
  159. redact(document) {
  160. this.operation.addToPipeline({ $redact: document });
  161. return this;
  162. }
  163. /**
  164. * Add a skip stage to the aggregation pipeline
  165. * @method
  166. * @param {number} value The state skip value.
  167. * @return {AggregationCursor}
  168. */
  169. skip(value) {
  170. this.operation.addToPipeline({ $skip: value });
  171. return this;
  172. }
  173. /**
  174. * Add a sort stage to the aggregation pipeline
  175. * @method
  176. * @param {object} document The sort stage document.
  177. * @return {AggregationCursor}
  178. */
  179. sort(document) {
  180. this.operation.addToPipeline({ $sort: document });
  181. return this;
  182. }
  183. /**
  184. * Add a unwind stage to the aggregation pipeline
  185. * @method
  186. * @param {(string|object)} field The unwind field name or stage document.
  187. * @return {AggregationCursor}
  188. */
  189. unwind(field) {
  190. this.operation.addToPipeline({ $unwind: field });
  191. return this;
  192. }
  193. /**
  194. * Return the cursor logger
  195. * @method
  196. * @return {Logger} return the cursor logger
  197. * @ignore
  198. */
  199. getLogger() {
  200. return this.logger;
  201. }
  202. }
  203. // aliases
  204. AggregationCursor.prototype.get = AggregationCursor.prototype.toArray;
  205. /**
  206. * AggregationCursor stream data event, fired for each document in the cursor.
  207. *
  208. * @event AggregationCursor#data
  209. * @type {object}
  210. */
  211. /**
  212. * AggregationCursor stream end event
  213. *
  214. * @event AggregationCursor#end
  215. * @type {null}
  216. */
  217. /**
  218. * AggregationCursor stream close event
  219. *
  220. * @event AggregationCursor#close
  221. * @type {null}
  222. */
  223. /**
  224. * AggregationCursor stream readable event
  225. *
  226. * @event AggregationCursor#readable
  227. * @type {null}
  228. */
  229. /**
  230. * Get the next available document from the cursor, returns null if no more documents are available.
  231. * @function AggregationCursor.prototype.next
  232. * @param {AggregationCursor~resultCallback} [callback] The result callback.
  233. * @throws {MongoError}
  234. * @return {Promise} returns Promise if no callback passed
  235. */
  236. /**
  237. * Check if there is any document still available in the cursor
  238. * @function AggregationCursor.prototype.hasNext
  239. * @param {AggregationCursor~resultCallback} [callback] The result callback.
  240. * @throws {MongoError}
  241. * @return {Promise} returns Promise if no callback passed
  242. */
  243. /**
  244. * The callback format for results
  245. * @callback AggregationCursor~toArrayResultCallback
  246. * @param {MongoError} error An error instance representing the error during the execution.
  247. * @param {object[]} documents All the documents the satisfy the cursor.
  248. */
  249. /**
  250. * Returns an array of documents. The caller is responsible for making sure that there
  251. * is enough memory to store the results. Note that the array only contain partial
  252. * results when this cursor had been previously accessed. In that case,
  253. * cursor.rewind() can be used to reset the cursor.
  254. * @method AggregationCursor.prototype.toArray
  255. * @param {AggregationCursor~toArrayResultCallback} [callback] The result callback.
  256. * @throws {MongoError}
  257. * @return {Promise} returns Promise if no callback passed
  258. */
  259. /**
  260. * The callback format for results
  261. * @callback AggregationCursor~resultCallback
  262. * @param {MongoError} error An error instance representing the error during the execution.
  263. * @param {(object|null)} result The result object if the command was executed successfully.
  264. */
  265. /**
  266. * Iterates over all the documents for this cursor. As with **{cursor.toArray}**,
  267. * not all of the elements will be iterated if this cursor had been previously accessed.
  268. * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike
  269. * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements
  270. * at any given time if batch size is specified. Otherwise, the caller is responsible
  271. * for making sure that the entire result can fit the memory.
  272. * @method AggregationCursor.prototype.each
  273. * @deprecated
  274. * @param {AggregationCursor~resultCallback} callback The result callback.
  275. * @throws {MongoError}
  276. * @return {null}
  277. */
  278. /**
  279. * Close the cursor, sending a AggregationCursor command and emitting close.
  280. * @method AggregationCursor.prototype.close
  281. * @param {AggregationCursor~resultCallback} [callback] The result callback.
  282. * @return {Promise} returns Promise if no callback passed
  283. */
  284. /**
  285. * Is the cursor closed
  286. * @method AggregationCursor.prototype.isClosed
  287. * @return {boolean}
  288. */
  289. /**
  290. * Execute the explain for the cursor
  291. *
  292. * For backwards compatibility, a verbosity of true is interpreted as "allPlansExecution"
  293. * and false as "queryPlanner". Prior to server version 3.6, aggregate()
  294. * ignores the verbosity parameter and executes in "queryPlanner".
  295. *
  296. * @method AggregationCursor.prototype.explain
  297. * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [verbosity=true] - An optional mode in which to run the explain.
  298. * @param {AggregationCursor~resultCallback} [callback] The result callback.
  299. * @return {Promise} returns Promise if no callback passed
  300. */
  301. /**
  302. * Clone the cursor
  303. * @function AggregationCursor.prototype.clone
  304. * @return {AggregationCursor}
  305. */
  306. /**
  307. * Resets the cursor
  308. * @function AggregationCursor.prototype.rewind
  309. * @return {AggregationCursor}
  310. */
  311. /**
  312. * The callback format for the forEach iterator method
  313. * @callback AggregationCursor~iteratorCallback
  314. * @param {Object} doc An emitted document for the iterator
  315. */
  316. /**
  317. * The callback error format for the forEach iterator method
  318. * @callback AggregationCursor~endCallback
  319. * @param {MongoError} error An error instance representing the error during the execution.
  320. */
  321. /**
  322. * Iterates over all the documents for this cursor using the iterator, callback pattern.
  323. * @method AggregationCursor.prototype.forEach
  324. * @param {AggregationCursor~iteratorCallback} iterator The iteration callback.
  325. * @param {AggregationCursor~endCallback} callback The end callback.
  326. * @throws {MongoError}
  327. * @return {null}
  328. */
  329. module.exports = AggregationCursor;