All files / src/operations find.ts

91.86% Statements 79/86
88% Branches 66/75
80% Functions 4/5
91.86% Lines 79/86

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 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280  400x   400x 400x         400x     400x   400x 400x 400x                                                                                                                                       400x                       3712860x   3712669x 3712669x 3712669x   3712669x         3712669x       3727687x               3726747x   3726747x   3726747x 3726747x 8269x 8269x     3726747x                               3726747x         3726747x 144568x     3726747x 16557x 16557x                 16557x     3726747x 1313x     3726747x 18327x     3726747x 3414455x 3389171x 3389171x   25284x       3726747x 3427671x 398x               398x   3427273x       3726747x           3726747x 3465x     3726747x 7384x     3726747x 3726747x 155493x     3726747x 229x     3726747x 229x     3726747x 229x     3726747x 229x     3726747x 7297x     3726747x 4x     3726747x 229x 3726518x 1403x     3726747x 5540x     3726747x       3726747x 241x     3726747x 1031x     3726747x 229x     3726747x     400x            
import type { Document } from '../bson';
import { CursorResponse, ExplainedCursorResponse } from '../cmap/wire_protocol/responses';
import { type AbstractCursorOptions, type CursorTimeoutMode } from '../cursor/abstract_cursor';
import { MongoInvalidArgumentError } from '../error';
import {
  decorateWithExplain,
  type ExplainOptions,
  validateExplainTimeoutOptions
} from '../explain';
import { ReadConcern } from '../read_concern';
import type { Server } from '../sdam/server';
import type { ClientSession } from '../sessions';
import { formatSort, type Sort } from '../sort';
import { type TimeoutContext } from '../timeout';
import { type MongoDBNamespace, normalizeHintField } from '../utils';
import { type CollationOptions, CommandOperation, type CommandOperationOptions } from './command';
import { Aspect, defineAspects, type Hint } from './operation';
 
/**
 * @public
 * @typeParam TSchema - Unused schema definition, deprecated usage, only specify `FindOptions` with no generic
 */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export interface FindOptions<TSchema extends Document = Document>
  extends Omit<CommandOperationOptions, 'writeConcern' | 'explain'>,
    AbstractCursorOptions {
  /** Sets the limit of documents returned in the query. */
  limit?: number;
  /** Set to sort the documents coming back from the query. Array of indexes, `[['a', 1]]` etc. */
  sort?: Sort;
  /** The fields to return in the query. Object of fields to either include or exclude (one of, not both), `{'a':1, 'b': 1}` **or** `{'a': 0, 'b': 0}` */
  projection?: Document;
  /** Set to skip N documents ahead in your query (useful for pagination). */
  skip?: number;
  /** Tell the query to use specific indexes in the query. Object of indexes to use, `{'_id':1}` */
  hint?: Hint;
  /** Specify if the cursor can timeout. */
  timeout?: boolean;
  /** Specify if the cursor is tailable. */
  tailable?: boolean;
  /** Specify if the cursor is a tailable-await cursor. Requires `tailable` to be true */
  awaitData?: boolean;
  /** Set the batchSize for the getMoreCommand when iterating over the query results. */
  batchSize?: number;
  /** If true, returns only the index keys in the resulting documents. */
  returnKey?: boolean;
  /** The inclusive lower bound for a specific index */
  min?: Document;
  /** The exclusive upper bound for a specific index */
  max?: Document;
  /** Number of milliseconds to wait before aborting the query. */
  maxTimeMS?: number;
  /** The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. Requires `tailable` and `awaitData` to be true */
  maxAwaitTimeMS?: number;
  /** The server normally times out idle cursors after an inactivity period (10 minutes) to prevent excess memory use. Set this option to prevent that. */
  noCursorTimeout?: boolean;
  /** Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). */
  collation?: CollationOptions;
  /** Allows disk use for blocking sort operations exceeding 100MB memory. (MongoDB 3.2 or higher) */
  allowDiskUse?: boolean;
  /** Determines whether to close the cursor after the first batch. Defaults to false. */
  singleBatch?: boolean;
  /** For queries against a sharded collection, allows the command (or subsequent getMore commands) to return partial results, rather than an error, if one or more queried shards are unavailable. */
  allowPartialResults?: boolean;
  /** Determines whether to return the record identifier for each document. If true, adds a field $recordId to the returned documents. */
  showRecordId?: boolean;
  /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
  let?: Document;
  /**
   * Option to enable an optimized code path for queries looking for a particular range of `ts` values in the oplog. Requires `tailable` to be true.
   * @deprecated Starting from MongoDB 4.4 this flag is not needed and will be ignored.
   */
  oplogReplay?: boolean;
 
  /**
   * Specifies the verbosity mode for the explain output.
   * @deprecated This API is deprecated in favor of `collection.find().explain()`.
   */
  explain?: ExplainOptions['explain'];
  /** @internal*/
  timeoutMode?: CursorTimeoutMode;
}
 
/** @internal */
export class FindOperation extends CommandOperation<CursorResponse> {
  /**
   * @remarks WriteConcern can still be present on the options because
   * we inherit options from the client/db/collection.  The
   * key must be present on the options in order to delete it.
   * This allows typescript to delete the key but will
   * not allow a writeConcern to be assigned as a property on options.
   */
  override options: FindOptions & { writeConcern?: never };
  filter: Document;
 
