3 var inherits = require('util').inherits
4 , f = require('util').format
5 , toError = require('./utils').toError
6 , getSingleProperty = require('./utils').getSingleProperty
7 , formattedOrderClause = require('./utils').formattedOrderClause
8 , handleCallback = require('./utils').handleCallback
9 , Logger = require('mongodb-core').Logger
10 , EventEmitter = require('events').EventEmitter
11 , ReadPreference = require('./read_preference')
12 , MongoError = require('mongodb-core').MongoError
13 , Readable = require('stream').Readable || require('readable-stream').Readable
14 , Define = require('./metadata')
15 , CoreCursor = require('./cursor')
16 , Query = require('mongodb-core').Query;
19 * @fileOverview The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB
20 * allowing for iteration over the results returned from the underlying query. It supports
21 * one by one document iteration, conversion to an array or can be iterated as a Node 0.10.X
24 * **AGGREGATIONCURSOR Cannot directly be instantiated**
26 * var MongoClient = require('mongodb').MongoClient,
27 * test = require('assert');
29 * var url = 'mongodb://localhost:27017/test';
30 * // Connect using MongoClient
31 * MongoClient.connect(url, function(err, db) {
32 * // Create a collection we want to drop later
33 * var col = db.collection('createIndexExample1');
34 * // Insert a bunch of documents
35 * col.insert([{a:1, b:1}
36 * , {a:2, b:2}, {a:3, b:3}
37 * , {a:4, b:4}], {w:1}, function(err, result) {
38 * test.equal(null, err);
39 * // Show that duplicate records got dropped
40 * col.aggregation({}, {cursor: {}}).toArray(function(err, items) {
41 * test.equal(null, err);
42 * test.equal(4, items.length);
50 * Namespace provided by the browser.
55 * Creates a new Aggregation Cursor instance (INTERNAL TYPE, do not instantiate directly)
56 * @class AggregationCursor
57 * @extends external:Readable
58 * @fires AggregationCursor#data
59 * @fires AggregationCursor#end
60 * @fires AggregationCursor#close
61 * @fires AggregationCursor#readable
62 * @return {AggregationCursor} an AggregationCursor instance.
64 var AggregationCursor = function(bson, ns, cmd, options, topology, topologyOptions) {
65 CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0));
67 var state = AggregationCursor.INIT;
68 var streamOptions = {};
73 // Get the promiseLibrary
74 var promiseLibrary = options.promiseLibrary;
76 // No promise library selected fall back
78 promiseLibrary = typeof global.Promise == 'function' ?
79 global.Promise : require('es6-promise').Promise;
83 Readable.call(this, {objectMode: true});
92 , streamOptions: streamOptions
104 , topologyOptions: topologyOptions
106 , promiseLibrary: promiseLibrary
111 * AggregationCursor stream data event, fired for each document in the cursor.
113 * @event AggregationCursor#data
118 * AggregationCursor stream end event
120 * @event AggregationCursor#end
125 * AggregationCursor stream close event
127 * @event AggregationCursor#close
132 * AggregationCursor stream readable event
134 * @event AggregationCursor#readable
138 // Inherit from Readable
139 inherits(AggregationCursor, Readable);
141 // Set the methods to inherit from prototype
142 var methodsToInherit = ['_next', 'next', 'each', 'forEach', 'toArray'
143 , 'rewind', 'bufferedCount', 'readBufferedDocuments', 'close', 'isClosed', 'kill'
144 , '_find', '_getmore', '_killcursor', 'isDead', 'explain', 'isNotified'];
147 for(var name in CoreCursor.prototype) {
148 AggregationCursor.prototype[name] = CoreCursor.prototype[name];
151 var define = AggregationCursor.define = new Define('AggregationCursor', AggregationCursor, true);
154 * Set the batch size for the cursor.
156 * @param {number} value The batchSize for the cursor.
157 * @throws {MongoError}
158 * @return {AggregationCursor}
160 AggregationCursor.prototype.batchSize = function(value) {
161 if(this.s.state == AggregationCursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true });
162 if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", drvier:true });
163 if(this.s.cmd.cursor) this.s.cmd.cursor.batchSize = value;
164 this.setCursorBatchSize(value);
168 define.classMethod('batchSize', {callback: false, promise:false, returns: [AggregationCursor]});
171 * Add a geoNear stage to the aggregation pipeline
173 * @param {object} document The geoNear stage document.
174 * @return {AggregationCursor}
176 AggregationCursor.prototype.geoNear = function(document) {
177 this.s.cmd.pipeline.push({$geoNear: document});
181 define.classMethod('geoNear', {callback: false, promise:false, returns: [AggregationCursor]});
184 * Add a group stage to the aggregation pipeline
186 * @param {object} document The group stage document.
187 * @return {AggregationCursor}
189 AggregationCursor.prototype.group = function(document) {
190 this.s.cmd.pipeline.push({$group: document});
194 define.classMethod('group', {callback: false, promise:false, returns: [AggregationCursor]});
197 * Add a limit stage to the aggregation pipeline
199 * @param {number} value The state limit value.
200 * @return {AggregationCursor}
202 AggregationCursor.prototype.limit = function(value) {
203 this.s.cmd.pipeline.push({$limit: value});
207 define.classMethod('limit', {callback: false, promise:false, returns: [AggregationCursor]});
210 * Add a match stage to the aggregation pipeline
212 * @param {object} document The match stage document.
213 * @return {AggregationCursor}
215 AggregationCursor.prototype.match = function(document) {
216 this.s.cmd.pipeline.push({$match: document});
220 define.classMethod('match', {callback: false, promise:false, returns: [AggregationCursor]});
223 * Add a maxTimeMS stage to the aggregation pipeline
225 * @param {number} value The state maxTimeMS value.
226 * @return {AggregationCursor}
228 AggregationCursor.prototype.maxTimeMS = function(value) {
229 if(this.s.topology.lastIsMaster().minWireVersion > 2) {
230 this.s.cmd.maxTimeMS = value;
235 define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [AggregationCursor]});
238 * Add a out stage to the aggregation pipeline
240 * @param {number} destination The destination name.
241 * @return {AggregationCursor}
243 AggregationCursor.prototype.out = function(destination) {
244 this.s.cmd.pipeline.push({$out: destination});
248 define.classMethod('out', {callback: false, promise:false, returns: [AggregationCursor]});
251 * Add a project stage to the aggregation pipeline
253 * @param {object} document The project stage document.
254 * @return {AggregationCursor}
256 AggregationCursor.prototype.project = function(document) {
257 this.s.cmd.pipeline.push({$project: document});
261 define.classMethod('project', {callback: false, promise:false, returns: [AggregationCursor]});
264 * Add a lookup stage to the aggregation pipeline
266 * @param {object} document The lookup stage document.
267 * @return {AggregationCursor}
269 AggregationCursor.prototype.lookup = function(document) {
270 this.s.cmd.pipeline.push({$lookup: document});
274 define.classMethod('lookup', {callback: false, promise:false, returns: [AggregationCursor]});
277 * Add a redact stage to the aggregation pipeline
279 * @param {object} document The redact stage document.
280 * @return {AggregationCursor}
282 AggregationCursor.prototype.redact = function(document) {
283 this.s.cmd.pipeline.push({$redact: document});
287 define.classMethod('redact', {callback: false, promise:false, returns: [AggregationCursor]});
290 * Add a skip stage to the aggregation pipeline
292 * @param {number} value The state skip value.
293 * @return {AggregationCursor}
295 AggregationCursor.prototype.skip = function(value) {
296 this.s.cmd.pipeline.push({$skip: value});
300 define.classMethod('skip', {callback: false, promise:false, returns: [AggregationCursor]});
303 * Add a sort stage to the aggregation pipeline
305 * @param {object} document The sort stage document.
306 * @return {AggregationCursor}
308 AggregationCursor.prototype.sort = function(document) {
309 this.s.cmd.pipeline.push({$sort: document});
313 define.classMethod('sort', {callback: false, promise:false, returns: [AggregationCursor]});
316 * Add a unwind stage to the aggregation pipeline
318 * @param {number} field The unwind field name.
319 * @return {AggregationCursor}
321 AggregationCursor.prototype.unwind = function(field) {
322 this.s.cmd.pipeline.push({$unwind: field});
326 define.classMethod('unwind', {callback: false, promise:false, returns: [AggregationCursor]});
328 AggregationCursor.prototype.get = AggregationCursor.prototype.toArray;
331 define.classMethod('toArray', {callback: true, promise:true});
332 define.classMethod('each', {callback: true, promise:false});
333 define.classMethod('forEach', {callback: true, promise:false});
334 define.classMethod('next', {callback: true, promise:true});
335 define.classMethod('close', {callback: true, promise:true});
336 define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]});
337 define.classMethod('rewind', {callback: false, promise:false});
338 define.classMethod('bufferedCount', {callback: false, promise:false, returns: [Number]});
339 define.classMethod('readBufferedDocuments', {callback: false, promise:false, returns: [Array]});
342 * Get the next available document from the cursor, returns null if no more documents are available.
343 * @function AggregationCursor.prototype.next
344 * @param {AggregationCursor~resultCallback} [callback] The result callback.
345 * @throws {MongoError}
346 * @return {Promise} returns Promise if no callback passed
350 * The callback format for results
351 * @callback AggregationCursor~toArrayResultCallback
352 * @param {MongoError} error An error instance representing the error during the execution.
353 * @param {object[]} documents All the documents the satisfy the cursor.
357 * Returns an array of documents. The caller is responsible for making sure that there
358 * is enough memory to store the results. Note that the array only contain partial
359 * results when this cursor had been previouly accessed. In that case,
360 * cursor.rewind() can be used to reset the cursor.
361 * @method AggregationCursor.prototype.toArray
362 * @param {AggregationCursor~toArrayResultCallback} [callback] The result callback.
363 * @throws {MongoError}
364 * @return {Promise} returns Promise if no callback passed
368 * The callback format for results
369 * @callback AggregationCursor~resultCallback
370 * @param {MongoError} error An error instance representing the error during the execution.
371 * @param {(object|null)} result The result object if the command was executed successfully.
375 * Iterates over all the documents for this cursor. As with **{cursor.toArray}**,
376 * not all of the elements will be iterated if this cursor had been previouly accessed.
377 * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike
378 * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements
379 * at any given time if batch size is specified. Otherwise, the caller is responsible
380 * for making sure that the entire result can fit the memory.
381 * @method AggregationCursor.prototype.each
382 * @param {AggregationCursor~resultCallback} callback The result callback.
383 * @throws {MongoError}
388 * Close the cursor, sending a AggregationCursor command and emitting close.
389 * @method AggregationCursor.prototype.close
390 * @param {AggregationCursor~resultCallback} [callback] The result callback.
391 * @return {Promise} returns Promise if no callback passed
395 * Is the cursor closed
396 * @method AggregationCursor.prototype.isClosed
401 * Execute the explain for the cursor
402 * @method AggregationCursor.prototype.explain
403 * @param {AggregationCursor~resultCallback} [callback] The result callback.
404 * @return {Promise} returns Promise if no callback passed
409 * @function AggregationCursor.prototype.clone
410 * @return {AggregationCursor}
415 * @function AggregationCursor.prototype.rewind
416 * @return {AggregationCursor}
420 * The callback format for the forEach iterator method
421 * @callback AggregationCursor~iteratorCallback
422 * @param {Object} doc An emitted document for the iterator
426 * The callback error format for the forEach iterator method
427 * @callback AggregationCursor~endCallback
428 * @param {MongoError} error An error instance representing the error during the execution.
432 * Iterates over all the documents for this cursor using the iterator, callback pattern.
433 * @method AggregationCursor.prototype.forEach
434 * @param {AggregationCursor~iteratorCallback} iterator The iteration callback.
435 * @param {AggregationCursor~endCallback} callback The end callback.
436 * @throws {MongoError}
440 AggregationCursor.INIT = 0;
441 AggregationCursor.OPEN = 1;
442 AggregationCursor.CLOSED = 2;
444 module.exports = AggregationCursor;