count_documents.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. 'use strict';
  2. const AggregateOperation = require('./aggregate');
  3. class CountDocumentsOperation extends AggregateOperation {
  4. constructor(collection, query, options) {
  5. const pipeline = [{ $match: query }];
  6. if (typeof options.skip === 'number') {
  7. pipeline.push({ $skip: options.skip });
  8. }
  9. if (typeof options.limit === 'number') {
  10. pipeline.push({ $limit: options.limit });
  11. }
  12. pipeline.push({ $group: { _id: 1, n: { $sum: 1 } } });
  13. super(collection, pipeline, options);
  14. }
  15. execute(server, callback) {
  16. super.execute(server, (err, result) => {
  17. if (err) {
  18. callback(err, null);
  19. return;
  20. }
  21. // NOTE: We're avoiding creating a cursor here to reduce the callstack.
  22. const response = result.result;
  23. if (response.cursor == null || response.cursor.firstBatch == null) {
  24. callback(null, 0);
  25. return;
  26. }
  27. const docs = response.cursor.firstBatch;
  28. callback(null, docs.length ? docs[0].n : 0);
  29. });
  30. }
  31. }
  32. module.exports = CountDocumentsOperation;