  constructor(ns: MongoDBNamespace, filter: Document = {}, options: FindOptions = {}) {
    super(undefined, options);
 
    this.options = { ...options };
    delete this.options.writeConcern;
    this.ns = ns;
 
    Iif (typeof filter !== 'object' || Array.isArray(filter)) {
      throw new MongoInvalidArgumentError('Query filter must be a plain object or ObjectId');
    }
 
    // special case passing in an ObjectId as a filter
    this.filter = filter != null && filter._bsontype === 'ObjectId' ? { _id: filter } : filter;
  }
 
  override get commandName() {
    return 'find' as const;
  }
 
  override async execute(
    server: Server,
    session: ClientSession | undefined,
    timeoutContext: TimeoutContext
  ): Promise<CursorResponse> {
    this.server = server;
 
    const options = this.options;
 
    let findCommand = makeFindCommand(this.ns, this.filter, options);
    if (this.explain) {
      validateExplainTimeoutOptions(this.options, this.explain);
      findCommand = decorateWithExplain(findCommand, this.explain);
    }
 
    return await server.command(
      this.ns,
      findCommand,
      {
        ...this.options,
        ...this.bsonOptions,
        documentsReturnedIn: 'firstBatch',
        session,
        timeoutContext
      },
      this.explain ? ExplainedCursorResponse : CursorResponse
    );
  }
}
 
function makeFindCommand(ns: MongoDBNamespace, filter: Document, options: FindOptions): Document {
  const findCommand: Document = {
    find: ns.collection,
    filter
  };
 
  if (options.sort) {
    findCommand.sort = formatSort(options.sort);
  }
 
  if (options.projection) {
    let projection = options.projection;
    Iif (projection && Array.isArray(projection)) {
      projection = projection.length
        ? projection.reduce((result, field) => {
            result[field] = 1;
            return result;
          }, {})
        : { _id: 1 };
    }
 
    findCommand.projection = projection;
  }
 
  if (options.hint) {
    findCommand.hint = normalizeHintField(options.hint);
  }
 
  if (typeof options.skip === 'number') {
    findCommand.skip = options.skip;
  }
 
  if (typeof options.limit === 'number') {
    if (options.limit < 0) {
      findCommand.limit = -options.limit;
      findCommand.singleBatch = true;
    } else {
      findCommand.limit = options.limit;
    }
  }
 
  if (typeof options.batchSize === 'number') {
    if (options.batchSize < 0) {
      Iif (
        options.limit &&
        options.limit !== 0 &&
        Math.abs(options.batchSize) < Math.abs(options.limit)
      ) {
        findCommand.limit = -options.batchSize;
      }
 
      findCommand.singleBatch = true;
    } else {
      findCommand.batchSize = options.batchSize;
    }
  }
 
  Iif (typeof options.singleBatch === 'boolean') {
    findCommand.singleBatch = options.singleBatch;
  }
 
  // we check for undefined specifically here to allow falsy values
  // eslint-disable-next-line no-restricted-syntax
  if (options.comment !== undefined) {
    findCommand.comment = options.comment;
  }
 
  if (typeof options.maxTimeMS === 'number') {
    findCommand.maxTimeMS = options.maxTimeMS;
  }
 
  const readConcern = ReadConcern.fromOptions(options);
  if (readConcern) {
    findCommand.readConcern = readConcern.toJSON();
  }
 
  if (options.max) {
    findCommand.max = options.max;
  }
 
  if (options.min) {
    findCommand.min = options.min;
  }
 
  if (typeof options.returnKey === 'boolean') {
    findCommand.returnKey = options.returnKey;
  }
 
  if (typeof options.showRecordId === 'boolean') {
    findCommand.showRecordId = options.showRecordId;
  }
 
  if (typeof options.tailable === 'boolean') {
    findCommand.tailable = options.tailable;
  }
 
  if (typeof options.oplogReplay === 'boolean') {
    findCommand.oplogReplay = options.oplogReplay;
  }
 
  if (typeof options.timeout === 'boolean') {
    findCommand.noCursorTimeout = !options.timeout;
  } else if (typeof options.noCursorTimeout === 'boolean') {
    findCommand.noCursorTimeout = options.noCursorTimeout;
  }
 
  if (typeof options.awaitData === 'boolean') {
    findCommand.awaitData = options.awaitData;
  }
 
  Iif (typeof options.allowPartialResults === 'boolean') {
    findCommand.allowPartialResults = options.allowPartialResults;
  }
 
  if (options.collation) {
    findCommand.collation = options.collation;
  }
 
  if (typeof options.allowDiskUse === 'boolean') {
    findCommand.allowDiskUse = options.allowDiskUse;
  }
 
  if (options.let) {
    findCommand.let = options.let;
  }
 
  return findCommand;
}
 
defineAspects(FindOperation, [
  Aspect.READ_OPERATION,
  Aspect.RETRYABLE,
  Aspect.EXPLAINABLE,
  Aspect.CURSOR_CREATING
]);