See Release Notes
Long Term Support Release
Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401] [Versions 400 and 401]
1 <?php 2 /* 3 * Copyright 2015-present MongoDB, Inc. 4 * 5 * Licensed under the Apache License, Version 2.0 (the "License"); 6 * you may not use this file except in compliance with the License. 7 * You may obtain a copy of the License at 8 * 9 * https://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18 namespace MongoDB\Operation; 19 20 use MongoDB\Driver\Cursor; 21 use MongoDB\Driver\Exception\RuntimeException as DriverRuntimeException; 22 use MongoDB\Driver\Query; 23 use MongoDB\Driver\ReadConcern; 24 use MongoDB\Driver\ReadPreference; 25 use MongoDB\Driver\Server; 26 use MongoDB\Driver\Session; 27 use MongoDB\Exception\InvalidArgumentException; 28 use MongoDB\Exception\UnsupportedException; 29 30 use function is_array; 31 use function is_bool; 32 use function is_integer; 33 use function is_object; 34 use function is_string; 35 use function trigger_error; 36 37 use const E_USER_DEPRECATED; 38 39 /** 40 * Operation for the find command. 41 * 42 * @api 43 * @see \MongoDB\Collection::find() 44 * @see https://mongodb.com/docs/manual/tutorial/query-documents/ 45 * @see https://mongodb.com/docs/manual/reference/operator/query-modifier/ 46 */ 47 class Find implements Executable, Explainable 48 { 49 public const NON_TAILABLE = 1; 50 public const TAILABLE = 2; 51 public const TAILABLE_AWAIT = 3; 52 53 /** @var string */ 54 private $databaseName; 55 56 /** @var string */ 57 private $collectionName; 58 59 /** @var array|object */ 60 private $filter; 61 62 /** @var array */ 63 private $options; 64 65 /** 66 * Constructs a find command. 67 * 68 * Supported options: 69 * 70 * * allowDiskUse (boolean): Enables writing to temporary files. When set 71 * to true, queries can write data to the _tmp sub-directory in the 72 * dbPath directory. 73 * 74 * * allowPartialResults (boolean): Get partial results from a mongos if 75 * some shards are inaccessible (instead of throwing an error). 76 * 77 * * batchSize (integer): The number of documents to return per batch. 78 * 79 * * collation (document): Collation specification. 80 * 81 * * comment (mixed): BSON value to attach as a comment to this command. 82 * 83 * Only string values are supported for server versions < 4.4. 84 * 85 * * cursorType (enum): Indicates the type of cursor to use. Must be either 86 * NON_TAILABLE, TAILABLE, or TAILABLE_AWAIT. The default is 87 * NON_TAILABLE. 88 * 89 * * hint (string|document): The index to use. Specify either the index 90 * name as a string or the index key pattern as a document. If specified, 91 * then the query system will only consider plans using the hinted index. 92 * 93 * * limit (integer): The maximum number of documents to return. 94 * 95 * * max (document): The exclusive upper bound for a specific index. 96 * 97 * * maxAwaitTimeMS (integer): The maxium amount of time for the server to wait 98 * on new documents to satisfy a query, if cursorType is TAILABLE_AWAIT. 99 * 100 * * maxScan (integer): Maximum number of documents or index keys to scan 101 * when executing the query. 102 * 103 * This option has been deprecated since version 1.4. 104 * 105 * * maxTimeMS (integer): The maximum amount of time to allow the query to 106 * run. If "$maxTimeMS" also exists in the modifiers document, this 107 * option will take precedence. 108 * 109 * * min (document): The inclusive upper bound for a specific index. 110 * 111 * * modifiers (document): Meta operators that modify the output or 112 * behavior of a query. Use of these operators is deprecated in favor of 113 * named options. 114 * 115 * * noCursorTimeout (boolean): The server normally times out idle cursors 116 * after an inactivity period (10 minutes) to prevent excess memory use. 117 * Set this option to prevent that. 118 * 119 * * oplogReplay (boolean): Internal replication use only. The driver 120 * should not set this. This option is deprecated as of MongoDB 4.4. 121 * 122 * * projection (document): Limits the fields to return for the matching 123 * document. 124 * 125 * * readConcern (MongoDB\Driver\ReadConcern): Read concern. 126 * 127 * * readPreference (MongoDB\Driver\ReadPreference): Read preference. 128 * 129 * * returnKey (boolean): If true, returns only the index keys in the 130 * resulting documents. 131 * 132 * * session (MongoDB\Driver\Session): Client session. 133 * 134 * * showRecordId (boolean): Determines whether to return the record 135 * identifier for each document. If true, adds a field $recordId to the 136 * returned documents. 137 * 138 * * skip (integer): The number of documents to skip before returning. 139 * 140 * * snapshot (boolean): Prevents the cursor from returning a document more 141 * than once because of an intervening write operation. 142 * 143 * This options has been deprecated since version 1.4. 144 * 145 * * sort (document): The order in which to return matching documents. If 146 * "$orderby" also exists in the modifiers document, this option will 147 * take precedence. 148 * 149 * * let (document): Map of parameter names and values. Values must be 150 * constant or closed expressions that do not reference document fields. 151 * Parameters can then be accessed as variables in an aggregate 152 * expression context (e.g. "$$var"). 153 * 154 * * typeMap (array): Type map for BSON deserialization. This will be 155 * applied to the returned Cursor (it is not sent to the server). 156 * 157 * @param string $databaseName Database name 158 * @param string $collectionName Collection name 159 * @param array|object $filter Query by which to filter documents 160 * @param array $options Command options 161 * @throws InvalidArgumentException for parameter/option parsing errors 162 */ 163 public function __construct(string $databaseName, string $collectionName, $filter, array $options = []) 164 { 165 if (! is_array($filter) && ! is_object($filter)) { 166 throw InvalidArgumentException::invalidType('$filter', $filter, 'array or object'); 167 } 168 169 if (isset($options['allowDiskUse']) && ! is_bool($options['allowDiskUse'])) { 170 throw InvalidArgumentException::invalidType('"allowDiskUse" option', $options['allowDiskUse'], 'boolean'); 171 } 172 173 if (isset($options['allowPartialResults']) && ! is_bool($options['allowPartialResults'])) { 174 throw InvalidArgumentException::invalidType('"allowPartialResults" option', $options['allowPartialResults'], 'boolean'); 175 } 176 177 if (isset($options['batchSize']) && ! is_integer($options['batchSize'])) { 178 throw InvalidArgumentException::invalidType('"batchSize" option', $options['batchSize'], 'integer'); 179 } 180 181 if (isset($options['collation']) && ! is_array($options['collation']) && ! is_object($options['collation'])) { 182 throw InvalidArgumentException::invalidType('"collation" option', $options['collation'], 'array or object'); 183 } 184 185 if (isset($options['cursorType'])) { 186 if (! is_integer($options['cursorType'])) { 187 throw InvalidArgumentException::invalidType('"cursorType" option', $options['cursorType'], 'integer'); 188 } 189 190 if ( 191 $options['cursorType'] !== self::NON_TAILABLE && 192 $options['cursorType'] !== self::TAILABLE && 193 $options['cursorType'] !== self::TAILABLE_AWAIT 194 ) { 195 throw new InvalidArgumentException('Invalid value for "cursorType" option: ' . $options['cursorType']); 196 } 197 } 198 199 if (isset($options['hint']) && ! is_string($options['hint']) && ! is_array($options['hint']) && ! is_object($options['hint'])) { 200 throw InvalidArgumentException::invalidType('"hint" option', $options['hint'], 'string or array or object'); 201 } 202 203 if (isset($options['limit']) && ! is_integer($options['limit'])) { 204 throw InvalidArgumentException::invalidType('"limit" option', $options['limit'], 'integer'); 205 } 206 207 if (isset($options['max']) && ! is_array($options['max']) && ! is_object($options['max'])) { 208 throw InvalidArgumentException::invalidType('"max" option', $options['max'], 'array or object'); 209 } 210 211 if (isset($options['maxAwaitTimeMS']) && ! is_integer($options['maxAwaitTimeMS'])) { 212 throw InvalidArgumentException::invalidType('"maxAwaitTimeMS" option', $options['maxAwaitTimeMS'], 'integer'); 213 } 214 215 if (isset($options['maxScan']) && ! is_integer($options['maxScan'])) { 216 throw InvalidArgumentException::invalidType('"maxScan" option', $options['maxScan'], 'integer'); 217 } 218 219 if (isset($options['maxTimeMS']) && ! is_integer($options['maxTimeMS'])) { 220 throw InvalidArgumentException::invalidType('"maxTimeMS" option', $options['maxTimeMS'], 'integer'); 221 } 222 223 if (isset($options['min']) && ! is_array($options['min']) && ! is_object($options['min'])) { 224 throw InvalidArgumentException::invalidType('"min" option', $options['min'], 'array or object'); 225 } 226 227 if (isset($options['modifiers']) && ! is_array($options['modifiers']) && ! is_object($options['modifiers'])) { 228 throw InvalidArgumentException::invalidType('"modifiers" option', $options['modifiers'], 'array or object'); 229 } 230 231 if (isset($options['noCursorTimeout']) && ! is_bool($options['noCursorTimeout'])) { 232 throw InvalidArgumentException::invalidType('"noCursorTimeout" option', $options['noCursorTimeout'], 'boolean'); 233 } 234 235 if (isset($options['oplogReplay']) && ! is_bool($options['oplogReplay'])) { 236 throw InvalidArgumentException::invalidType('"oplogReplay" option', $options['oplogReplay'], 'boolean'); 237 } 238 239 if (isset($options['projection']) && ! is_array($options['projection']) && ! is_object($options['projection'])) { 240 throw InvalidArgumentException::invalidType('"projection" option', $options['projection'], 'array or object'); 241 } 242 243 if (isset($options['readConcern']) && ! $options['readConcern'] instanceof ReadConcern) { 244 throw InvalidArgumentException::invalidType('"readConcern" option', $options['readConcern'], ReadConcern::class); 245 } 246 247 if (isset($options['readPreference']) && ! $options['readPreference'] instanceof ReadPreference) { 248 throw InvalidArgumentException::invalidType('"readPreference" option', $options['readPreference'], ReadPreference::class); 249 } 250 251 if (isset($options['returnKey']) && ! is_bool($options['returnKey'])) { 252 throw InvalidArgumentException::invalidType('"returnKey" option', $options['returnKey'], 'boolean'); 253 } 254 255 if (isset($options['session']) && ! $options['session'] instanceof Session) { 256 throw InvalidArgumentException::invalidType('"session" option', $options['session'], Session::class); 257 } 258 259 if (isset($options['showRecordId']) && ! is_bool($options['showRecordId'])) { 260 throw InvalidArgumentException::invalidType('"showRecordId" option', $options['showRecordId'], 'boolean'); 261 } 262 263 if (isset($options['skip']) && ! is_integer($options['skip'])) { 264 throw InvalidArgumentException::invalidType('"skip" option', $options['skip'], 'integer'); 265 } 266 267 if (isset($options['snapshot']) && ! is_bool($options['snapshot'])) { 268 throw InvalidArgumentException::invalidType('"snapshot" option', $options['snapshot'], 'boolean'); 269 } 270 271 if (isset($options['sort']) && ! is_array($options['sort']) && ! is_object($options['sort'])) { 272 throw InvalidArgumentException::invalidType('"sort" option', $options['sort'], 'array or object'); 273 } 274 275 if (isset($options['typeMap']) && ! is_array($options['typeMap'])) { 276 throw InvalidArgumentException::invalidType('"typeMap" option', $options['typeMap'], 'array'); 277 } 278 279 if (isset($options['let']) && ! is_array($options['let']) && ! is_object($options['let'])) { 280 throw InvalidArgumentException::invalidType('"let" option', $options['let'], 'array or object'); 281 } 282 283 if (isset($options['readConcern']) && $options['readConcern']->isDefault()) { 284 unset($options['readConcern']); 285 } 286 287 if (isset($options['snapshot'])) { 288 trigger_error('The "snapshot" option is deprecated and will be removed in a future release', E_USER_DEPRECATED); 289 } 290 291 if (isset($options['maxScan'])) { 292 trigger_error('The "maxScan" option is deprecated and will be removed in a future release', E_USER_DEPRECATED); 293 } 294 295 $this->databaseName = $databaseName; 296 $this->collectionName = $collectionName; 297 $this->filter = $filter; 298 $this->options = $options; 299 } 300 301 /** 302 * Execute the operation. 303 * 304 * @see Executable::execute() 305 * @return Cursor 306 * @throws UnsupportedException if read concern is used and unsupported 307 * @throws DriverRuntimeException for other driver errors (e.g. connection errors) 308 */ 309 public function execute(Server $server) 310 { 311 $inTransaction = isset($this->options['session']) && $this->options['session']->isInTransaction(); 312 if ($inTransaction && isset($this->options['readConcern'])) { 313 throw UnsupportedException::readConcernNotSupportedInTransaction(); 314 } 315 316 $cursor = $server->executeQuery($this->databaseName . '.' . $this->collectionName, new Query($this->filter, $this->createQueryOptions()), $this->createExecuteOptions()); 317 318 if (isset($this->options['typeMap'])) { 319 $cursor->setTypeMap($this->options['typeMap']); 320 } 321 322 return $cursor; 323 } 324 325 /** 326 * Returns the command document for this operation. 327 * 328 * @see Explainable::getCommandDocument() 329 * @return array 330 */ 331 public function getCommandDocument(Server $server) 332 { 333 return $this->createCommandDocument(); 334 } 335 336 /** 337 * Construct a command document for Find 338 */ 339 private function createCommandDocument(): array 340 { 341 $cmd = ['find' => $this->collectionName, 'filter' => (object) $this->filter]; 342 343 $options = $this->createQueryOptions(); 344 345 if (empty($options)) { 346 return $cmd; 347 } 348 349 // maxAwaitTimeMS is a Query level option so should not be considered here 350 unset($options['maxAwaitTimeMS']); 351 352 $modifierFallback = [ 353 ['allowPartialResults', 'partial'], 354 ['comment', '$comment'], 355 ['hint', '$hint'], 356 ['maxScan', '$maxScan'], 357 ['max', '$max'], 358 ['maxTimeMS', '$maxTimeMS'], 359 ['min', '$min'], 360 ['returnKey', '$returnKey'], 361 ['showRecordId', '$showDiskLoc'], 362 ['sort', '$orderby'], 363 ['snapshot', '$snapshot'], 364 ]; 365 366 foreach ($modifierFallback as $modifier) { 367 if (! isset($options[$modifier[0]]) && isset($options['modifiers'][$modifier[1]])) { 368 $options[$modifier[0]] = $options['modifiers'][$modifier[1]]; 369 } 370 } 371 372 unset($options['modifiers']); 373 374 return $cmd + $options; 375 } 376 377 /** 378 * Create options for executing the command. 379 * 380 * @see https://php.net/manual/en/mongodb-driver-server.executequery.php 381 */ 382 private function createExecuteOptions(): array 383 { 384 $options = []; 385 386 if (isset($this->options['readPreference'])) { 387 $options['readPreference'] = $this->options['readPreference']; 388 } 389 390 if (isset($this->options['session'])) { 391 $options['session'] = $this->options['session']; 392 } 393 394 return $options; 395 } 396 397 /** 398 * Create options for the find query. 399 * 400 * Note that these are separate from the options for executing the command, 401 * which are created in createExecuteOptions(). 402 */ 403 private function createQueryOptions(): array 404 { 405 $options = []; 406 407 if (isset($this->options['cursorType'])) { 408 if ($this->options['cursorType'] === self::TAILABLE) { 409 $options['tailable'] = true; 410 } 411 412 if ($this->options['cursorType'] === self::TAILABLE_AWAIT) { 413 $options['tailable'] = true; 414 $options['awaitData'] = true; 415 } 416 } 417 418 foreach (['allowDiskUse', 'allowPartialResults', 'batchSize', 'comment', 'hint', 'limit', 'maxAwaitTimeMS', 'maxScan', 'maxTimeMS', 'noCursorTimeout', 'oplogReplay', 'projection', 'readConcern', 'returnKey', 'showRecordId', 'skip', 'snapshot', 'sort'] as $option) { 419 if (isset($this->options[$option])) { 420 $options[$option] = $this->options[$option]; 421 } 422 } 423 424 foreach (['collation', 'let', 'max', 'min'] as $option) { 425 if (isset($this->options[$option])) { 426 $options[$option] = (object) $this->options[$option]; 427 } 428 } 429 430 $modifiers = empty($this->options['modifiers']) ? [] : (array) $this->options['modifiers']; 431 432 if (! empty($modifiers)) { 433 $options['modifiers'] = $modifiers; 434 } 435 436 return $options; 437 } 438 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body