estimated_document_count.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.EstimatedDocumentCountOperation = void 0;
  4. const utils_1 = require("../utils");
  5. const command_1 = require("./command");
  6. const operation_1 = require("./operation");
  7. /** @internal */
  8. class EstimatedDocumentCountOperation extends command_1.CommandOperation {
  9. constructor(collection, options = {}) {
  10. super(collection, options);
  11. this.options = options;
  12. this.collectionName = collection.collectionName;
  13. }
  14. execute(server, session, callback) {
  15. if ((0, utils_1.maxWireVersion)(server) < 12) {
  16. return this.executeLegacy(server, session, callback);
  17. }
  18. const pipeline = [{ $collStats: { count: {} } }, { $group: { _id: 1, n: { $sum: '$count' } } }];
  19. const cmd = { aggregate: this.collectionName, pipeline, cursor: {} };
  20. if (typeof this.options.maxTimeMS === 'number') {
  21. cmd.maxTimeMS = this.options.maxTimeMS;
  22. }
  23. super.executeCommand(server, session, cmd, (err, response) => {
  24. var _a, _b;
  25. if (err && err.code !== 26) {
  26. callback(err);
  27. return;
  28. }
  29. callback(undefined, ((_b = (_a = response === null || response === void 0 ? void 0 : response.cursor) === null || _a === void 0 ? void 0 : _a.firstBatch[0]) === null || _b === void 0 ? void 0 : _b.n) || 0);
  30. });
  31. }
  32. executeLegacy(server, session, callback) {
  33. const cmd = { count: this.collectionName };
  34. if (typeof this.options.maxTimeMS === 'number') {
  35. cmd.maxTimeMS = this.options.maxTimeMS;
  36. }
  37. super.executeCommand(server, session, cmd, (err, response) => {
  38. if (err) {
  39. callback(err);
  40. return;
  41. }
  42. callback(undefined, response.n || 0);
  43. });
  44. }
  45. }
  46. exports.EstimatedDocumentCountOperation = EstimatedDocumentCountOperation;
  47. (0, operation_1.defineAspects)(EstimatedDocumentCountOperation, [
  48. operation_1.Aspect.READ_OPERATION,
  49. operation_1.Aspect.RETRYABLE,
  50. operation_1.Aspect.CURSOR_CREATING
  51. ]);
  52. //# sourceMappingURL=estimated_document_count.js.map