All files / src/operations count.ts

100% Statements 21/21
90% Branches 9/10
100% Functions 3/3
100% Lines 21/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75            400x 400x                                 400x           20581x   20581x 20581x 20581x       24730x               24272x 24272x         24272x 2279x     24272x 2279x     24272x 1194x     24272x 984x     24272x 18352x       400x  
import type { Document } from '../bson';
import type { Collection } from '../collection';
import type { Server } from '../sdam/server';
import type { ClientSession } from '../sessions';
import { type TimeoutContext } from '../timeout';
import type { MongoDBNamespace } from '../utils';
import { CommandOperation, type CommandOperationOptions } from './command';
import { Aspect, defineAspects } from './operation';
 
/** @public */
export interface CountOptions extends CommandOperationOptions {
  /** The number of documents to skip. */
  skip?: number;
  /** The maximum amounts to count before aborting. */
  limit?: number;
  /**
   * Number of milliseconds to wait before aborting the query.
   */
  maxTimeMS?: number;
  /** An index name hint for the query. */
  hint?: string | Document;
}
 
/** @internal */
export class CountOperation extends CommandOperation<number> {
  override options: CountOptions;
  collectionName?: string;
  query: Document;
 
  constructor(namespace: MongoDBNamespace, filter: Document, options: CountOptions) {
    super({ s: { namespace: namespace } } as unknown as Collection, options);
 
    this.options = options;
    this.collectionName = namespace.collection;
    this.query = filter;
  }
 
  override get commandName() {
    return 'count' as const;
  }
 
  override async execute(
    server: Server,
    session: ClientSession | undefined,
    timeoutContext: TimeoutContext
  ): Promise<number> {
    const options = this.options;
    const cmd: Document = {
      count: this.collectionName,
      query: this.query
    };
 
    if (typeof options.limit === 'number') {
      cmd.limit = options.limit;
    }
 
    if (typeof options.skip === 'number') {
      cmd.skip = options.skip;
    }
 
    if (options.hint != null) {
      cmd.hint = options.hint;
    }
 
    if (typeof options.maxTimeMS === 'number') {
      cmd.maxTimeMS = options.maxTimeMS;
    }
 
    const result = await super.executeCommand(server, session, cmd, timeoutContext);
    return result ? result.n : 0;
  }
}
 
defineAspects(CountOperation, [Aspect.READ_OPERATION, Aspect.RETRYABLE]);