count_documents.js 1.2 KB

12345678910111213141516171819202122232425262728293031
  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. async execute(server, session) {
  20. const result = await super.execute(server, session);
  21. // NOTE: We're avoiding creating a cursor here to reduce the callstack.
  22. const response = result;
  23. if (response.cursor == null || response.cursor.firstBatch == null) {
  24. return 0;
  25. }
  26. const docs = response.cursor.firstBatch;
  27. return docs.length ? docs[0].n : 0;
  28. }
  29. }
  30. exports.CountDocumentsOperation = CountDocumentsOperation;
  31. //# sourceMappingURL=count_documents.js.map