count_documents.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.CountDocumentsOperation = void 0;
  4. const aggregate_1 = require("./aggregate");
  5. /** @internal */
  6. class CountDocumentsOperation extends aggregate_1.AggregateOperation {
  7. constructor(collection, query, options) {
  8. const pipeline = [];
  9. pipeline.push({ $match: query });
  10. if (typeof options.skip === 'number') {
  11. pipeline.push({ $skip: options.skip });
  12. }
  13. if (typeof options.limit === 'number') {
  14. pipeline.push({ $limit: options.limit });
  15. }
  16. pipeline.push({ $group: { _id: 1, n: { $sum: 1 } } });
  17. super(collection.s.namespace, pipeline, options);
  18. }
  19. execute(server, session, callback) {
  20. super.execute(server, session, (err, result) => {
  21. if (err || !result) {
  22. callback(err);
  23. return;
  24. }
  25. // NOTE: We're avoiding creating a cursor here to reduce the callstack.
  26. const response = result;
  27. if (response.cursor == null || response.cursor.firstBatch == null) {
  28. callback(undefined, 0);
  29. return;
  30. }
  31. const docs = response.cursor.firstBatch;
  32. callback(undefined, docs.length ? docs[0].n : 0);
  33. });
  34. }
  35. }
  36. exports.CountDocumentsOperation = CountDocumentsOperation;
  37. //# sourceMappingURL=count_documents.js.map