diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index bfdf3c5b..00000000 --- a/.gitmodules +++ /dev/null @@ -1,4 +0,0 @@ -[submodule "mongo-php-library"] - path = mongo-php-library - url = https://github.com/mongodb/mongo-php-library.git - branch = v1.17 diff --git a/mongo-php-library b/mongo-php-library deleted file mode 160000 index 528d2d1e..00000000 --- a/mongo-php-library +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 528d2d1ec3d8995f8c7c635f7e76731632556832 diff --git a/source/.static/.mongodb b/source/.static/.mongodb new file mode 100644 index 00000000..e69de29b diff --git a/source/examples/codecs/handling-data-types/DateTimeCodec.php b/source/examples/codecs/handling-data-types/DateTimeCodec.php new file mode 100644 index 00000000..31aba37e --- /dev/null +++ b/source/examples/codecs/handling-data-types/DateTimeCodec.php @@ -0,0 +1,60 @@ + */ +final class DateTimeCodec implements Codec +{ + use DecodeIfSupported; + use EncodeIfSupported; + + public function canDecode(mixed $value): bool + { + /* This codec inspects the BSON document to ensure it has the fields it expects, and that those fields are of + * the correct type. This is a robust approach to avoid decoding document that are not supported and would cause + * exceptions. + * + * For large documents, this can be inefficient as we're inspecting the entire document four times (once for + * each call to has() and get()). For small documents, this is not a problem. + */ + return $value instanceof Document + && $value->has('utc') && $value->get('utc') instanceof UTCDateTime + && $value->has('tz') && is_string($value->get('tz')); + } + + public function canEncode(mixed $value): bool + { + return $value instanceof DateTimeInterface; + } + + public function decode(mixed $value): DateTimeImmutable + { + if (! $this->canDecode($value)) { + throw UnsupportedValueException::invalidDecodableValue($value); + } + + $timeZone = new DateTimeZone($value->get('tz')); + $dateTime = $value->get('utc') + ->toDateTime() + ->setTimeZone($timeZone); + + return DateTimeImmutable::createFromMutable($dateTime); + } + + public function encode(mixed $value): Document + { + if (! $this->canEncode($value)) { + throw UnsupportedValueException::invalidEncodableValue($value); + } + + return Document::fromPHP([ + 'utc' => new UTCDateTime($value), + 'tz' => $value->getTimezone()->getName(), + ]); + } +} diff --git a/source/examples/codecs/handling-data-types/Person.php b/source/examples/codecs/handling-data-types/Person.php new file mode 100644 index 00000000..4f1307d9 --- /dev/null +++ b/source/examples/codecs/handling-data-types/Person.php @@ -0,0 +1,13 @@ + */ +final class PersonCodec implements DocumentCodec +{ + use DecodeIfSupported; + use EncodeIfSupported; + + public function __construct( + private readonly DateTimeCodec $dateTimeCodec = new DateTimeCodec(), + ) { + } + + public function canDecode(mixed $value): bool + { + return $value instanceof Document && $value->has('name'); + } + + public function canEncode(mixed $value): bool + { + return $value instanceof Person; + } + + public function decode(mixed $value): Person + { + if (! $this->canDecode($value)) { + throw UnsupportedValueException::invalidDecodableValue($value); + } + + return new Person( + $value->get('name'), + $this->dateTimeCodec->decode($value->get('createdAt')), + $value->get('_id'), + ); + } + + public function encode(mixed $value): Document + { + if (! $this->canEncode($value)) { + throw UnsupportedValueException::invalidEncodableValue($value); + } + + return Document::fromPHP([ + '_id' => $value->id, + 'name' => $value->name, + 'createdAt' => $this->dateTimeCodec->encode($value->createdAt), + ]); + } +} diff --git a/source/examples/codecs/handling-documents/Person.php b/source/examples/codecs/handling-documents/Person.php new file mode 100644 index 00000000..d3c9b4bf --- /dev/null +++ b/source/examples/codecs/handling-documents/Person.php @@ -0,0 +1,12 @@ + */ +final class PersonCodec implements DocumentCodec +{ + // These traits define commonly used functionality to avoid duplication + use DecodeIfSupported; + use EncodeIfSupported; + + public function canDecode(mixed $value): bool + { + return $value instanceof Document && $value->has('name'); + } + + public function canEncode(mixed $value): bool + { + return $value instanceof Person; + } + + public function decode(mixed $value): Person + { + if (! $this->canDecode($value)) { + throw UnsupportedValueException::invalidDecodableValue($value); + } + + return new Person( + $value->get('name'), + $value->get('_id'), + ); + } + + public function encode(mixed $value): Document + { + if (! $this->canEncode($value)) { + throw UnsupportedValueException::invalidEncodableValue($value); + } + + return Document::fromPHP([ + '_id' => $value->id, + 'name' => $value->name, + ]); + } +} diff --git a/source/examples/codecs/handling-documents/disabling-codec.php b/source/examples/codecs/handling-documents/disabling-codec.php new file mode 100644 index 00000000..c3769fd7 --- /dev/null +++ b/source/examples/codecs/handling-documents/disabling-codec.php @@ -0,0 +1,7 @@ +aggregate($pipeline, ['codec' => null]); + +// Overrides the collection codec, using the specified type map +$collection->findOne($filter, ['typeMap' => ['root' => 'stdClass']]); diff --git a/source/examples/codecs/handling-documents/using-codec.php b/source/examples/codecs/handling-documents/using-codec.php new file mode 100644 index 00000000..4d05ac29 --- /dev/null +++ b/source/examples/codecs/handling-documents/using-codec.php @@ -0,0 +1,13 @@ +selectCollection('test', 'person', [ + 'codec' => new PersonCodec(), +]); + +$person = new Person('Jane Doe'); +$collection->insertOne($person); + +$person = $collection->findOne(); diff --git a/source/examples/codecs/handling-embedded-documents/Address.php b/source/examples/codecs/handling-embedded-documents/Address.php new file mode 100644 index 00000000..b9b67838 --- /dev/null +++ b/source/examples/codecs/handling-embedded-documents/Address.php @@ -0,0 +1,12 @@ + */ +final class AddressCodec implements DocumentCodec +{ + use DecodeIfSupported; + use EncodeIfSupported; + + public function canDecode(mixed $value): bool + { + return $value instanceof Document + && $value->has('street') + && $value->has('postCode') + && $value->has('city') + && $value->has('country'); + } + + public function canEncode(mixed $value): bool + { + return $value instanceof Address; + } + + public function decode(mixed $value): Address + { + if (! $this->canDecode($value)) { + throw UnsupportedValueException::invalidDecodableValue($value); + } + + return new Address( + $value->get('street'), + $value->get('postCode'), + $value->get('city'), + $value->get('country'), + ); + } + + public function encode(mixed $value): Document + { + if (! $this->canEncode($value)) { + throw UnsupportedValueException::invalidEncodableValue($value); + } + + return Document::fromPHP([ + 'street' => $value->street, + 'postCode' => $value->postCode, + 'city' => $value->city, + 'country' => $value->country, + ]); + } +} diff --git a/source/examples/codecs/handling-embedded-documents/Person.php b/source/examples/codecs/handling-embedded-documents/Person.php new file mode 100644 index 00000000..a2440d54 --- /dev/null +++ b/source/examples/codecs/handling-embedded-documents/Person.php @@ -0,0 +1,14 @@ + */ +final class PersonCodec implements DocumentCodec +{ + use DecodeIfSupported; + use EncodeIfSupported; + + public function __construct( + private readonly AddressCodec $addressCodec = new AddressCodec(), + ) { + } + + public function canDecode(mixed $value): bool + { + return $value instanceof Document && $value->has('name'); + } + + public function canEncode(mixed $value): bool + { + return $value instanceof Person; + } + + public function decode(mixed $value): Person + { + if (! $this->canDecode($value)) { + throw UnsupportedValueException::invalidDecodableValue($value); + } + + $person = new Person( + $value->get('name'), + $value->get('_id'), + ); + + // Address is optional, so only decode if it exists + if ($value->has('address')) { + $person->address = $this->addressCodec->decode($value->get('address')); + } + + return $person; + } + + public function encode(mixed $value): Document + { + if (! $this->canEncode($value)) { + throw UnsupportedValueException::invalidEncodableValue($value); + } + + $data = [ + '_id' => $value->id, + 'name' => $value->name, + ]; + + // Don't add a null value to the document if address is not set + if ($value->address) { + $data['address'] = $this->addressCodec->encode($value->address); + } + + return Document::fromPHP($data); + } +} diff --git a/source/examples/encryption/create_data_key.php b/source/examples/encryption/create_data_key.php new file mode 100644 index 00000000..9dd27d72 --- /dev/null +++ b/source/examples/encryption/create_data_key.php @@ -0,0 +1,46 @@ +selectCollection('encryption', '__keyVault')->drop(); +$client->selectCollection('encryption', '__keyVault')->createIndex(['keyAltNames' => 1], [ + 'unique' => true, + 'partialFilterExpression' => ['keyAltNames' => ['$exists' => true]], +]); + +// Create a ClientEncryption object to manage data encryption keys +$clientEncryption = $client->createClientEncryption([ + 'keyVaultNamespace' => 'encryption.__keyVault', + 'kmsProviders' => [ + 'local' => ['key' => $localKey], + ], +]); + +/* Create a data encryption key. To store the key ID for later use, you can use + * serialize(), var_export(), etc. */ +$keyId = $clientEncryption->createDataKey('local'); + +print_r($keyId); + +// Encrypt a value using the key that was just created +$encryptedValue = $clientEncryption->encrypt('mySecret', [ + 'algorithm' => ClientEncryption::AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC, + 'keyId' => $keyId, +]); + +print_r($encryptedValue); diff --git a/source/examples/encryption/csfle-automatic_encryption-local_schema.php b/source/examples/encryption/csfle-automatic_encryption-local_schema.php new file mode 100644 index 00000000..42557447 --- /dev/null +++ b/source/examples/encryption/csfle-automatic_encryption-local_schema.php @@ -0,0 +1,87 @@ +createClientEncryption([ + 'keyVaultNamespace' => 'encryption.__keyVault', + 'kmsProviders' => [ + 'local' => ['key' => $localKey], + ], +]); + +/* Create a data encryption key. Alternatively, this key ID could be read from a + * configuration file. */ +$keyId = $clientEncryption->createDataKey('local'); + +/* Define a JSON schema for the encrypted collection. Since this only utilizes + * encryption schema syntax, it can be used for both the server-side and local + * schema. */ +$schema = [ + 'bsonType' => 'object', + 'properties' => [ + 'encryptedField' => [ + 'encrypt' => [ + 'keyId' => [$keyId], + 'bsonType' => 'string', + 'algorithm' => ClientEncryption::AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC, + ], + ], + ], +]; + +/* Create another client with automatic encryption enabled. Configure a local + * schema for the encrypted collection using the "schemaMap" option. */ +$encryptedClient = new Client($uri, [], [ + 'autoEncryption' => [ + 'keyVaultNamespace' => 'encryption.__keyVault', + 'kmsProviders' => ['local' => ['key' => $localKey]], + 'schemaMap' => ['test.coll' => $schema], + ], +]); + +/* Create a new collection for this script. Configure a server-side schema by + * explicitly creating the collection with a "validator" option. + * + * Note: without a server-side schema, another client could potentially insert + * unencrypted data into the collection. Therefore, a local schema should always + * be used in conjunction with a server-side schema. */ +$encryptedClient->selectDatabase('test')->createCollection('coll', ['validator' => ['$jsonSchema' => $schema]]); +$encryptedCollection = $encryptedClient->selectCollection('test', 'coll'); + +/* Using the encrypted client, insert and find a document to demonstrate that + * the encrypted field is automatically encrypted and decrypted. */ +$encryptedCollection->insertOne(['_id' => 1, 'encryptedField' => 'mySecret']); + +print_r($encryptedCollection->findOne(['_id' => 1])); + +/* Using the client configured without encryption, find the same document and + * observe that the field is not automatically decrypted. */ +$unencryptedCollection = $client->selectCollection('test', 'coll'); + +print_r($unencryptedCollection->findOne(['_id' => 1])); + +/* Attempt to insert another document with an unencrypted field value to + * demonstrate that the server-side schema is enforced. */ +try { + $unencryptedCollection->insertOne(['_id' => 2, 'encryptedField' => 'myOtherSecret']); +} catch (ServerException $e) { + printf("Error inserting document: %s\n", $e->getMessage()); +} diff --git a/source/examples/encryption/csfle-automatic_encryption-server_side_schema.php b/source/examples/encryption/csfle-automatic_encryption-server_side_schema.php new file mode 100644 index 00000000..44531522 --- /dev/null +++ b/source/examples/encryption/csfle-automatic_encryption-server_side_schema.php @@ -0,0 +1,79 @@ +createClientEncryption([ + 'keyVaultNamespace' => 'encryption.__keyVault', + 'kmsProviders' => [ + 'local' => ['key' => $localKey], + ], +]); + +/* Create a data encryption key. Alternatively, this key ID could be read from a + * configuration file. */ +$keyId = $clientEncryption->createDataKey('local'); + +// Create another client with automatic encryption enabled +$encryptedClient = new Client($uri, [], [ + 'autoEncryption' => [ + 'keyVaultNamespace' => 'encryption.__keyVault', + 'kmsProviders' => ['local' => ['key' => $localKey]], + ], +]); + +// Define a JSON schema for the encrypted collection +$schema = [ + 'bsonType' => 'object', + 'properties' => [ + 'encryptedField' => [ + 'encrypt' => [ + 'keyId' => [$keyId], + 'bsonType' => 'string', + 'algorithm' => ClientEncryption::AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC, + ], + ], + ], +]; + +/* Create a new collection for this script. Configure a server-side schema by + * explicitly creating the collection with a "validator" option. */ +$encryptedClient->selectDatabase('test')->createCollection('coll', ['validator' => ['$jsonSchema' => $schema]]); +$encryptedCollection = $encryptedClient->selectCollection('test', 'coll'); + +/* Using the encrypted client, insert and find a document to demonstrate that + * the encrypted field is automatically encrypted and decrypted. */ +$encryptedCollection->insertOne(['_id' => 1, 'encryptedField' => 'mySecret']); + +print_r($encryptedCollection->findOne(['_id' => 1])); + +/* Using the client configured without encryption, find the same document and + * observe that the field is not automatically decrypted. */ +$unencryptedCollection = $client->selectCollection('test', 'coll'); + +print_r($unencryptedCollection->findOne(['_id' => 1])); + +/* Attempt to insert another document with an unencrypted field value to + * demonstrate that the server-side schema is enforced. */ +try { + $unencryptedCollection->insertOne(['_id' => 2, 'encryptedField' => 'myOtherSecret']); +} catch (ServerException $e) { + printf("Error inserting document: %s\n", $e->getMessage()); +} diff --git a/source/examples/encryption/csfle-explicit_encryption.php b/source/examples/encryption/csfle-explicit_encryption.php new file mode 100644 index 00000000..d36b4b32 --- /dev/null +++ b/source/examples/encryption/csfle-explicit_encryption.php @@ -0,0 +1,51 @@ +createClientEncryption([ + 'keyVaultNamespace' => 'encryption.__keyVault', + 'kmsProviders' => [ + 'local' => ['key' => $localKey], + ], +]); + +/* Create a data encryption key. Alternatively, this key ID could be read from a + * configuration file. */ +$keyId = $clientEncryption->createDataKey('local'); + +// Insert a document with a manually encrypted field +$encryptedValue = $clientEncryption->encrypt('mySecret', [ + 'algorithm' => ClientEncryption::AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC, + 'keyId' => $keyId, +]); + +$collection = $client->selectCollection('test', 'coll'); +$collection->insertOne(['_id' => 1, 'encryptedField' => $encryptedValue]); + +/* Using the client configured without encryption, find the document and observe + * that the field is not automatically decrypted. */ + +/** @var object{encryptedField: Binary} $document */ +$document = $collection->findOne(); + +print_r($document); + +// Manually decrypt the field +printf("Decrypted: %s\n", $clientEncryption->decrypt($document->encryptedField)); diff --git a/source/examples/encryption/csfle-explicit_encryption_automatic_decryption.php b/source/examples/encryption/csfle-explicit_encryption_automatic_decryption.php new file mode 100644 index 00000000..072b273a --- /dev/null +++ b/source/examples/encryption/csfle-explicit_encryption_automatic_decryption.php @@ -0,0 +1,52 @@ + [ + 'keyVaultNamespace' => 'encryption.__keyVault', + 'kmsProviders' => ['local' => ['key' => $localKey]], + 'bypassAutoEncryption' => true, + ], +]); + +// Create a ClientEncryption object to manage data encryption keys +$clientEncryption = $client->createClientEncryption([ + 'keyVaultNamespace' => 'encryption.__keyVault', + 'kmsProviders' => [ + 'local' => ['key' => $localKey], + ], +]); + +/* Create a data encryption key. Alternatively, this key ID could be read from a + * configuration file. */ +$keyId = $clientEncryption->createDataKey('local'); + +// Insert a document with a manually encrypted field +$encryptedValue = $clientEncryption->encrypt('mySecret', [ + 'algorithm' => ClientEncryption::AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC, + 'keyId' => $keyId, +]); + +$collection = $client->selectCollection('test', 'coll'); +$collection->insertOne(['_id' => 1, 'encryptedField' => $encryptedValue]); + +/* Using the client configured with encryption (but not automatic encryption), + * find the document and observe that the field is automatically decrypted. */ +$document = $collection->findOne(); + +print_r($document); diff --git a/source/examples/encryption/key_alt_name.php b/source/examples/encryption/key_alt_name.php new file mode 100644 index 00000000..03100aaf --- /dev/null +++ b/source/examples/encryption/key_alt_name.php @@ -0,0 +1,52 @@ +selectCollection('encryption', '__keyVault')->drop(); +$client->selectCollection('encryption', '__keyVault')->createIndex(['keyAltNames' => 1], [ + 'unique' => true, + 'partialFilterExpression' => ['keyAltNames' => ['$exists' => true]], +]); + +// Create a ClientEncryption object to manage data encryption keys +$clientEncryption = $client->createClientEncryption([ + 'keyVaultNamespace' => 'encryption.__keyVault', + 'kmsProviders' => [ + 'local' => ['key' => $localKey], + ], +]); + +// Create a data encryption key with an alternate name +$clientEncryption->createDataKey('local', ['keyAltNames' => ['myDataKey']]); + +/* Attempt to create a second key with the same name to demonstrate that the + * unique index is enforced. */ +try { + $clientEncryption->createDataKey('local', ['keyAltNames' => ['myDataKey']]); +} catch (ServerException $e) { + printf("Error creating key: %s\n", $e->getMessage()); +} + +// Encrypt a value, using the "keyAltName" option instead of "keyId" +$encryptedValue = $clientEncryption->encrypt('mySecret', [ + 'algorithm' => ClientEncryption::AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC, + 'keyAltName' => 'myDataKey', +]); + +print_r($encryptedValue); diff --git a/source/examples/encryption/queryable_encryption-automatic.php b/source/examples/encryption/queryable_encryption-automatic.php new file mode 100644 index 00000000..024afe95 --- /dev/null +++ b/source/examples/encryption/queryable_encryption-automatic.php @@ -0,0 +1,79 @@ +createClientEncryption([ + 'keyVaultNamespace' => 'encryption.__keyVault', + 'kmsProviders' => ['local' => ['key' => $localKey]], +]); + +/* Create the data encryption keys for this script. Alternatively, the key IDs + * could be read from a configuration file. */ +$keyId1 = $clientEncryption->createDataKey('local'); +$keyId2 = $clientEncryption->createDataKey('local'); + +/* Create another client with automatic encryption enabled. Configure the + * encrypted collection using the "encryptedFields" option. */ +$encryptedClient = new Client($uri, [], [ + 'autoEncryption' => [ + 'keyVaultNamespace' => 'encryption.__keyVault', + 'kmsProviders' => ['local' => ['key' => $localKey]], + 'encryptedFieldsMap' => [ + 'test.coll' => [ + 'fields' => [ + [ + 'path' => 'encryptedIndexed', + 'bsonType' => 'string', + 'keyId' => $keyId1, + 'queries' => ['queryType' => ClientEncryption::QUERY_TYPE_EQUALITY], + ], + [ + 'path' => 'encryptedUnindexed', + 'bsonType' => 'string', + 'keyId' => $keyId2, + ], + ], + ], + ], + ], +]); + +/* Create the data collection for this script. The create and drop helpers will + * infer encryptedFields from the client configuration and manage internal + * encryption collections automatically. Alternatively, the "encryptedFields" + * option can also be passed explicitly. */ +$encryptedClient->selectDatabase('test')->createCollection('coll'); +$encryptedCollection = $encryptedClient->selectCollection('test', 'coll'); + +/* Using the encrypted client, insert a document and find it by querying on the + * encrypted field. Fields will be automatically encrypted and decrypted. */ +$encryptedCollection->insertOne([ + '_id' => 1, + 'encryptedIndexed' => 'indexedValue', + 'encryptedUnindexed' => 'unindexedValue', +]); + +print_r($encryptedCollection->findOne(['encryptedIndexed' => 'indexedValue'])); + +/* Using the client configured without encryption, find the same document and + * observe that fields are not automatically decrypted. */ +$unencryptedCollection = $client->selectCollection('test', 'coll'); + +print_r($unencryptedCollection->findOne(['_id' => 1])); diff --git a/source/examples/encryption/queryable_encryption-explicit.php b/source/examples/encryption/queryable_encryption-explicit.php new file mode 100644 index 00000000..a07d88d1 --- /dev/null +++ b/source/examples/encryption/queryable_encryption-explicit.php @@ -0,0 +1,94 @@ +createClientEncryption([ + 'keyVaultNamespace' => 'encryption.__keyVault', + 'kmsProviders' => ['local' => ['key' => $localKey]], +]); + +/* Create the data encryption keys. Alternatively, the key IDs could be read + * from a configuration file. */ +$keyId1 = $clientEncryption->createDataKey('local'); +$keyId2 = $clientEncryption->createDataKey('local'); + +// Create another client with automatic encryption disabled +$encryptedClient = new Client($uri, [], [ + 'autoEncryption' => [ + 'keyVaultNamespace' => 'encryption.__keyVault', + 'kmsProviders' => ['local' => ['key' => $localKey]], + 'bypassQueryAnalysis' => true, + ], +]); + +// Define encrypted fields for the collection +$encryptedFields = [ + 'fields' => [ + [ + 'path' => 'encryptedIndexed', + 'bsonType' => 'string', + 'keyId' => $keyId1, + 'queries' => ['queryType' => ClientEncryption::QUERY_TYPE_EQUALITY], + ], + [ + 'path' => 'encryptedUnindexed', + 'bsonType' => 'string', + 'keyId' => $keyId2, + ], + ], +]; + +/* Create the data collection for this script. Specify the "encryptedFields" + * option to ensure that internal encryption collections are also created. The + * "encryptedFields" option should also be specified when dropping the + * collection to ensure that internal encryption collections are dropped. */ +$encryptedClient->selectDatabase('test')->createCollection('coll', ['encryptedFields' => $encryptedFields]); +$encryptedCollection = $encryptedClient->selectCollection('test', 'coll'); + +// Insert a document with manually encrypted fields +$indexedInsertPayload = $clientEncryption->encrypt('indexedValue', [ + 'algorithm' => ClientEncryption::ALGORITHM_INDEXED, + 'contentionFactor' => 1, + 'keyId' => $keyId1, +]); + +$unindexedInsertPayload = $clientEncryption->encrypt('unindexedValue', [ + 'algorithm' => ClientEncryption::ALGORITHM_UNINDEXED, + 'keyId' => $keyId2, +]); + +$encryptedCollection->insertOne([ + '_id' => 1, + 'encryptedIndexed' => $indexedInsertPayload, + 'encryptedUnindexed' => $unindexedInsertPayload, +]); + +/* Encrypt the payload for an "equality" query using the same key that was used + * to encrypt the corresponding insert payload. */ +$indexedFindPayload = $clientEncryption->encrypt('indexedValue', [ + 'algorithm' => ClientEncryption::ALGORITHM_INDEXED, + 'queryType' => ClientEncryption::QUERY_TYPE_EQUALITY, + 'contentionFactor' => 1, + 'keyId' => $keyId1, +]); + +/* Using the client configured with encryption (but not automatic encryption), + * find the document and observe that the fields are automatically decrypted. */ +print_r($encryptedCollection->findOne(['encryptedIndexed' => $indexedFindPayload])); diff --git a/source/faq.txt b/source/faq.txt new file mode 100644 index 00000000..101f757f --- /dev/null +++ b/source/faq.txt @@ -0,0 +1,182 @@ +========================== +Frequently Asked Questions +========================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +Common Extension Installation Errors +------------------------------------ + +PHP Headers Not Found +~~~~~~~~~~~~~~~~~~~~~ + +For example: + +.. code-block:: none + + /private/tmp/pear/install/mongodb/php_phongo.c:24:10: fatal error: 'php.h' file not found + + #include + ^~~~~~~ + +This error indicates that PHP's build system cannot find the necessary headers. +All PHP extensions require headers in order to compile. Additionally, those +headers must correspond to the PHP runtime for which the extension will be used. +Generally, the ``phpize`` command (invoked by ``pecl``) will ensure that the +extension builds with the correct headers. + +Note that the mere presence of a PHP runtime does not mean that headers are +available. On various Linux distributions, headers are often published under a +separate ``php-dev`` or ``php-devel`` package. On macOS, the default PHP runtime +does not include headers and users typically need to install PHP (and headers) +via `Homebrew `_ in order to build an extension. + +Multiple PHP Runtimes Installed +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If your system has multiple versions of PHP installed, each version will have +its own ``pecl`` and ``phpize`` commands. Additionally, each PHP runtime may +have separate ``php.ini`` files for each SAPI (e.g. FPM, CLI). If the extension +has been installed but is not available at runtime, double-check that you have +used the correct ``pecl`` command and have modified the appropriate ``php.ini`` +file(s). + +If there is any doubt about the ``php.ini`` file being used by a PHP runtime, +you should examine the output of :php:`phpinfo() ` for that particular +SAPI. Additionally, :php:`php_ini_loaded_file() ` and +:php:`php_ini_scanned_files() ` may be used to determine +exactly which INI files have been loaded by PHP. + +To debug issues with the extension not being loaded, you can use the +``detect-extension`` script provided in the tools directory. You can run this +script from the CLI or include it in a script accessible via your web server. +The tool will point out potential issues and installation instructions for your +system. Assuming you've installed the library through Composer, you can call the +script from the vendor directory: + +.. code-block:: none + + php vendor/mongodb/mongodb/tools/detect-extension.php + +If you want to check configuration for a web server SAPI, include the file in +a script accessible from the web server and open it in your browser. Remember to +wrap the script in ``
`` tags to properly format its output:
+
+.. code-block:: php
+
+   
+ +Loading an Incompatible DLL on Windows +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Windows binaries are available for various combinations of PHP version, +thread safety (TS or NTS), and architecture (x86 or x64). Failure to select the +correct binary will result in an error when attempting to load the extension DLL +at runtime: + +.. code-block:: none + + PHP Warning: PHP Startup: Unable to load dynamic library 'mongodb' + +Ensure that you have downloaded a DLL that corresponds to the following PHP +runtime properties: + +- PHP version (``PHP_VERSION``) +- Thread safety (``PHP_ZTS``) +- Architecture (``PHP_INT_SIZE``) + +In addition to the aforementioned constants, these properties can also be +inferred from :php:`phpinfo() `. If your system has multiple PHP +runtimes installed, double-check that you are examining the ``phpinfo()`` output +for the correct environment. + +The aforementioned ``detect-extension`` script can also be used to determine the +appropriate DLL for your PHP environment. + +Server Selection Failures +------------------------- + +The following are all examples of +:doc:`Server Selection ` failures: + +.. code-block:: none + + No suitable servers found (`serverSelectionTryOnce` set): + [connection refused calling hello on 'a.example.com:27017'] + [connection refused calling hello on 'b.example.com:27017'] + + No suitable servers found: `serverSelectionTimeoutMS` expired: + [socket timeout calling hello on 'example.com:27017'] + + No suitable servers found: `serverSelectionTimeoutMS` expired: + [connection timeout calling hello on 'a.example.com:27017'] + [connection timeout calling hello on 'b.example.com:27017'] + [TLS handshake failed: -9806 calling hello on 'c.example.com:27017'] + + No suitable servers found: `serverselectiontimeoutms` timed out: + [TLS handshake failed: certificate verify failed (64): IP address mismatch calling hello on 'a.example.com:27017'] + [TLS handshake failed: certificate verify failed (64): IP address mismatch calling hello on 'b.example.com:27017'] + +These errors typically manifest as a +:php:`MongoDB\Driver\Exception\ConnectionTimeoutException ` +exception from the extension. The actual exception messages originate from +libmongoc, which is the underlying system library used by the extension. Since +these messages can take many forms, it's helpful to break down the structure of +the message so you can better diagnose errors in your application. + +Messages will typically start with "No suitable servers found". The next part of +the message indicates *how* server selection failed. By default, the extension +avoids a server selection loop and instead makes a single attempt (according to +the ``serverSelectionTryOnce`` connection string option). If the extension is +configured to utilize a loop, a message like "serverSelectionTimeoutMS expired" +will tell us that we exhausted its time limit. + +The last component of the message tells us *why* server selection failed, and +includes one or more errors directly from the topology scanner, which is the +service responsible for connecting to and monitoring each host. Any host that +last experienced an error during monitoring will be included in this list. These +messages typically originate from low-level socket or TLS functions. + +The following is not meant to be exhaustive, but will hopefully point you in the +right direction for analyzing the contributing factor(s) for a server selection +failure: + +- "connection refused" likely indicates that the remote host is not listening on + the expected port. +- "connection timeout" could indicate a routing or firewall issue, or perhaps + a timeout due to latency. +- "socket timeout" suggests that a connection *was* established at some point + but was dropped or otherwise timed out due to latency. +- "TLS handshake failed" suggests something related to TLS or OCSP verification + and is sometimes indicative of misconfigured TLS certificates. + +In the case of a connection failure, you can use the ``connect`` tool to try and +receive more information. This tool attempts to connect to each host in a +connection string using socket functions to see if it is able to establish a +connection, send, and receive data. The tool takes the connection string to a +MongoDB deployment as its only argument. Assuming you've installed the library +through Composer, you would call the script from the vendor directory: + +.. code-block:: none + + php vendor/mongodb/mongodb/tools/connect.php mongodb://127.0.0.1:27017 + +In case the server does not accept connections, the output will look like this: + +.. code-block:: none + + Looking up MongoDB at mongodb://127.0.0.1:27017 + Found 1 host(s) in the URI. Will attempt to connect to each. + + Could not connect to 127.0.0.1:27017: Connection refused + +.. note:: + + The tool only supports the ``mongodb://`` URI schema. Using the + ``mongodb+srv`` scheme is not supported. diff --git a/source/includes/extracts-bucket-option.yaml b/source/includes/extracts-bucket-option.yaml new file mode 100644 index 00000000..a3eb915f --- /dev/null +++ b/source/includes/extracts-bucket-option.yaml @@ -0,0 +1,36 @@ +ref: bucket-option-codec +content: | + The :doc:`codec ` to use for encoding or decoding documents. + This option is mutually exclusive with the ``typeMap`` option. + + Defaults to the bucket's codec. Inheritance for a default ``codec`` option + takes precedence over that of the ``typeMap`` option. +--- +ref: bucket-option-readConcern +source: + ref: common-option-readConcern + file: extracts-common-option.yaml +replacement: + object: bucket +--- +ref: bucket-option-readPreference +source: + ref: common-option-readPreference + file: extracts-common-option.yaml +replacement: + object: bucket +--- +ref: bucket-option-typeMap +source: + ref: common-option-typeMap + file: extracts-common-option.yaml +replacement: + object: bucket +--- +ref: bucket-option-writeConcern +source: + ref: common-option-writeConcern + file: extracts-common-option.yaml +replacement: + object: bucket +... diff --git a/source/includes/extracts-bulkwriteexception.yaml b/source/includes/extracts-bulkwriteexception.yaml new file mode 100644 index 00000000..6276458e --- /dev/null +++ b/source/includes/extracts-bulkwriteexception.yaml @@ -0,0 +1,21 @@ +ref: bulkwriteexception-result +content: | + If a :php:`MongoDB\Driver\Exception\BulkWriteException + ` is thrown, users should call + :php:`getWriteResult() ` and + inspect the returned :php:`MongoDB\Driver\WriteResult + ` object to determine the nature of the error. + + For example, a write operation may have been successfully applied to the + primary server but failed to satisfy the write concern (e.g. replication took + too long). Alternatively, a write operation may have failed outright (e.g. + unique key violation). +--- +ref: bulkwriteexception-ordered +content: | + In the case of a bulk write, the result may indicate multiple successful write + operations and/or errors. If the ``ordered`` option is ``true``, some + operations may have succeeded before the first error was encountered and the + exception thrown. If the ``ordered`` option is ``false``, multiple errors may + have been encountered. +... diff --git a/source/includes/extracts-client-option.yaml b/source/includes/extracts-client-option.yaml new file mode 100644 index 00000000..9b9020bd --- /dev/null +++ b/source/includes/extracts-client-option.yaml @@ -0,0 +1,28 @@ +ref: client-option-readConcern +source: + ref: common-option-readConcern + file: extracts-common-option.yaml +replacement: + object: client +--- +ref: client-option-readPreference +source: + ref: common-option-readPreference + file: extracts-common-option.yaml +replacement: + object: client +--- +ref: client-option-typeMap +source: + ref: common-option-typeMap + file: extracts-common-option.yaml +replacement: + object: client +--- +ref: client-option-writeConcern +source: + ref: common-option-writeConcern + file: extracts-common-option.yaml +replacement: + object: client +... diff --git a/source/includes/extracts-collection-option.yaml b/source/includes/extracts-collection-option.yaml new file mode 100644 index 00000000..ecc82a42 --- /dev/null +++ b/source/includes/extracts-collection-option.yaml @@ -0,0 +1,49 @@ +ref: collection-option-codec +content: | + The :doc:`codec ` to use for encoding or decoding documents. + This option is mutually exclusive with the ``typeMap`` option. + + Defaults to the collection's codec. Inheritance for a default ``codec`` option + takes precedence over that of the ``typeMap`` option. +--- +ref: collection-option-collation +content: | + :manual:`Collation ` allows users to specify + language-specific rules for string comparison, such as rules for lettercase + and accent marks. When specifying collation, the ``locale`` field is + mandatory; all other collation fields are optional. For descriptions of the + fields, see :manual:`Collation Document `. + + If the collation is unspecified but the collection has a default collation, + the operation uses the collation specified for the collection. If no + collation is specified for the collection or for the operation, MongoDB uses + the simple binary comparison used in prior versions for string comparisons. +--- +ref: collection-option-readConcern +source: + ref: common-option-readConcern + file: extracts-common-option.yaml +replacement: + object: collection +--- +ref: collection-option-readPreference +source: + ref: common-option-readPreference + file: extracts-common-option.yaml +replacement: + object: collection +--- +ref: collection-option-typeMap +source: + ref: common-option-typeMap + file: extracts-common-option.yaml +replacement: + object: collection +--- +ref: collection-option-writeConcern +source: + ref: common-option-writeConcern + file: extracts-common-option.yaml +replacement: + object: collection +... diff --git a/source/includes/extracts-common-option.yaml b/source/includes/extracts-common-option.yaml new file mode 100644 index 00000000..39cab355 --- /dev/null +++ b/source/includes/extracts-common-option.yaml @@ -0,0 +1,91 @@ +ref: common-option-codec +content: | + The :doc:`codec ` to use for encoding or decoding documents. + This option is mutually exclusive with the ``typeMap`` option. +--- +ref: common-option-collation +content: | + :manual:`Collation ` allows users to specify + language-specific rules for string comparison, such as rules for lettercase + and accent marks. When specifying collation, the ``locale`` field is + mandatory; all other collation fields are optional. For descriptions of the + fields, see :manual:`Collation Document `. +--- +ref: common-option-comment +content: | + Enables users to specify an arbitrary comment to help trace the operation + through the :manual:`database profiler `, + :manual:`currentOp ` output, and + :manual:`logs `. +--- +ref: common-option-comment-string-before-4.4 +content: | + The comment can be any valid BSON type since MongoDB 4.4. Earlier server + versions only support string values. +--- +ref: common-option-hint +content: | + The index to use. Specify either the index name as a string or the index key + pattern as a document. If specified, then the query system will only consider + plans using the hinted index. +--- +ref: common-option-let +content: | + Map of parameter names and values. Values must be constant or closed + expressions that do not reference document fields. Parameters can then be + accessed as variables in an aggregate expression context (e.g. ``$$var``). + + This is not supported for server versions prior to 5.0 and will result in an + exception at execution time if used. +--- +ref: common-option-maxTimeMS +content: | + The cumulative time limit in milliseconds for processing operations on the + cursor. MongoDB aborts the operation at the earliest following + :term:`interrupt point`. +--- +ref: common-option-readConcern +content: | + :manual:`Read concern ` to use for the operation. + Defaults to the {{object}}'s read concern. +replacement: + object: object +--- +ref: common-option-readConcern-transaction +content: | + It is not possible to specify a read concern for individual operations as part + of a transaction. Instead, set the ``readConcern`` option when + :php:`starting the transaction `. +--- +ref: common-option-readPreference +content: | + :manual:`Read preference ` to use for the + operation. Defaults to the {{object}}'s read preference. +replacement: + object: object +--- +ref: common-option-session +content: | + Client session to associate with the operation. +--- +ref: common-option-typeMap +content: | + The :php:`type map ` + to apply to cursors, which determines how BSON documents are converted to PHP + values. Defaults to the {{object}}'s type map. +replacement: + object: object +--- +ref: common-option-writeConcern +content: | + :manual:`Write concern ` to use for the operation. + Defaults to the {{object}}'s write concern. +replacement: + object: object +--- +ref: common-option-writeConcern-transaction +content: | + It is not possible to specify a write concern for individual operations as + part of a transaction. Instead, set the ``writeConcern`` option when + :php:`starting the transaction `. +... diff --git a/source/includes/extracts-database-option.yaml b/source/includes/extracts-database-option.yaml new file mode 100644 index 00000000..e83c7abf --- /dev/null +++ b/source/includes/extracts-database-option.yaml @@ -0,0 +1,28 @@ +ref: database-option-readConcern +source: + ref: common-option-readConcern + file: extracts-common-option.yaml +replacement: + object: database +--- +ref: database-option-readPreference +source: + ref: common-option-readPreference + file: extracts-common-option.yaml +replacement: + object: database +--- +ref: database-option-typeMap +source: + ref: common-option-typeMap + file: extracts-common-option.yaml +replacement: + object: database +--- +ref: database-option-writeConcern +source: + ref: common-option-writeConcern + file: extracts-common-option.yaml +replacement: + object: database +... diff --git a/source/includes/extracts-error.yaml b/source/includes/extracts-error.yaml new file mode 100644 index 00000000..c4d8afa5 --- /dev/null +++ b/source/includes/extracts-error.yaml @@ -0,0 +1,52 @@ +ref: error-driver-bulkwriteexception +content: | + :php:`MongoDB\Driver\Exception\BulkWriteException + ` for errors related to the write + operation. Users should inspect the value returned by :php:`getWriteResult() + ` to determine the nature of the + error. +--- +ref: error-driver-invalidargumentexception +content: | + :php:`MongoDB\Driver\Exception\InvalidArgumentException + ` for errors related to the + parsing of parameters or options at the extension level. +--- +ref: error-driver-runtimeexception +content: | + :php:`MongoDB\Driver\Exception\RuntimeException + ` for other errors at the extension + level (e.g. connection errors). +--- +ref: error-badmethodcallexception-write-result +content: | + :phpclass:`MongoDB\Exception\BadMethodCallException` if this method is + called and the write operation used an unacknowledged :manual:`write concern + `. +--- +ref: error-invalidargumentexception +content: | + :phpclass:`MongoDB\Exception\InvalidArgumentException` for errors related to + the parsing of parameters or options. +--- +ref: error-unexpectedvalueexception +content: | + :phpclass:`MongoDB\Exception\UnexpectedValueException` if the command + response from the server was malformed. +--- +ref: error-unsupportedexception +content: | + :phpclass:`MongoDB\Exception\UnsupportedException` if options are used and + not supported by the selected server (e.g. ``collation``, ``readConcern``, + ``writeConcern``). +--- +ref: error-gridfs-filenotfoundexception +content: | + :phpclass:`MongoDB\GridFS\Exception\FileNotFoundException` if no file was + found for the selection criteria. +--- +ref: error-gridfs-corruptfileexception +content: | + :phpclass:`MongoDB\GridFS\Exception\CorruptFileException` if the file's + metadata or chunk documents contain unexpected or invalid data. +... diff --git a/source/includes/extracts-note.yaml b/source/includes/extracts-note.yaml new file mode 100644 index 00000000..6225fafb --- /dev/null +++ b/source/includes/extracts-note.yaml @@ -0,0 +1,28 @@ +ref: note-bson-comparison +content: | + When evaluating query criteria, MongoDB compares types and values according to + its own :manual:`comparison rules for BSON types + `, which differs from PHP's + :php:`comparison ` and :php:`type juggling + ` rules. When matching a special + BSON type the query criteria should use the respective :php:`BSON class + ` in the extension (e.g. use + :php:`MongoDB\BSON\ObjectId ` to match an + :manual:`ObjectId `). +--- +ref: note-atlas-search-requirement +content: | + This command can only be run on a deployment hosted on + `MongoDB Atlas `__ and requires an Atlas cluster tier of at + least M10. A + `Local Atlas Deployment `__ + can also be used for development. +--- +ref: note-atlas-search-async +content: | + Atlas Search indexes are managed asynchronously. After creating or updating an + index, you can periodically execute + :phpmethod:`MongoDB\Collection::listSearchIndexes()` and check the + ``queryable`` :manual:`output field ` + to determine whether it is ready to be used. +... diff --git a/source/includes/extracts-option-requires.yaml b/source/includes/extracts-option-requires.yaml new file mode 100644 index 00000000..edc1c0d3 --- /dev/null +++ b/source/includes/extracts-option-requires.yaml @@ -0,0 +1,47 @@ +ref: _option-requires-version +content: | + This option is available since MongoDB {{version}} and will result in an + exception at execution time if specified for an older server version. +--- +ref: option-requires-4.2 +source: + file: extracts-option-requires.yaml + ref: _option-requires-version +replacement: + version: "4.2" +--- +ref: option-requires-4.4 +source: + file: extracts-option-requires.yaml + ref: _option-requires-version +replacement: + version: "4.4" +--- +ref: option-requires-5.0 +source: + file: extracts-option-requires.yaml + ref: _option-requires-version +replacement: + version: "5.0" +--- +ref: option-requires-5.3 +source: + file: extracts-option-requires.yaml + ref: _option-requires-version +replacement: + version: "5.3" +--- +ref: option-requires-6.0 +source: + file: extracts-option-requires.yaml + ref: _option-requires-version +replacement: + version: "6.0" +--- +ref: option-requires-7.0 +source: + file: extracts-option-requires.yaml + ref: _option-requires-version +replacement: + version: "7.0" +... diff --git a/source/includes/extracts-watch-option.yaml b/source/includes/extracts-watch-option.yaml new file mode 100644 index 00000000..648989c7 --- /dev/null +++ b/source/includes/extracts-watch-option.yaml @@ -0,0 +1,143 @@ +ref: watch-option-batchSize +content: | + Specifies the batch size for the cursor, which will apply to both the initial + ``aggregate`` command and any subsequent ``getMore`` commands. This determines + the maximum number of change events to return in each response from the + server. + + .. note:: + + Irrespective of the ``batchSize`` option, the initial ``aggregate`` command + response for a change stream generally does not include any documents + unless another option is used to configure its starting point (e.g. + ``startAfter``). +--- +ref: watch-option-fullDocument +content: | + Determines how the ``fullDocument`` response field will be populated for + update operations. + + By default, change streams only return the delta of fields (via an + ``updateDescription`` field) for update operations and ``fullDocument`` is + omitted. Insert and replace operations always include the ``fullDocument`` + field. Delete operations omit the field as the document no longer exists. + + Specify "updateLookup" to return the current majority-committed version of the + updated document. + + MongoDB 6.0+ allows returning the post-image of the modified document if the + collection has ``changeStreamPreAndPostImages`` enabled. Specify + "whenAvailable" to return the post-image if available or a null value if not. + Specify "required" to return the post-image if available or raise an error if + not. + + The following values are supported: + + - ``MongoDB\Operation\Watch::FULL_DOCUMENT_UPDATE_LOOKUP`` + - ``MongoDB\Operation\Watch::FULL_DOCUMENT_WHEN_AVAILABLE`` + - ``MongoDB\Operation\Watch::FULL_DOCUMENT_REQUIRED`` + + .. note:: + + This is an option of the ``$changeStream`` pipeline stage. +--- +ref: watch-option-fullDocumentBeforeChange +content: | + Determines how the ``fullDocumentBeforeChange`` response field will be + populated. By default, the field is omitted. + + MongoDB 6.0+ allows returning the pre-image of the modified document if the + collection has ``changeStreamPreAndPostImages`` enabled. Specify + "whenAvailable" to return the pre-image if available or a null value if not. + Specify "required" to return the pre-image if available or raise an error if + not. + + The following values are supported: + + - ``MongoDB\Operation\Watch::FULL_DOCUMENT_BEFORE_CHANGE_WHEN_AVAILABLE`` + - ``MongoDB\Operation\Watch::FULL_DOCUMENT_BEFORE_CHANGE_REQUIRED`` + + .. note:: + + This is an option of the ``$changeStream`` pipeline stage. + + .. versionadded:: 1.13 +--- +ref: watch-option-maxAwaitTimeMS +content: | + Positive integer denoting the time limit in milliseconds for the server to + block a getMore operation if no data is available. +--- +ref: watch-option-resumeAfter +content: | + Specifies the logical starting point for the new change stream. The ``_id`` + field in documents returned by the change stream may be used here. + + Using this option in conjunction with ``startAfter`` and/or + ``startAtOperationTime`` will result in a server error. The options are + mutually exclusive. + + .. note:: + + This is an option of the ``$changeStream`` pipeline stage. +--- +ref: watch-option-showExpandedEvents +content: | + If true, instructs the server to include additional DDL events in the change + stream. The additional events that may be included are: + + - ``createIndexes`` + - ``dropIndexes`` + - ``modify`` + - ``create`` + - ``shardCollection`` + - ``reshardCollection`` (server 6.1+) + - ``refineCollectionShardKey`` (server 6.1+) + + This is not supported for server versions prior to 6.0 and will result in an + exception at execution time if used. + + .. note:: + + This is an option of the ``$changeStream`` pipeline stage. + + .. versionadded:: 1.13 +--- +ref: watch-option-startAfter +content: | + Specifies the logical starting point for the new change stream. The ``_id`` + field in documents returned by the change stream may be used here. Unlike + ``resumeAfter``, this option can be used with a resume token from an + "invalidate" event. + + Using this option in conjunction with ``resumeAfter`` and/or + ``startAtOperationTime`` will result in a server error. The options are + mutually exclusive. + + This is not supported for server versions prior to 4.2 and will result in an + exception at execution time if used. + + .. note:: + + This is an option of the ``$changeStream`` pipeline stage. + + .. versionadded:: 1.5 +--- +ref: watch-option-startAtOperationTime +content: | + If specified, the change stream will only provide changes that occurred at or + after the specified timestamp. Command responses from a MongoDB 4.0+ server + include an ``operationTime`` that can be used here. By default, the + ``operationTime`` returned by the initial ``aggregate`` command will be used + if available. + + Using this option in conjunction with ``resumeAfter`` and/or ``startAfter`` + will result in a server error. The options are mutually exclusive. + + This is not supported for server versions prior to 4.0 and will result in an + exception at execution time if used. + + .. note:: + + This is an option of the ``$changeStream`` pipeline stage. +... diff --git a/source/index.txt b/source/index.txt new file mode 100644 index 00000000..01158168 --- /dev/null +++ b/source/index.txt @@ -0,0 +1,72 @@ +=================== +MongoDB PHP Library +=================== + +.. default-domain:: mongodb + +The |php-library| provides a high-level abstraction around the lower-level +:php:`mongodb extension `. + +The ``mongodb`` extension provides a limited API to connect to the database and +execute generic commands, queries, and write operations. In contrast, the +|php-library| provides a full-featured API and models client, database, and +collection objects. Each of those classes provide various helper methods for +performing operations in context. For example, :phpclass:`MongoDB\Collection` +implements methods for executing CRUD operations and managing indexes on the +collection, among other things. + +If you are developing a PHP application with MongoDB, you should consider using +the |php-library| instead of the extension alone. + +New to the PHP Library? +----------------------- + +If you have some experience with MongoDB but are new to the PHP library, the +following pages should help you get started: + +- :doc:`/tutorial/install-php-library` + +- :doc:`/tutorial/connecting` + +- :doc:`/tutorial/crud` + +- :doc:`/tutorial/commands` + +- :doc:`/tutorial/gridfs` + +- :doc:`/tutorial/modeling-bson-data` + +- :doc:`/reference/bson` + +Code examples can be found in the ``examples`` directory in the source code. + +If you have previously worked with the legacy ``mongo`` extension, it will be +helpful to review the :doc:`/upgrade` for a summary of API changes between the +old driver and this library. + +New to MongoDB? +--------------- + +If you are a new MongoDB user, the following links should help you become more +familiar with MongoDB and introduce some of the concepts and terms you will +encounter in the library documentation: + +- :manual:`Introduction to MongoDB ` + +- :manual:`Databases and Collections ` + +- :manual:`Documents ` and + :manual:`BSON Types ` + +- :manual:`MongoDB CRUD Operations ` + +.. class:: hidden + + .. toctree:: + :titlesonly: + + Installation + /tutorial + /upgrade + /reference + FAQ diff --git a/source/pretty.js b/source/pretty.js new file mode 100644 index 00000000..cd0aa1e1 --- /dev/null +++ b/source/pretty.js @@ -0,0 +1,4 @@ +$(document).ready(function() { + $('pre code').parent().addClass('prettyprint well'); + prettyPrint(); +}); diff --git a/source/reference.txt b/source/reference.txt new file mode 100644 index 00000000..2dd51527 --- /dev/null +++ b/source/reference.txt @@ -0,0 +1,17 @@ +================= +API Documentation +================= + +.. default-domain:: mongodb + +.. toctree:: + :titlesonly: + + /reference/bson + /reference/class/MongoDBClient + /reference/class/MongoDBDatabase + /reference/class/MongoDBCollection + /reference/class/MongoDBGridFSBucket + /reference/result-classes + /reference/functions + /reference/exception-classes diff --git a/source/reference/bson.txt b/source/reference/bson.txt new file mode 100644 index 00000000..315b87a5 --- /dev/null +++ b/source/reference/bson.txt @@ -0,0 +1,51 @@ +==== +BSON +==== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Overview +-------- + +MongoDB stores data records as BSON documents. BSON is a binary representation +of JSON documents, though it contains more data types than JSON. For the BSON +spec, see `bsonspec.org `_. + +By default, the |php-library| returns BSON documents as +:phpclass:`MongoDB\Model\BSONDocument` objects and BSON arrays as +:phpclass:`MongoDB\Model\BSONArray` objects, respectively. + +Classes +------- + +.. phpclass:: MongoDB\Model\BSONArray + + This class extends PHP's :php:`ArrayObject ` class. It also + implements PHP's :php:`JsonSerializable ` interface and the + extension's :php:`MongoDB\BSON\Serializable ` and + :php:`MongoDB\BSON\Unserializable ` + interfaces. + + By default, the library will deserialize BSON arrays as instances of this + class. During BSON and JSON serialization, instances of this class will + serialize as an array type (:php:`array_values() ` is used + internally to numerically reindex the array). + +.. phpclass:: MongoDB\Model\BSONDocument + + This class extends PHP's :php:`ArrayObject ` class. It also + implements PHP's :php:`JsonSerializable ` interface and the + extension's :php:`MongoDB\BSON\Serializable ` and + :php:`MongoDB\BSON\Unserializable ` + interfaces. + + By default, the library will deserialize BSON documents as instances of this + class. During BSON and JSON serialization, instances of this class will + serialize as a document type (:php:`object casting + ` is used internally). diff --git a/source/reference/class/MongoDBBulkWriteResult.txt b/source/reference/class/MongoDBBulkWriteResult.txt new file mode 100644 index 00000000..2e8c78cf --- /dev/null +++ b/source/reference/class/MongoDBBulkWriteResult.txt @@ -0,0 +1,36 @@ +============================== +MongoDB\\BulkWriteResult Class +============================== + +Definition +---------- + +.. phpclass:: MongoDB\BulkWriteResult + + This class contains information about an executed bulk write operation. It + encapsulates a :php:`MongoDB\Driver\WriteResult ` + object and is returned from :phpmethod:`MongoDB\Collection::bulkWrite()`. + +Methods +------- + +.. toctree:: + :titlesonly: + + getDeletedCount() + getInsertedCount() + getInsertedIds() + getMatchedCount() + getModifiedCount() + getUpsertedCount() + getUpsertedIds() + isAcknowledged() + +- :phpmethod:`MongoDB\BulkWriteResult::getDeletedCount()` +- :phpmethod:`MongoDB\BulkWriteResult::getInsertedCount()` +- :phpmethod:`MongoDB\BulkWriteResult::getInsertedIds()` +- :phpmethod:`MongoDB\BulkWriteResult::getMatchedCount()` +- :phpmethod:`MongoDB\BulkWriteResult::getModifiedCount()` +- :phpmethod:`MongoDB\BulkWriteResult::getUpsertedCount()` +- :phpmethod:`MongoDB\BulkWriteResult::getUpsertedIds()` +- :phpmethod:`MongoDB\BulkWriteResult::isAcknowledged()` \ No newline at end of file diff --git a/source/reference/class/MongoDBChangeStream.txt b/source/reference/class/MongoDBChangeStream.txt new file mode 100644 index 00000000..bd82c5e0 --- /dev/null +++ b/source/reference/class/MongoDBChangeStream.txt @@ -0,0 +1,42 @@ +=========================== +MongoDB\\ChangeStream Class +=========================== + +.. versionadded:: 1.3 + +Definition +---------- + +.. phpclass:: MongoDB\ChangeStream + + This class extends PHP's :php:`Iterator ` + interface. An instance of this class is returned by + :phpmethod:`MongoDB\Client::watch()`, + :phpmethod:`MongoDB\Database::watch()`, and + :phpmethod:`MongoDB\Collection::watch()`. + + This class allows for iteration of events in a change stream. It also allows + iteration to automatically resume after certain errors, such as a replica set + failover. + +Methods +------- + +.. toctree:: + :titlesonly: + + current() + getCursorId() + getResumeToken() + key() + next() + rewind() + valid() + +- :phpmethod:`MongoDB\ChangeStream::current()` +- :phpmethod:`MongoDB\ChangeStream::getCursorId()` +- :phpmethod:`MongoDB\ChangeStream::getResumeToken()` +- :phpmethod:`MongoDB\ChangeStream::key()` +- :phpmethod:`MongoDB\ChangeStream::next()` +- :phpmethod:`MongoDB\ChangeStream::rewind()` +- :phpmethod:`MongoDB\ChangeStream::valid()` \ No newline at end of file diff --git a/source/reference/class/MongoDBClient.txt b/source/reference/class/MongoDBClient.txt new file mode 100644 index 00000000..9c97c873 --- /dev/null +++ b/source/reference/class/MongoDBClient.txt @@ -0,0 +1,61 @@ +===================== +MongoDB\\Client Class +===================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpclass:: MongoDB\Client + + This class serves as an entry point for the |php-library|. It is the + preferred class for connecting to a MongoDB server or cluster of servers and + acts as a gateway for accessing individual databases and collections. + :phpclass:`MongoDB\Client` is analogous to the extension's + :php:`MongoDB\Driver\Manager ` class, which it + `composes `_. + +Methods +------- + +.. toctree:: + :titlesonly: + + __construct() + __get() + createClientEncryption() + dropDatabase() + getManager() + getReadConcern() + getReadPreference() + getTypeMap() + getWriteConcern() + listDatabaseNames() + listDatabases() + selectCollection() + selectDatabase() + startSession() + watch() + +- :phpmethod:`MongoDB\Client::__construct()` +- :phpmethod:`MongoDB\Client::__get()` +- :phpmethod:`MongoDB\Client::createClientEncryption()` +- :phpmethod:`MongoDB\Client::dropDatabase()` +- :phpmethod:`MongoDB\Client::getManager()` +- :phpmethod:`MongoDB\Client::getReadConcern()` +- :phpmethod:`MongoDB\Client::getReadPreference()` +- :phpmethod:`MongoDB\Client::getTypeMap()` +- :phpmethod:`MongoDB\Client::getWriteConcern()` +- :phpmethod:`MongoDB\Client::listDatabaseNames()` +- :phpmethod:`MongoDB\Client::listDatabases()` +- :phpmethod:`MongoDB\Client::selectCollection()` +- :phpmethod:`MongoDB\Client::selectDatabase()` +- :phpmethod:`MongoDB\Client::startSession()` +- :phpmethod:`MongoDB\Client::watch()` diff --git a/source/reference/class/MongoDBCollection.txt b/source/reference/class/MongoDBCollection.txt new file mode 100644 index 00000000..462ac4d9 --- /dev/null +++ b/source/reference/class/MongoDBCollection.txt @@ -0,0 +1,132 @@ +========================= +MongoDB\\Collection Class +========================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpclass:: MongoDB\Collection + + Provides methods for common operations on collections and documents, + including CRUD operations and index management. + + You can construct collections directly using the extension's + :php:`MongoDB\Driver\Manager ` class or + select a collection from the library's :phpclass:`MongoDB\Client` or + :phpclass:`MongoDB\Database` classes. A collection may also be cloned from + an existing :phpclass:`MongoDB\Collection` object via the + :phpmethod:`withOptions() ` method. + + :phpclass:`MongoDB\Collection` supports the :php:`readConcern + `, :php:`readPreference + `, :php:`typeMap + `, + and :php:`writeConcern ` options. If you omit an + option, the collection inherits the value from the :php:`Manager + ` constructor argument or the :phpclass:`Client ` + or :phpclass:`Database ` object used to select the collection. + + Operations within the :phpclass:`MongoDB\Collection` class inherit the + collection's options. + +Methods +------- + +.. toctree:: + :titlesonly: + + __construct() + aggregate() + bulkWrite() + count() + countDocuments() + createIndex() + createIndexes() + createSearchIndex() + createSearchIndexes() + deleteMany() + deleteOne() + distinct() + drop() + dropIndex() + dropIndexes() + dropSearchIndex() + estimatedDocumentCount() + explain() + find() + findOne() + findOneAndDelete() + findOneAndReplace() + findOneAndUpdate() + getCollectionName() + getDatabaseName() + getManager() + getNamespace() + getReadConcern() + getReadPreference() + getTypeMap() + getWriteConcern() + insertMany() + insertOne() + listIndexes() + listSearchIndexes() + mapReduce() + rename() + replaceOne() + updateMany() + updateOne() + updateSearchIndex() + watch() + withOptions() + +- :phpmethod:`MongoDB\Collection::__construct()` +- :phpmethod:`MongoDB\Collection::aggregate()` +- :phpmethod:`MongoDB\Collection::bulkWrite()` +- :phpmethod:`MongoDB\Collection::count()` +- :phpmethod:`MongoDB\Collection::countDocuments()` +- :phpmethod:`MongoDB\Collection::createIndex()` +- :phpmethod:`MongoDB\Collection::createIndexes()` +- :phpmethod:`MongoDB\Collection::createSearchIndex()` +- :phpmethod:`MongoDB\Collection::createSearchIndexes()` +- :phpmethod:`MongoDB\Collection::deleteMany()` +- :phpmethod:`MongoDB\Collection::deleteOne()` +- :phpmethod:`MongoDB\Collection::distinct()` +- :phpmethod:`MongoDB\Collection::drop()` +- :phpmethod:`MongoDB\Collection::dropIndex()` +- :phpmethod:`MongoDB\Collection::dropIndexes()` +- :phpmethod:`MongoDB\Collection::dropSearchIndex()` +- :phpmethod:`MongoDB\Collection::estimatedDocumentCount()` +- :phpmethod:`MongoDB\Collection::explain()` +- :phpmethod:`MongoDB\Collection::find()` +- :phpmethod:`MongoDB\Collection::findOne()` +- :phpmethod:`MongoDB\Collection::findOneAndDelete()` +- :phpmethod:`MongoDB\Collection::findOneAndReplace()` +- :phpmethod:`MongoDB\Collection::findOneAndUpdate()` +- :phpmethod:`MongoDB\Collection::getCollectionName()` +- :phpmethod:`MongoDB\Collection::getDatabaseName()` +- :phpmethod:`MongoDB\Collection::getManager()` +- :phpmethod:`MongoDB\Collection::getNamespace()` +- :phpmethod:`MongoDB\Collection::getReadConcern()` +- :phpmethod:`MongoDB\Collection::getReadPreference()` +- :phpmethod:`MongoDB\Collection::getTypeMap()` +- :phpmethod:`MongoDB\Collection::getWriteConcern()` +- :phpmethod:`MongoDB\Collection::insertMany()` +- :phpmethod:`MongoDB\Collection::insertOne()` +- :phpmethod:`MongoDB\Collection::listIndexes()` +- :phpmethod:`MongoDB\Collection::listSearchIndexes()` +- :phpmethod:`MongoDB\Collection::mapReduce()` +- :phpmethod:`MongoDB\Collection::rename()` +- :phpmethod:`MongoDB\Collection::replaceOne()` +- :phpmethod:`MongoDB\Collection::updateMany()` +- :phpmethod:`MongoDB\Collection::updateOne()` +- :phpmethod:`MongoDB\Collection::updateSearchIndex()` +- :phpmethod:`MongoDB\Collection::watch()` +- :phpmethod:`MongoDB\Collection::withOptions()` diff --git a/source/reference/class/MongoDBDatabase.txt b/source/reference/class/MongoDBDatabase.txt new file mode 100644 index 00000000..d733616f --- /dev/null +++ b/source/reference/class/MongoDBDatabase.txt @@ -0,0 +1,90 @@ +======================= +MongoDB\\Database Class +======================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpclass:: MongoDB\Database + + Provides methods for common operations on a database, such as executing + database commands and managing collections. + + You can construct a database directly using the extension's + :php:`MongoDB\Driver\Manager ` class or + select a database from the library's :phpclass:`MongoDB\Client` class. A + database may also be cloned from an existing :phpclass:`MongoDB\Database` + object via the :phpmethod:`withOptions() ` + method. + + :phpclass:`MongoDB\Database` supports the :php:`readConcern + `, :php:`readPreference + `, :php:`typeMap + `, + and :php:`writeConcern ` options. If you omit an + option, the database inherits the value from the :php:`Manager + ` constructor argument or the :phpclass:`Client ` + object used to select the database. + + Operations within the :phpclass:`MongoDB\Database` class inherit the + Database's options. + +Methods +------- + +.. toctree:: + :titlesonly: + + __construct() + __get() + aggregate() + command() + createCollection() + createEncryptedCollection() + drop() + dropCollection() + getDatabaseName() + getManager() + getReadConcern() + getReadPreference() + getTypeMap() + getWriteConcern() + listCollectionNames() + listCollections() + modifyCollection() + renameCollection() + selectCollection() + selectGridFSBucket() + watch() + withOptions() + +- :phpmethod:`MongoDB\Database::__construct()` +- :phpmethod:`MongoDB\Database::__get()` +- :phpmethod:`MongoDB\Database::aggregate()` +- :phpmethod:`MongoDB\Database::command()` +- :phpmethod:`MongoDB\Database::createCollection()` +- :phpmethod:`MongoDB\Database::createEncryptedCollection()` +- :phpmethod:`MongoDB\Database::drop()` +- :phpmethod:`MongoDB\Database::dropCollection()` +- :phpmethod:`MongoDB\Database::getDatabaseName()` +- :phpmethod:`MongoDB\Database::getManager()` +- :phpmethod:`MongoDB\Database::getReadConcern()` +- :phpmethod:`MongoDB\Database::getReadPreference()` +- :phpmethod:`MongoDB\Database::getTypeMap()` +- :phpmethod:`MongoDB\Database::getWriteConcern()` +- :phpmethod:`MongoDB\Database::listCollectionNames()` +- :phpmethod:`MongoDB\Database::listCollections()` +- :phpmethod:`MongoDB\Database::modifyCollection()` +- :phpmethod:`MongoDB\Database::renameCollection()` +- :phpmethod:`MongoDB\Database::selectCollection()` +- :phpmethod:`MongoDB\Database::selectGridFSBucket()` +- :phpmethod:`MongoDB\Database::watch()` +- :phpmethod:`MongoDB\Database::withOptions()` \ No newline at end of file diff --git a/source/reference/class/MongoDBDeleteResult.txt b/source/reference/class/MongoDBDeleteResult.txt new file mode 100644 index 00000000..cd4aa2bc --- /dev/null +++ b/source/reference/class/MongoDBDeleteResult.txt @@ -0,0 +1,25 @@ +=========================== +MongoDB\\DeleteResult Class +=========================== + +Definition +---------- + +.. phpclass:: MongoDB\DeleteResult + + This class contains information about an executed delete operation. It + encapsulates a :php:`MongoDB\Driver\WriteResult ` + object and is returned from :phpmethod:`MongoDB\Collection::deleteMany()` or + :phpmethod:`MongoDB\Collection::deleteOne()`. + +Methods +------- + +.. toctree:: + :titlesonly: + + getDeletedCount() + isAcknowledged() + +- :phpmethod:`MongoDB\DeleteResult::getDeletedCount()` +- :phpmethod:`MongoDB\DeleteResult::isAcknowledged()` diff --git a/source/reference/class/MongoDBGridFSBucket.txt b/source/reference/class/MongoDBGridFSBucket.txt new file mode 100644 index 00000000..f6681a63 --- /dev/null +++ b/source/reference/class/MongoDBGridFSBucket.txt @@ -0,0 +1,82 @@ +============================= +MongoDB\\GridFS\\Bucket Class +============================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpclass:: MongoDB\GridFS\Bucket + + :manual:`GridFS ` is a specification for storing and retrieving + files in MongoDB. GridFS uses two collections to store files. One collection + stores the file chunks (e.g. ``fs.chunks``), and the other stores file + metadata (e.g. ``fs.files``). The :phpclass:`MongoDB\GridFS\Bucket` class + provides an interface around these collections for working with the files as + PHP :php:`Streams `. + + You can construct a GridFS bucket using the extension's + :php:`Manager ` class, or select a bucket from + the library's :phpclass:`MongoDB\Database` class via the + :phpmethod:`selectGridFSBucket() ` + method. + +Methods +------- + +.. toctree:: + :titlesonly: + + __construct() + delete() + downloadToStream() + downloadToStreamByName() + drop() + find() + findOne() + getBucketName() + getChunksCollection() + getChunkSizeBytes() + getDatabaseName() + getFileDocumentForStream() + getFileIdForStream() + getFilesCollection() + getReadConcern() + getReadPreference() + getTypeMap() + getWriteConcern() + openDownloadStream() + openDownloadStreamByName() + openUploadStream() + rename() + uploadFromStream() + +- :phpmethod:`MongoDB\GridFS\Bucket::__construct()` +- :phpmethod:`MongoDB\GridFS\Bucket::delete()` +- :phpmethod:`MongoDB\GridFS\Bucket::downloadToStream()` +- :phpmethod:`MongoDB\GridFS\Bucket::drop()` +- :phpmethod:`MongoDB\GridFS\Bucket::find()` +- :phpmethod:`MongoDB\GridFS\Bucket::findOne()` +- :phpmethod:`MongoDB\GridFS\Bucket::getBucketName()` +- :phpmethod:`MongoDB\GridFS\Bucket::getChunksCollection()` +- :phpmethod:`MongoDB\GridFS\Bucket::getChunkSizeBytes()` +- :phpmethod:`MongoDB\GridFS\Bucket::getDatabaseName()` +- :phpmethod:`MongoDB\GridFS\Bucket::getFileDocumentForStream()` +- :phpmethod:`MongoDB\GridFS\Bucket::getFileIdForStream()` +- :phpmethod:`MongoDB\GridFS\Bucket::getFilesCollection()` +- :phpmethod:`MongoDB\GridFS\Bucket::getReadConcern()` +- :phpmethod:`MongoDB\GridFS\Bucket::getReadPreference()` +- :phpmethod:`MongoDB\GridFS\Bucket::getTypeMap()` +- :phpmethod:`MongoDB\GridFS\Bucket::getWriteConcern()` +- :phpmethod:`MongoDB\GridFS\Bucket::openDownloadStream()` +- :phpmethod:`MongoDB\GridFS\Bucket::openDownloadStreamByName()` +- :phpmethod:`MongoDB\GridFS\Bucket::openUploadStream()` +- :phpmethod:`MongoDB\GridFS\Bucket::rename()` +- :phpmethod:`MongoDB\GridFS\Bucket::uploadFromStream()` diff --git a/source/reference/class/MongoDBInsertManyResult.txt b/source/reference/class/MongoDBInsertManyResult.txt new file mode 100644 index 00000000..f7f79c8c --- /dev/null +++ b/source/reference/class/MongoDBInsertManyResult.txt @@ -0,0 +1,26 @@ +=============================== +MongoDB\\InsertManyResult Class +=============================== + +Definition +---------- + +.. phpclass:: MongoDB\InsertManyResult + + This class contains information about an executed bulk insert operation. It + encapsulates a :php:`MongoDB\Driver\WriteResult ` + object and is returned from :phpmethod:`MongoDB\Collection::insertMany()`. + +Methods +------- + +.. toctree:: + :titlesonly: + + getInsertedCount() + getInsertedIds() + isAcknowledged() + +- :phpmethod:`MongoDB\InsertManyResult::getInsertedCount()` +- :phpmethod:`MongoDB\InsertManyResult::getInsertedIds()` +- :phpmethod:`MongoDB\InsertManyResult::isAcknowledged()` \ No newline at end of file diff --git a/source/reference/class/MongoDBInsertOneResult.txt b/source/reference/class/MongoDBInsertOneResult.txt new file mode 100644 index 00000000..09e0a35b --- /dev/null +++ b/source/reference/class/MongoDBInsertOneResult.txt @@ -0,0 +1,26 @@ +============================== +MongoDB\\InsertOneResult Class +============================== + +Definition +---------- + +.. phpclass:: MongoDB\InsertOneResult + + This class contains information about an executed insert operation. It + encapsulates a :php:`MongoDB\Driver\WriteResult ` + object and is returned from :phpmethod:`MongoDB\Collection::insertOne()`. + +Methods +------- + +.. toctree:: + :titlesonly: + + getInsertedCount() + getInsertedId() + isAcknowledged() + +- :phpmethod:`MongoDB\InsertOneResult::getInsertedCount()` +- :phpmethod:`MongoDB\InsertOneResult::getInsertedId()` +- :phpmethod:`MongoDB\InsertOneResult::isAcknowledged()` \ No newline at end of file diff --git a/source/reference/class/MongoDBMapReduceResult.txt b/source/reference/class/MongoDBMapReduceResult.txt new file mode 100644 index 00000000..8f27cce9 --- /dev/null +++ b/source/reference/class/MongoDBMapReduceResult.txt @@ -0,0 +1,34 @@ +============================== +MongoDB\\MapReduceResult Class +============================== + +.. versionadded:: 1.2 + +Definition +---------- + +.. phpclass:: MongoDB\MapReduceResult + + This class extends PHP's :php:`IteratorAggregate ` + interface. An instance of this class is returned by + :phpmethod:`MongoDB\Collection::mapReduce()`. + + This class allows for iteration of map-reduce results irrespective of the + output method (e.g. inline, collection). It also provides access to command + statistics. + +Methods +------- + +.. toctree:: + :titlesonly: + + getCounts() + getExecutionTimeMS() + getIterator() + getTiming() + +- :phpmethod:`MongoDB\MapReduceResult::getCounts()` +- :phpmethod:`MongoDB\MapReduceResult::getExecutionTimeMS()` +- :phpmethod:`MongoDB\MapReduceResult::getIterator()` +- :phpmethod:`MongoDB\MapReduceResult::getTiming()` \ No newline at end of file diff --git a/source/reference/class/MongoDBModelCollectionInfo.txt b/source/reference/class/MongoDBModelCollectionInfo.txt new file mode 100644 index 00000000..76b9af35 --- /dev/null +++ b/source/reference/class/MongoDBModelCollectionInfo.txt @@ -0,0 +1,49 @@ +==================================== +MongoDB\\Model\\CollectionInfo Class +==================================== + +Definition +---------- + +.. phpclass:: MongoDB\Model\CollectionInfo + + This class models information about a collection. Instances of this class are + returned by traversing a :phpclass:`MongoDB\Model\CollectionInfoIterator`, + which is returned by :phpmethod:`MongoDB\Database::listCollections()`. + +.. versionchanged:: 1.4 + + This class implements PHP's :php:`ArrayAccess ` interface. This + provides a mechanism for accessing index fields for which there exists no + helper method. :php:`isset() ` may be used to check for the existence + of a field before accessing it with ``[]``. + + .. note:: + + The :phpclass:`MongoDB\Model\CollectionInfo` class is immutable. Attempting + to modify it via the :php:`ArrayAccess ` interface will + result in a :phpclass:`MongoDB\Exception\BadMethodCallException`. + +Methods +------- + +.. toctree:: + :titlesonly: + + getCappedMax() + getCappedSize() + getIdIndex() + getInfo() + getName() + getOptions() + getType() + isCapped() + +- :phpmethod:`MongoDB\Model\CollectionInfo::getCappedMax()` +- :phpmethod:`MongoDB\Model\CollectionInfo::getCappedSize()` +- :phpmethod:`MongoDB\Model\CollectionInfo::getIdIndex()` +- :phpmethod:`MongoDB\Model\CollectionInfo::getInfo()` +- :phpmethod:`MongoDB\Model\CollectionInfo::getName()` +- :phpmethod:`MongoDB\Model\CollectionInfo::getOptions()` +- :phpmethod:`MongoDB\Model\CollectionInfo::getType()` +- :phpmethod:`MongoDB\Model\CollectionInfo::isCapped()` \ No newline at end of file diff --git a/source/reference/class/MongoDBModelCollectionInfoIterator.txt b/source/reference/class/MongoDBModelCollectionInfoIterator.txt new file mode 100644 index 00000000..fca6da62 --- /dev/null +++ b/source/reference/class/MongoDBModelCollectionInfoIterator.txt @@ -0,0 +1,20 @@ +============================================ +MongoDB\\Model\\CollectionInfoIterator Class +============================================ + +Definition +---------- + +.. phpclass:: MongoDB\Model\CollectionInfoIterator + + This interface extends PHP's :php:`Iterator ` + interface. An instance of this interface is returned by + :phpmethod:`MongoDB\Database::listCollections()`. + +Methods +------- + +This interface adds no new methods to :php:`Iterator +`, but specifies that :php:`current() +` will return an instance of +:phpclass:`MongoDB\Model\CollectionInfo`. \ No newline at end of file diff --git a/source/reference/class/MongoDBModelDatabaseInfo.txt b/source/reference/class/MongoDBModelDatabaseInfo.txt new file mode 100644 index 00000000..a8d18cd6 --- /dev/null +++ b/source/reference/class/MongoDBModelDatabaseInfo.txt @@ -0,0 +1,39 @@ +================================== +MongoDB\\Model\\DatabaseInfo Class +================================== + +Definition +---------- + +.. phpclass:: MongoDB\Model\DatabaseInfo + + This class models information about a database. Instances of this class are + returned by traversing a :phpclass:`MongoDB\Model\DatabaseInfoIterator`, + which is returned by :phpmethod:`MongoDB\Client::listDatabases()`. + +.. versionchanged:: 1.4 + + This class implements PHP's :php:`ArrayAccess ` interface. This + provides a mechanism for accessing index fields for which there exists no + helper method. :php:`isset() ` may be used to check for the existence + of a field before accessing it with ``[]``. + + .. note:: + + The :phpclass:`MongoDB\Model\DatabaseInfo` class is immutable. Attempting + to modify it via the :php:`ArrayAccess ` interface will + result in a :phpclass:`MongoDB\Exception\BadMethodCallException`. + +Methods +------- + +.. toctree:: + :titlesonly: + + getName() + getSizeOnDisk() + isEmpty() + +- :phpmethod:`MongoDB\Model\DatabaseInfo::getName()` +- :phpmethod:`MongoDB\Model\DatabaseInfo::getSizeOnDisk()` +- :phpmethod:`MongoDB\Model\DatabaseInfo::isEmpty()` \ No newline at end of file diff --git a/source/reference/class/MongoDBModelDatabaseInfoIterator.txt b/source/reference/class/MongoDBModelDatabaseInfoIterator.txt new file mode 100644 index 00000000..ba36ef2e --- /dev/null +++ b/source/reference/class/MongoDBModelDatabaseInfoIterator.txt @@ -0,0 +1,20 @@ +========================================== +MongoDB\\Model\\DatabaseInfoIterator Class +========================================== + +Definition +---------- + +.. phpclass:: MongoDB\Model\DatabaseInfoIterator + + This interface extends PHP's :php:`Iterator ` + interface. An instance of this interface is returned by + :phpmethod:`MongoDB\Client::listDatabases()`. + +Methods +------- + +This interface adds no new methods to :php:`Iterator +`, but specifies that :php:`current() +` will return an instance of +:phpclass:`MongoDB\Model\DatabaseInfo`. \ No newline at end of file diff --git a/source/reference/class/MongoDBModelIndexInfo.txt b/source/reference/class/MongoDBModelIndexInfo.txt new file mode 100644 index 00000000..4d017e5d --- /dev/null +++ b/source/reference/class/MongoDBModelIndexInfo.txt @@ -0,0 +1,51 @@ +=============================== +MongoDB\\Model\\IndexInfo Class +=============================== + +Definition +---------- + +.. phpclass:: MongoDB\Model\IndexInfo + + This class models information about an index. Instances of this class are + returned by traversing a :phpclass:`MongoDB\Model\IndexInfoIterator`, + which is returned by :phpmethod:`MongoDB\Collection::listIndexes()`. + + This class implements PHP's :php:`ArrayAccess ` interface. This + provides a mechanism for accessing index fields for which there exists no + helper method. :php:`isset() ` may be used to check for the existence + of a field before accessing it with ``[]``. + + .. note:: + + The :phpclass:`MongoDB\Model\IndexInfo` class is immutable. Attempting + to modify it via the :php:`ArrayAccess ` interface will + result in a :phpclass:`MongoDB\Exception\BadMethodCallException`. + +Methods +------- + +.. toctree:: + :titlesonly: + + getKey() + getName() + getNamespace() + getVersion() + is2dSphere() + isGeoHaystack() + isSparse() + isText() + isTtl() + isUnique() + +- :phpmethod:`MongoDB\Model\IndexInfo::getKey()` +- :phpmethod:`MongoDB\Model\IndexInfo::getName()` +- :phpmethod:`MongoDB\Model\IndexInfo::getNamespace()` +- :phpmethod:`MongoDB\Model\IndexInfo::getVersion()` +- :phpmethod:`MongoDB\Model\IndexInfo::is2dSphere()` +- :phpmethod:`MongoDB\Model\IndexInfo::isGeoHaystack()` +- :phpmethod:`MongoDB\Model\IndexInfo::isSparse()` +- :phpmethod:`MongoDB\Model\IndexInfo::isText()` +- :phpmethod:`MongoDB\Model\IndexInfo::isTtl()` +- :phpmethod:`MongoDB\Model\IndexInfo::isUnique()` \ No newline at end of file diff --git a/source/reference/class/MongoDBModelIndexInfoIterator.txt b/source/reference/class/MongoDBModelIndexInfoIterator.txt new file mode 100644 index 00000000..0fae59c2 --- /dev/null +++ b/source/reference/class/MongoDBModelIndexInfoIterator.txt @@ -0,0 +1,20 @@ +======================================= +MongoDB\\Model\\IndexInfoIterator Class +======================================= + +Definition +---------- + +.. phpclass:: MongoDB\Model\IndexInfoIterator + + This interface extends PHP's :php:`Iterator ` + interface. An instance of this interface is returned by + :phpmethod:`MongoDB\Collection::listIndexes()`. + +Methods +------- + +This interface adds no new methods to :php:`Iterator +`, but specifies that :php:`current() +` will return an instance of +:phpclass:`MongoDB\Model\IndexInfo`. \ No newline at end of file diff --git a/source/reference/class/MongoDBUpdateResult.txt b/source/reference/class/MongoDBUpdateResult.txt new file mode 100644 index 00000000..52561e59 --- /dev/null +++ b/source/reference/class/MongoDBUpdateResult.txt @@ -0,0 +1,33 @@ +=========================== +MongoDB\\UpdateResult Class +=========================== + +Definition +---------- + +.. phpclass:: MongoDB\UpdateResult + + This class contains information about an executed update or replace + operation. It encapsulates a :php:`MongoDB\Driver\WriteResult + ` object and is returned from + :phpmethod:`MongoDB\Collection::replaceOne()`, + :phpmethod:`MongoDB\Collection::updateMany()`, or + :phpmethod:`MongoDB\Collection::updateOne()`. + +Methods +------- + +.. toctree:: + :titlesonly: + + getMatchedCount() + getModifiedCount() + getUpsertedCount() + getUpsertedId() + isAcknowledged() + +- :phpmethod:`MongoDB\UpdateResult::getMatchedCount()` +- :phpmethod:`MongoDB\UpdateResult::getModifiedCount()` +- :phpmethod:`MongoDB\UpdateResult::getUpsertedCount()` +- :phpmethod:`MongoDB\UpdateResult::getUpsertedId()` +- :phpmethod:`MongoDB\UpdateResult::isAcknowledged()` \ No newline at end of file diff --git a/source/reference/exception-classes.txt b/source/reference/exception-classes.txt new file mode 100644 index 00000000..b21801a3 --- /dev/null +++ b/source/reference/exception-classes.txt @@ -0,0 +1,148 @@ +================= +Exception Classes +================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +MongoDB\\Exception\\BadMethodCallException +------------------------------------------ + +.. phpclass:: MongoDB\Exception\BadMethodCallException + + This exception is thrown when an unsupported method is invoked on an object. + + For example, using an unacknowledged write concern with + :phpmethod:`MongoDB\Collection::insertMany()` will return a + :phpclass:`MongoDB\InsertManyResult` object. It is a logical error to call + :phpmethod:`MongoDB\InsertManyResult::getInsertedCount()`, since the number + of inserted documents can only be determined from the response of an + acknowledged write operation. + + This class extends PHP's :php:`BadMethodCallException + ` class and implements the library's + :phpclass:`Exception ` interface. + +---- + +MongoDB\\Exception\\CreateEncryptedCollectionException +------------------------------------------------------ + +.. phpclass:: MongoDB\Exception\CreateEncryptedCollectionException + + Thrown by :phpmethod:`MongoDB\Database::createEncryptedCollection()` if any + error is encountered while creating data keys or creating the collection. The + original exception and modified ``encryptedFields`` option can be accessed + via the ``getPrevious()`` and ``getEncryptedFields()`` methods, respectively. + + This class extends the library's :phpclass:`RuntimeException + ` class. + +---- + +MongoDB\\Exception\\InvalidArgumentException +-------------------------------------------- + +.. phpclass:: MongoDB\Exception\InvalidArgumentException + + Thrown for errors related to the parsing of parameters or options within the + library. + + This class extends the extension's :php:`InvalidArgumentException + ` class and implements the + library's :phpclass:`Exception ` interface. + +---- + +MongoDB\\Exception\\UnexpectedValueException +-------------------------------------------- + +.. phpclass:: MongoDB\Exception\UnexpectedValueException + + This exception is thrown when a command response from the server is + malformed or not what the library expected. This exception means that an + assertion in some operation, which abstracts a database command, has failed. + It may indicate a corrupted BSON response or bug in the server or driver. + + This class extends the extension's :php:`UnexpectedValueException + ` class and implements the + library's :phpclass:`Exception ` interface. + +---- + +MongoDB\\Exception\\UnsupportedException +---------------------------------------- + +.. phpclass:: MongoDB\Exception\UnsupportedException + + This exception is thrown if an option is used and not supported by the + selected server. It is used sparingly in cases where silently ignoring the + unsupported option might otherwise lead to unexpected behavior. + + This class extends the library's :phpclass:`RuntimeException + ` class. + + .. note:: + + Unlike :phpclass:`InvalidArgumentException + `, which may be thrown when + an operation's parameters and options are parsed during construction, the + selected server is not known until an operation is executed. + +---- + +MongoDB\\GridFS\\Exception\\CorruptFileException +------------------------------------------------ + +.. phpclass:: MongoDB\GridFS\Exception\CorruptFileException + + This exception is thrown if a GridFS file's metadata or chunk documents + contain unexpected or invalid data. + + When selecting a GridFS file, this may be thrown if a metadata field has an + incorrect type or its value is out of range (e.g. negative ``length``). When + reading a GridFS file, this may be thrown if a chunk's index is out of + sequence or its binary data's length out of range. + + This class extends the library's :phpclass:`RuntimeException + ` class. + +---- + +MongoDB\\GridFS\\Exception\\FileNotFoundException +------------------------------------------------- + +.. phpclass:: MongoDB\GridFS\Exception\FileNotFoundException + + This exception is thrown if no GridFS file was found for the selection + criteria (e.g. ``id``, ``filename``). + + This class extends the library's :phpclass:`RuntimeException + ` class. + +---- + +MongoDB\\Exception\\Exception +----------------------------- + +.. phpclass:: MongoDB\Exception\Exception + + This interface extends the extension's :php:`Exception + ` interface and is implemented by all + exception classes within the library. + +---- + +MongoDB\\Exception\\RuntimeException +------------------------------------ + +.. phpclass:: MongoDB\Exception\RuntimeException + + This class extends the extension's :php:`RuntimeException + ` class, which in turn extends + PHP's :php:`RuntimeException ` class. diff --git a/source/reference/function/add_logger.txt b/source/reference/function/add_logger.txt new file mode 100644 index 00000000..69076915 --- /dev/null +++ b/source/reference/function/add_logger.txt @@ -0,0 +1,63 @@ +===================== +MongoDB\\add_logger() +===================== + +.. versionadded:: 1.17 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\add_logger() + + Registers a PSR logger to receive log messages from the extension. + + .. code-block:: php + + function add_logger(Psr\Log\LoggerInterface $logger): void + +Parameters +---------- + +``$logger`` : Psr\\Log\\LoggerInterface + A logger to register. + + If the logger is already registered, the method will have no effect. + +Behavior +-------- + +This function allows the application to register one or more +`Psr\\Log\\LoggerInterface `__ +objects to receive log messages from libmongoc and the extension. Each +registered logger will receive messages for *all* clients. + +Messages originating from the extension will have their log level translated to +an equivalent `PSR log level `__. +For performance reasons, trace-level messages from the extension are *not* +forwarded to PSR loggers. The extension's +:php:`mongodb.debug ` INI +configuration must be used to collect trace-level logs. + +Log messages also include a domain string that identifies the driver component +that emitted the log message. This value is provided to the PSR logger via the +{{domain}} key of the context array. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-invalidargumentexception.rst + +See Also +-------- + +- :phpmethod:`MongoDB\remove_logger()` +- `PSR-3: Logger Interface `__ +- `libmongoc: Logging `__ diff --git a/source/reference/function/remove_logger.txt b/source/reference/function/remove_logger.txt new file mode 100644 index 00000000..369c5c13 --- /dev/null +++ b/source/reference/function/remove_logger.txt @@ -0,0 +1,45 @@ +======================== +MongoDB\\remove_logger() +======================== + +.. versionadded:: 1.17 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\remove_logger() + + Unregisters a PSR logger to no longer receive log messages from the + extension. + + .. code-block:: php + + function remove_logger(Psr\Log\LoggerInterface $logger): void + +Parameters +---------- + +``$logger`` : Psr\Log\LoggerInterface + A logger to unregister. + + If the logger is not registered, the method will have no effect. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-invalidargumentexception.rst + +See Also +-------- + +- :phpmethod:`MongoDB\add_logger()` +- `PSR-3: Logger Interface `__ +- `libmongoc: Logging `__ diff --git a/source/reference/function/with_transaction.txt b/source/reference/function/with_transaction.txt new file mode 100644 index 00000000..b759025e --- /dev/null +++ b/source/reference/function/with_transaction.txt @@ -0,0 +1,95 @@ +=========================== +MongoDB\\with_transaction() +=========================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +.. versionadded:: 1.5 + +Definition +---------- + +.. phpmethod:: MongoDB\with_transaction() + + Execute a callback within a transaction using the given client session + + .. code-block:: php + + function with_transaction( + MongoDB\Driver\Session $session, + callable $callback, + array $transactionOptions = [] + ): void + +Parameters +---------- + +``$session`` : :php:`MongoDB\Driver\Session ` + A client session used to execute the transaction. + +``$callback`` : :php:`callable ` + A callback that will be run inside the transaction. The callback must accept a + :php:`MongoDB\Driver\Session ` object as its first + argument. + +``$transactionOptions`` : array + Transaction options, which will be passed to + :php:`MongoDB\Driver\Session::startTransaction `. + See the extension documentation for a list of supported options. + +Behavior +-------- + +This function is responsible for starting a transaction, invoking a callback, +and committing a transaction. It also applies logic to retry this process after +certain errors within a preset time limit. The callback is expected to execute +one or more operations within the transactionby passing the callback's +:php:`MongoDB\Driver\Session ` argument as an option to +those operations; however, that is not enforced. + +.. note:: + + Applications are strongly encouraged to use an + `idempotent `_ callback, since it + may be invoked multiple times if retryable errors are encountered during + either callback execution or committing. + +Any exception thrown during execution of the callback will be caught and +evaluated. If an exception has a ``TransientTransactionError`` error label, the +transaction will be aborted, restarted, and the callback will be invoked again. +For any other exception, the transaction will be aborted and the exception +re-thrown to propagate the error to the caller of ``with_transaction()``. + +Following successful execution of the callback, the transaction will be +committed. If an exception with an UnknownTransactionCommitResult error label is +encountered, the commit will be retried. If an exception with a +``TransientTransactionError`` error label is encountered, the transaction will +be restarted and control will return to invoking the callback. Any other +exception will be re-thrown to propagate the error to the caller of +``with_transaction()``. + +When an error occurs during callback execution or committing, the process is +only retried if fewer than 120 seconds have elapsed since ``with_transaction()`` +was first called. This time limit is not configurable. After this time, any +exception that would normally result in a retry attempt will instead be +re-thrown. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +See Also +-------- + +- :php:`MongoDB\Driver\Session::startTransaction ` +- :php:`MongoDB\Driver\Session::commitTransaction ` +- :manual:`Transactions: Drivers API ` documentation in the MongoDB manual +- `Convenient API for Transactions `_ specification diff --git a/source/reference/functions.txt b/source/reference/functions.txt new file mode 100644 index 00000000..a5130b8f --- /dev/null +++ b/source/reference/functions.txt @@ -0,0 +1,22 @@ +========= +Functions +========= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +.. toctree:: + :titlesonly: + + add_logger() + remove_logger() + with_transaction() + +- :phpmethod:`MongoDB\add_logger()` +- :phpmethod:`MongoDB\remove_logger()` +- :phpmethod:`MongoDB\with_transaction()` diff --git a/source/reference/method/MongoDBBulkWriteResult-getDeletedCount.txt b/source/reference/method/MongoDBBulkWriteResult-getDeletedCount.txt new file mode 100644 index 00000000..8dbe98d5 --- /dev/null +++ b/source/reference/method/MongoDBBulkWriteResult-getDeletedCount.txt @@ -0,0 +1,42 @@ +=========================================== +MongoDB\\BulkWriteResult::getDeletedCount() +=========================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\BulkWriteResult::getDeletedCount() + + Return the total number of documents that were deleted by all delete + operations in the bulk write. + + .. code-block:: php + + function getDeletedCount(): integer + + This method should only be called if the write was acknowledged. + +Return Values +------------- + +The total number of documents that were deleted by all delete operations in the +bulk write. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-badmethodcallexception-write-result.rst + +See Also +-------- + +- :php:`MongoDB\Driver\WriteResult::getDeletedCount() + ` diff --git a/source/reference/method/MongoDBBulkWriteResult-getInsertedCount.txt b/source/reference/method/MongoDBBulkWriteResult-getInsertedCount.txt new file mode 100644 index 00000000..8d9a4ed8 --- /dev/null +++ b/source/reference/method/MongoDBBulkWriteResult-getInsertedCount.txt @@ -0,0 +1,42 @@ +============================================ +MongoDB\\BulkWriteResult::getInsertedCount() +============================================ + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\BulkWriteResult::getInsertedCount() + + Return the total number of documents that were inserted by all insert + operations in the bulk write. + + .. code-block:: php + + function getInsertedCount(): integer + + This method should only be called if the write was acknowledged. + +Return Values +------------- + +The total number of documents that were inserted by all insert operations in the +bulk write. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-badmethodcallexception-write-result.rst + +See Also +-------- + +- :php:`MongoDB\Driver\WriteResult::getInsertedCount() + ` diff --git a/source/reference/method/MongoDBBulkWriteResult-getInsertedIds.txt b/source/reference/method/MongoDBBulkWriteResult-getInsertedIds.txt new file mode 100644 index 00000000..bb6752ff --- /dev/null +++ b/source/reference/method/MongoDBBulkWriteResult-getInsertedIds.txt @@ -0,0 +1,38 @@ +========================================== +MongoDB\\BulkWriteResult::getInsertedIds() +========================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\BulkWriteResult::getInsertedIds() + + Return a map of IDs (i.e. ``_id`` field values) for documents that were + inserted by all insert operations in the bulk write. + + .. code-block:: php + + function getInsertedIds(): array + + Since IDs are created by the driver, this method may be called irrespective + of whether the write was acknowledged. + +Return Values +------------- + +A map of IDs (i.e. ``_id`` field values) for documents that were inserted by all +insert operations in the bulk write. + +The index of each ID in the map corresponds to each document's position in the +bulk operation. If a document had an ID prior to inserting (i.e. the driver did +not generate an ID), the index will contain its ``_id`` field value. Any +driver-generated ID will be a :php:`MongoDB\BSON\ObjectId +` instance. diff --git a/source/reference/method/MongoDBBulkWriteResult-getMatchedCount.txt b/source/reference/method/MongoDBBulkWriteResult-getMatchedCount.txt new file mode 100644 index 00000000..02341bed --- /dev/null +++ b/source/reference/method/MongoDBBulkWriteResult-getMatchedCount.txt @@ -0,0 +1,51 @@ +=========================================== +MongoDB\\BulkWriteResult::getMatchedCount() +=========================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\BulkWriteResult::getMatchedCount() + + Return the total number of documents that were matched by all update and + replace operations in the bulk write. + + .. code-block:: php + + function getMatchedCount(): integer + + This method should only be called if the write was acknowledged. + + .. note:: + + If an update/replace operation results in no change to the document + (e.g. setting the value of a field to its current value), the matched + count may be greater than the value returned by + :phpmethod:`getModifiedCount() + `. + +Return Values +------------- + +The total number of documents that were matched by all update and replace +operations in the bulk write. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-badmethodcallexception-write-result.rst + +See Also +-------- + +- :phpmethod:`MongoDB\BulkWriteResult::getModifiedCount()` +- :php:`MongoDB\Driver\WriteResult::getMatchedCount() + ` diff --git a/source/reference/method/MongoDBBulkWriteResult-getModifiedCount.txt b/source/reference/method/MongoDBBulkWriteResult-getModifiedCount.txt new file mode 100644 index 00000000..6f179bd8 --- /dev/null +++ b/source/reference/method/MongoDBBulkWriteResult-getModifiedCount.txt @@ -0,0 +1,50 @@ +============================================ +MongoDB\\BulkWriteResult::getModifiedCount() +============================================ + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\BulkWriteResult::getModifiedCount() + + Return the total number of documents that were modified by all update and + replace operations in the bulk write. + + .. code-block:: php + + function getModifiedCount(): integer + + This method should only be called if the write was acknowledged. + + .. note:: + + If an update/replace operation results in no change to the document + (e.g. setting the value of a field to its current value), the modified + count may be less than the value returned by :phpmethod:`getMatchedCount() + `. + +Return Values +------------- + +The total number of documents that were modified by all update and replace +operations in the bulk write. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-badmethodcallexception-write-result.rst + +See Also +-------- + +- :phpmethod:`MongoDB\BulkWriteResult::getMatchedCount()` +- :php:`MongoDB\Driver\WriteResult::getModifiedCount() + ` diff --git a/source/reference/method/MongoDBBulkWriteResult-getUpsertedCount.txt b/source/reference/method/MongoDBBulkWriteResult-getUpsertedCount.txt new file mode 100644 index 00000000..00f1ff1f --- /dev/null +++ b/source/reference/method/MongoDBBulkWriteResult-getUpsertedCount.txt @@ -0,0 +1,42 @@ +============================================ +MongoDB\\BulkWriteResult::getUpsertedCount() +============================================ + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\BulkWriteResult::getUpsertedCount() + + Return the total number of documents that were upserted by all update and + replace operations in the bulk write. + + .. code-block:: php + + function getUpsertedCount(): integer + + This method should only be called if the write was acknowledged. + +Return Values +------------- + +The total number of documents that were upserted by all update and replace +operations in the bulk write. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-badmethodcallexception-write-result.rst + +See Also +-------- + +- :php:`MongoDB\Driver\WriteResult::getUpsertedCount() + ` diff --git a/source/reference/method/MongoDBBulkWriteResult-getUpsertedIds.txt b/source/reference/method/MongoDBBulkWriteResult-getUpsertedIds.txt new file mode 100644 index 00000000..df0b1fbb --- /dev/null +++ b/source/reference/method/MongoDBBulkWriteResult-getUpsertedIds.txt @@ -0,0 +1,46 @@ +========================================== +MongoDB\\BulkWriteResult::getUpsertedIds() +========================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\BulkWriteResult::getUpsertedIds() + + Return a map of IDs (i.e. ``_id`` field values) for documents that were + upserted by all update and replace operations in the bulk write. + + .. code-block:: php + + function getUpsertedIds(): array + +Return Values +------------- + +A map of IDs (i.e. ``_id`` field values) for documents that were upserted by all +update and replace operations in the bulk write. + +The index of each ID in the map corresponds to each document's position in the +bulk operation. If a document had an ID prior to upserting (i.e. the server did +not generate an ID), the index will contain its ``_id`` field value. Any +server-generated ID will be a :php:`MongoDB\BSON\ObjectId +` instance. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-badmethodcallexception-write-result.rst + +See Also +-------- + +- :php:`MongoDB\Driver\WriteResult::getUpsertedIds() + ` diff --git a/source/reference/method/MongoDBBulkWriteResult-isAcknowledged.txt b/source/reference/method/MongoDBBulkWriteResult-isAcknowledged.txt new file mode 100644 index 00000000..611f9fa7 --- /dev/null +++ b/source/reference/method/MongoDBBulkWriteResult-isAcknowledged.txt @@ -0,0 +1,34 @@ +========================================== +MongoDB\\BulkWriteResult::isAcknowledged() +========================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\BulkWriteResult::isAcknowledged() + + Return whether the write was acknowledged. + + .. code-block:: php + + function isAcknowledged(): boolean + +Return Values +------------- + +A boolean indicating whether the write was acknowledged. + +See Also +-------- + +- :php:`MongoDB\Driver\WriteResult::isAcknowledged() + ` +- :manual:`Write Concern ` in the MongoDB manual diff --git a/source/reference/method/MongoDBChangeStream-current.txt b/source/reference/method/MongoDBChangeStream-current.txt new file mode 100644 index 00000000..ccff68e0 --- /dev/null +++ b/source/reference/method/MongoDBChangeStream-current.txt @@ -0,0 +1,106 @@ +================================ +MongoDB\\ChangeStream::current() +================================ + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\ChangeStream::current() + + Returns the current event in the change stream. + + .. code-block:: php + + function current(): array|object|null + + The structure of each event document will vary based on the operation type. + See :manual:`Change Events ` in the MongoDB manual + for more information. + +Return Values +------------- + +An array or object for the current event in the change stream, or ``null`` if +there is no current event (i.e. :phpmethod:`MongoDB\ChangeStream::valid()` +returns ``false``). The return type will depend on the ``typeMap`` option for +:phpmethod:`MongoDB\Collection::watch()`. + +Examples +-------- + +This example reports events while iterating a change stream. + +.. code-block:: php + + test->inventory; + + $changeStream = $collection->watch(); + + for ($changeStream->rewind(); true; $changeStream->next()) { + if ( ! $changeStream->valid()) { + continue; + } + + $event = $changeStream->current(); + + $ns = sprintf('%s.%s', $event['ns']['db'], $event['ns']['coll']); + $id = json_encode($event['documentKey']['_id']); + + switch ($event['operationType']) { + case 'delete': + printf("Deleted document in %s with _id: %s\n\n", $ns, $id); + break; + + case 'insert': + printf("Inserted new document in %s\n", $ns); + echo json_encode($event['fullDocument']), "\n\n"; + break; + + case 'replace': + printf("Replaced new document in %s with _id: %s\n", $ns, $id); + echo json_encode($event['fullDocument']), "\n\n"; + break; + + case 'update': + printf("Updated document in %s with _id: %s\n", $ns, $id); + echo json_encode($event['updateDescription']), "\n\n"; + break; + } + } + +Assuming that a document was inserted, updated, and deleted while the above +script was iterating the change stream, the output would then resemble: + +.. code-block:: none + + Inserted new document in test.inventory + {"_id":{"$oid":"5a81fc0d6118fd1af1790d32"},"name":"Widget","quantity":5} + + Updated document in test.inventory with _id: {"$oid":"5a81fc0d6118fd1af1790d32"} + {"updatedFields":{"quantity":4},"removedFields":[]} + + Deleted document in test.inventory with _id: {"$oid":"5a81fc0d6118fd1af1790d32"} + +See Also +-------- + +- :phpmethod:`MongoDB\Client::watch()` +- :phpmethod:`MongoDB\Collection::watch()` +- :phpmethod:`MongoDB\Database::watch()` +- :php:`Iterator::current() ` +- :ref:`Tailable Cursor Iteration ` +- :manual:`Change Streams ` documentation in the MongoDB manual +- :manual:`Change Events ` documentation in the + MongoDB manual diff --git a/source/reference/method/MongoDBChangeStream-getCursorId.txt b/source/reference/method/MongoDBChangeStream-getCursorId.txt new file mode 100644 index 00000000..066930e1 --- /dev/null +++ b/source/reference/method/MongoDBChangeStream-getCursorId.txt @@ -0,0 +1,62 @@ +==================================== +MongoDB\\ChangeStream::getCursorId() +==================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\ChangeStream::getCursorId() + + Returns the change stream cursor's ID. + + .. code-block:: php + + function getCursorId(): MongoDB\Driver\CursorId + +Return Values +------------- + +A :php:`MongoDB\Driver\CursorId ` object. + +Examples +-------- + +This example reports the cursor ID for a change stream. + +.. code-block:: php + + test->inventory; + + $changeStream = $collection->watch(); + + var_dump($changeStream->getCursorId()); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Driver\CursorId)#5 (1) { + ["id"]=> + int(8462642181784669708) + } + +See Also +-------- + +- :phpmethod:`MongoDB\Client::watch()` +- :phpmethod:`MongoDB\Collection::watch()` +- :phpmethod:`MongoDB\Database::watch()` +- :php:`MongoDB\Driver\CursorId ` +- :php:`MongoDB\Driver\Cursor::getId() ` diff --git a/source/reference/method/MongoDBChangeStream-getResumeToken.txt b/source/reference/method/MongoDBChangeStream-getResumeToken.txt new file mode 100644 index 00000000..873e29bb --- /dev/null +++ b/source/reference/method/MongoDBChangeStream-getResumeToken.txt @@ -0,0 +1,75 @@ +======================================= +MongoDB\\ChangeStream::getResumeToken() +======================================= + +.. versionadded:: 1.5 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\ChangeStream::getResumeToken() + + Returns the cached resume token that will be used to resume the change + stream. + + .. code-block:: php + + function getResumeToken(): array|object|null + +Return Values +------------- + +An array or object, or ``null`` if there is no cached resume token. The return +type will depend on the ``typeMap`` option for the ``watch()`` method used to +create the change stream. + +Examples +-------- + +This example captures the resume token for a change stream after encountering +an ``invalidate`` event and uses it to construct a second change stream using +the ``startAfter`` option. + +.. code-block:: php + + test->inventory; + + $changeStream = $collection->watch(); + + for ($changeStream->rewind(); true; $changeStream->next()) { + if ( ! $changeStream->valid()) { + continue; + } + + $event = $changeStream->current(); + + if ($event['operationType'] === 'invalidate') { + $startAfter = $changeStream->getResumeToken(); + break; + } + + printf("%d: %s\n", $changeStream->key(), $event['operationType']); + } + + $changeStream = $collection->watch([], ['startAfter' => $startAfter]); + +See Also +-------- + +- :phpmethod:`MongoDB\Client::watch()` +- :phpmethod:`MongoDB\Collection::watch()` +- :phpmethod:`MongoDB\Database::watch()` +- :manual:`Resume a Change Stream ` + documentation in the MongoDB manual diff --git a/source/reference/method/MongoDBChangeStream-key.txt b/source/reference/method/MongoDBChangeStream-key.txt new file mode 100644 index 00000000..8b35616f --- /dev/null +++ b/source/reference/method/MongoDBChangeStream-key.txt @@ -0,0 +1,76 @@ +============================ +MongoDB\\ChangeStream::key() +============================ + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\ChangeStream::key() + + Returns the index of the current event in the change stream. + + .. code-block:: php + + function key(): integer|null + + The index of the first event in a change stream starts at zero and will + increment by one for each subsequent event. + +Return Values +------------- + +The index of the current event in the change stream, or ``null`` if there is no +current event (i.e. :phpmethod:`MongoDB\ChangeStream::valid()` returns +``false``). + +Examples +-------- + +This example reports the index of events while iterating a change stream. + +.. code-block:: php + + test->inventory; + + $changeStream = $collection->watch(); + + for ($changeStream->rewind(); true; $changeStream->next()) { + if ( ! $changeStream->valid()) { + continue; + } + + $event = $changeStream->current(); + + printf("%d: %s\n", $changeStream->key(), $event['operationType']); + } + +Assuming that a document was inserted, updated, and deleted while the above +script was iterating the change stream, the output would then resemble: + +.. code-block:: none + + 0: insert + 1: update + 2: delete + +See Also +-------- + +- :phpmethod:`MongoDB\Client::watch()` +- :phpmethod:`MongoDB\Collection::watch()` +- :phpmethod:`MongoDB\Database::watch()` +- :php:`Iterator::key() ` +- :ref:`Tailable Cursor Iteration ` +- :manual:`Change Streams ` documentation in the MongoDB manual diff --git a/source/reference/method/MongoDBChangeStream-next.txt b/source/reference/method/MongoDBChangeStream-next.txt new file mode 100644 index 00000000..559ae4cb --- /dev/null +++ b/source/reference/method/MongoDBChangeStream-next.txt @@ -0,0 +1,44 @@ +============================= +MongoDB\\ChangeStream::next() +============================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\ChangeStream::next() + + Advances the change stream and attempts to load the next event. + + .. code-block:: php + + function next(): void + + .. note:: + + Advancing the change stream does not guarantee that there will be a + current event to access. You should still call + :phpmethod:`MongoDB\ChangeStream::valid()` to check for a current event + at each step of iteration. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +See Also +-------- + +- :phpmethod:`MongoDB\Client::watch()` +- :phpmethod:`MongoDB\Collection::watch()` +- :phpmethod:`MongoDB\Database::watch()` +- :php:`Iterator::next() ` +- :ref:`Tailable Cursor Iteration ` +- :manual:`Change Streams ` documentation in the MongoDB manual diff --git a/source/reference/method/MongoDBChangeStream-rewind.txt b/source/reference/method/MongoDBChangeStream-rewind.txt new file mode 100644 index 00000000..066e99aa --- /dev/null +++ b/source/reference/method/MongoDBChangeStream-rewind.txt @@ -0,0 +1,54 @@ +=============================== +MongoDB\\ChangeStream::rewind() +=============================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\ChangeStream::rewind() + + Rewinds the change stream and attempts to load the first event. + + .. code-block:: php + + function rewind(): void + + This method should be called at the start of change stream iteration. + + .. note:: + + Rewinding the change stream does not guarantee that there will be a + current event to access. You should still call + :phpmethod:`MongoDB\ChangeStream::valid()` to check for a current event + at each step of iteration. After initially rewinding the change stream, + :phpmethod:`MongoDB\ChangeStream::next()` should be used to iterate + further. + +Errors/Exceptions +----------------- + +:php:`MongoDB\Driver\Exception\LogicException +` if this method is called after a call +to :phpmethod:`MongoDB\ChangeStream::next()` (i.e. the underlying +:php:`MongoDB\Driver\Cursor ` has already been +advanced). + +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +See Also +-------- + +- :phpmethod:`MongoDB\Client::watch()` +- :phpmethod:`MongoDB\Collection::watch()` +- :phpmethod:`MongoDB\Database::watch()` +- :php:`Iterator::rewind() ` +- :ref:`Tailable Cursor Iteration ` +- :manual:`Change Streams ` documentation in the MongoDB manual diff --git a/source/reference/method/MongoDBChangeStream-valid.txt b/source/reference/method/MongoDBChangeStream-valid.txt new file mode 100644 index 00000000..bab45f1f --- /dev/null +++ b/source/reference/method/MongoDBChangeStream-valid.txt @@ -0,0 +1,42 @@ +============================== +MongoDB\\ChangeStream::valid() +============================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\ChangeStream::valid() + + Returns whether there is a current event in the change stream. + + .. code-block:: php + + function valid(): boolean + + When manually iterating the change stream using + :php:`Iterator ` methods, this method should + be used to determine if :phpmethod:`MongoDB\ChangeStream::current()` and + :phpmethod:`MongoDB\ChangeStream::key()` can be called. + +Return Values +------------- + +A boolean indicating whether there is a current event in the change stream. + +See Also +-------- + +- :phpmethod:`MongoDB\Client::watch()` +- :phpmethod:`MongoDB\Collection::watch()` +- :phpmethod:`MongoDB\Database::watch()` +- :php:`Iterator::valid() ` +- :ref:`Tailable Cursor Iteration ` +- :manual:`Change Streams ` documentation in the MongoDB manual diff --git a/source/reference/method/MongoDBClient-createClientEncryption.txt b/source/reference/method/MongoDBClient-createClientEncryption.txt new file mode 100644 index 00000000..ef0d2529 --- /dev/null +++ b/source/reference/method/MongoDBClient-createClientEncryption.txt @@ -0,0 +1,54 @@ +========================================= +MongoDB\\Client::createClientEncryption() +========================================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Client::createClientEncryption() + + Returns a :php:`MongoDB\Driver\ClientEncryption ` + object for manual encryption and decryption of values. + + .. code-block:: php + + function createClientEncryption(array $options): MongoDB\Driver\ClientEncryption + +Parameters +---------- + +``$options`` : array + An array specifying the desired options. Refer to the + :php:`MongoDB\Driver\Manager::createClientEncryption() ` + extension documentation for a list of supported options. + + If a :phpclass:`MongoDB\Client` is provided for the ``keyVaultClient`` + option, it will be unwrapped into a + :php:`MongoDB\Driver\Manager ` for the + extension. + +Return Values +------------- + +A :php:`MongoDB\Driver\ClientEncryption ` +instance which can be used to encrypt and decrypt values. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-invalidargumentexception.rst + +See Also +-------- + +- :php:`MongoDB\Driver\Manager::createClientEncryption() + ` diff --git a/source/reference/method/MongoDBClient-dropDatabase.txt b/source/reference/method/MongoDBClient-dropDatabase.txt new file mode 100644 index 00000000..9545ed49 --- /dev/null +++ b/source/reference/method/MongoDBClient-dropDatabase.txt @@ -0,0 +1,113 @@ +=============================== +MongoDB\\Client::dropDatabase() +=============================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Client::dropDatabase() + + Drop a database on the server. + + .. code-block:: php + + function dropDatabase(string $databaseName, array $options = []): array|object + +Parameters +---------- + +``$databaseName`` : string + The name of the database to drop. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.13 + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + .. versionadded:: 1.3 + + * - typeMap + - array + - .. include:: /includes/extracts/client-option-typeMap.rst + + This will be used for the returned command result document. + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - .. include:: /includes/extracts/client-option-writeConcern.rst + +Return Values +------------- + +An array or object with the result document of the :manual:`dropDatabase +` command. The return type will depend on the +``typeMap`` option. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Example +------- + +The following example drops the ``test`` database: + +.. code-block:: php + + dropDatabase('test'); + + var_dump($result); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Model\BSONDocument)#8 (1) { + ["storage":"ArrayObject":private]=> + array(2) { + ["dropped"]=> + string(4) "test" + ["ok"]=> + float(1) + } + } + +See Also +-------- + +- :phpmethod:`MongoDB\Database::drop()` +- :manual:`dropDatabase ` command reference in + the MongoDB manual diff --git a/source/reference/method/MongoDBClient-getManager.txt b/source/reference/method/MongoDBClient-getManager.txt new file mode 100644 index 00000000..9618beca --- /dev/null +++ b/source/reference/method/MongoDBClient-getManager.txt @@ -0,0 +1,35 @@ +============================= +MongoDB\\Client::getManager() +============================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Client::getManager() + + Accessor for the + :php:`MongoDB\Driver\Manager ` used by this + :phpclass:`Client `. + + .. code-block:: php + + function getManager(): MongoDB\Manager + +Return Values +------------- + +A :php:`MongoDB\Driver\Manager ` object. + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::getManager()` +- :phpmethod:`MongoDB\Database::getManager()` diff --git a/source/reference/method/MongoDBClient-getReadConcern.txt b/source/reference/method/MongoDBClient-getReadConcern.txt new file mode 100644 index 00000000..89643bd5 --- /dev/null +++ b/source/reference/method/MongoDBClient-getReadConcern.txt @@ -0,0 +1,60 @@ +================================= +MongoDB\\Client::getReadConcern() +================================= + +.. versionadded:: 1.2 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Client::getReadConcern() + + Returns the read concern for this client. + + .. code-block:: php + + function getReadConcern(): MongoDB\Driver\ReadConcern + +Return Values +------------- + +A :php:`MongoDB\Driver\ReadConcern ` object. + +Example +------- + +.. code-block:: php + + 'majority', + ]); + + var_dump($client->getReadConcern()); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Driver\ReadConcern)#5 (1) { + ["level"]=> + string(8) "majority" + } + +See Also +-------- + +- :manual:`Read Concern ` in the MongoDB manual +- :php:`MongoDB\Driver\ReadConcern::isDefault() ` +- :phpmethod:`MongoDB\Collection::getReadConcern()` +- :phpmethod:`MongoDB\Database::getReadConcern()` +- :phpmethod:`MongoDB\GridFS\Bucket::getReadConcern()` diff --git a/source/reference/method/MongoDBClient-getReadPreference.txt b/source/reference/method/MongoDBClient-getReadPreference.txt new file mode 100644 index 00000000..564d108f --- /dev/null +++ b/source/reference/method/MongoDBClient-getReadPreference.txt @@ -0,0 +1,60 @@ +==================================== +MongoDB\\Client::getReadPreference() +==================================== + +.. versionadded:: 1.2 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Client::getReadPreference() + + Returns the read preference for this client. + + .. code-block:: php + + function getReadPreference(): MongoDB\Driver\ReadPreference + +Return Values +------------- + +A :php:`MongoDB\Driver\ReadPreference ` +object. + +Example +------- + +.. code-block:: php + + 'primaryPreferred', + ]); + + var_dump($client->getReadPreference()); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Driver\ReadPreference)#5 (1) { + ["mode"]=> + string(16) "primaryPreferred" + } + +See Also +-------- + +- :manual:`Read Preference ` in the MongoDB manual +- :phpmethod:`MongoDB\Collection::getReadPreference()` +- :phpmethod:`MongoDB\Database::getReadPreference()` +- :phpmethod:`MongoDB\GridFS\Bucket::getReadPreference()` diff --git a/source/reference/method/MongoDBClient-getTypeMap.txt b/source/reference/method/MongoDBClient-getTypeMap.txt new file mode 100644 index 00000000..89c620af --- /dev/null +++ b/source/reference/method/MongoDBClient-getTypeMap.txt @@ -0,0 +1,67 @@ +============================= +MongoDB\\Client::getTypeMap() +============================= + +.. versionadded:: 1.2 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Client::getTypeMap() + + Returns the type map for this client. + + .. code-block:: php + + function getTypeMap(): array + +Return Values +------------- + +A :ref:`type map ` array. + +Example +------- + +.. code-block:: php + + [ + 'root' => 'array', + 'document' => 'array', + 'array' => 'array', + ], + ]); + + var_dump($client->getTypeMap()); + +The output would then resemble: + +.. code-block:: none + + array(3) { + ["root"]=> + string(5) "array" + ["document"]=> + string(5) "array" + ["array"]=> + string(5) "array" + } + +See Also +-------- + +- :doc:`/reference/bson` +- :phpmethod:`MongoDB\Collection::getTypeMap()` +- :phpmethod:`MongoDB\Database::getTypeMap()` +- :phpmethod:`MongoDB\GridFS\Bucket::getTypeMap()` diff --git a/source/reference/method/MongoDBClient-getWriteConcern.txt b/source/reference/method/MongoDBClient-getWriteConcern.txt new file mode 100644 index 00000000..270707f0 --- /dev/null +++ b/source/reference/method/MongoDBClient-getWriteConcern.txt @@ -0,0 +1,61 @@ +================================== +MongoDB\\Client::getWriteConcern() +================================== + +.. versionadded:: 1.2 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Client::getWriteConcern() + + Returns the write concern for this client. + + .. code-block:: php + + function getWriteConcern(): MongoDB\Driver\WriteConcern + +Return Values +------------- + +A :php:`MongoDB\Driver\WriteConcern ` +object. + +Example +------- + +.. code-block:: php + + true, + ]); + + var_dump($client->getWriteConcern()); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Driver\WriteConcern)#4 (1) { + ["j"]=> + bool(true) + } + +See Also +-------- + +- :manual:`Write Concern ` in the MongoDB manual +- :php:`MongoDB\Driver\WriteConcern::isDefault() ` +- :phpmethod:`MongoDB\Collection::getWriteConcern()` +- :phpmethod:`MongoDB\Database::getWriteConcern()` +- :phpmethod:`MongoDB\GridFS\Bucket::getWriteConcern()` diff --git a/source/reference/method/MongoDBClient-listDatabaseNames.txt b/source/reference/method/MongoDBClient-listDatabaseNames.txt new file mode 100644 index 00000000..bdb7e095 --- /dev/null +++ b/source/reference/method/MongoDBClient-listDatabaseNames.txt @@ -0,0 +1,120 @@ +==================================== +MongoDB\\Client::listDatabaseNames() +==================================== + +.. versionadded:: 1.7 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Client::listDatabaseNames() + + Returns names for all databases on the server. + + .. code-block:: php + + function listDatabaseNames(array $options = []): Iterator + +Parameters +---------- + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - authorizedDatabases + - boolean + - A flag that determines which databases are returned based on the user + privileges when access control is enabled. For more information, see the + `listDatabases command documentation `_. + + For servers < 4.0.5, this option is ignored. + + .. versionadded:: 1.7 + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.13 + + * - filter + - array|object + - A query expression to filter the list of databases. + + You can specify a query expression for database fields (e.g. ``name``, + ``sizeOnDisk``, ``empty``). + + .. versionadded:: 1.3 + + * - maxTimeMS + - integer + - .. include:: /includes/extracts/common-option-maxTimeMS.rst + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + .. versionadded:: 1.3 + +Return Values +------------- + +An :php:`Iterator `, which provides the name of each +database on the server. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unexpectedvalueexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Example +------- + +The following example lists all databases on the server: + +.. code-block:: php + + listDatabaseNames() as $databaseName) { + var_dump($databaseName); + } + +The output would then resemble: + +.. code-block:: none + + string(5) "local" + string(4) "test" + +See Also +-------- + +- :phpmethod:`MongoDB\Client::listDatabases()` +- :manual:`listDatabases ` command reference + in the MongoDB manual +- `Enumerating Databases + `_ + specification diff --git a/source/reference/method/MongoDBClient-listDatabases.txt b/source/reference/method/MongoDBClient-listDatabases.txt new file mode 100644 index 00000000..93a4d65a --- /dev/null +++ b/source/reference/method/MongoDBClient-listDatabases.txt @@ -0,0 +1,135 @@ +================================ +MongoDB\\Client::listDatabases() +================================ + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Client::listDatabases() + + Returns information for all databases on the server. + + .. code-block:: php + + function listDatabases(array $options = []): MongoDB\Model\DatabaseInfoIterator + +Parameters +---------- + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - authorizedDatabases + - boolean + - A flag that determines which databases are returned based on the user + privileges when access control is enabled. For more information, see the + `listDatabases command documentation `_. + + For servers < 4.0.5, this option is ignored. + + .. versionadded:: 1.7 + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.13 + + * - filter + - array|object + - A query expression to filter the list of databases. + + You can specify a query expression for database fields (e.g. ``name``, + ``sizeOnDisk``, ``empty``). + + .. versionadded:: 1.3 + + * - maxTimeMS + - integer + - .. include:: /includes/extracts/common-option-maxTimeMS.rst + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + .. versionadded:: 1.3 + + + +Return Values +------------- + +A traversable :phpclass:`MongoDB\Model\DatabaseInfoIterator`, which contains +a :phpclass:`MongoDB\Model\DatabaseInfo` object for each database on the +server. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unexpectedvalueexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Example +------- + +The following example lists all databases on the server: + +.. code-block:: php + + listDatabases() as $databaseInfo) { + var_dump($databaseInfo); + } + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Model\DatabaseInfo)#4 (3) { + ["name"]=> + string(5) "local" + ["sizeOnDisk"]=> + float(65536) + ["empty"]=> + bool(false) + } + object(MongoDB\Model\DatabaseInfo)#7 (3) { + ["name"]=> + string(4) "test" + ["sizeOnDisk"]=> + float(32768) + ["empty"]=> + bool(false) + } + +See Also +-------- + +- :phpmethod:`MongoDB\Client::listDatabaseNames()` +- :manual:`listDatabases ` command reference + in the MongoDB manual +- `Enumerating Databases + `_ + specification diff --git a/source/reference/method/MongoDBClient-selectCollection.txt b/source/reference/method/MongoDBClient-selectCollection.txt new file mode 100644 index 00000000..c1984500 --- /dev/null +++ b/source/reference/method/MongoDBClient-selectCollection.txt @@ -0,0 +1,126 @@ +=================================== +MongoDB\\Client::selectCollection() +=================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Client::selectCollection() + + Selects a collection on the server. + + .. code-block:: php + + function selectCollection( + string $databaseName, + string $collectionName, + array $options = [] + ): MongoDB\Collection + +Parameters +---------- + +``$databaseName`` : string + The name of the database containing the collection to select. + +``$collectionName`` : string + The name of the collection to select. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - codec + - MongoDB\\Codec\\DocumentCodec + - The default :doc:`codec ` to use for collection + operations. + + .. versionadded:: 1.17 + + * - readConcern + - :php:`MongoDB\Driver\ReadConcern ` + - The default read concern to use for collection operations. Defaults to + the client's read concern. + + * - readPreference + - :php:`MongoDB\Driver\ReadPreference ` + - The default read preference to use for collection operations. Defaults + to the client's read preference. + + * - typeMap + - array + - The default type map to use for collection operations. Defaults to the + client's type map. + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - The default write concern to use for collection operations. Defaults to + the client's write concern. + +Return Values +------------- + +A :phpclass:`MongoDB\Collection` object. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-invalidargumentexception.rst + +Behavior +-------- + +The selected collection inherits options such as read preference and type +mapping from the :phpclass:`Client ` object. Options may be +overridden via the ``$options`` parameter. + +Example +------- + +The following example selects the ``users`` collection in the ``test`` database: + +.. code-block:: php + + selectCollection('test', 'users'); + +The following example selects the ``users`` collection in the ``test`` database +with a custom read preference: + +.. code-block:: php + + selectCollection( + 'test', + 'users', + [ + 'readPreference' => new MongoDB\Driver\ReadPreference('primaryPreferred'), + ] + ); + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::__construct()` +- :phpmethod:`MongoDB\Database::selectCollection()` diff --git a/source/reference/method/MongoDBClient-selectDatabase.txt b/source/reference/method/MongoDBClient-selectDatabase.txt new file mode 100644 index 00000000..33c7ec32 --- /dev/null +++ b/source/reference/method/MongoDBClient-selectDatabase.txt @@ -0,0 +1,114 @@ +================================= +MongoDB\\Client::selectDatabase() +================================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Client::selectDatabase() + + Selects a database on the server. + + .. code-block:: php + + function selectDatabase( + string $databaseName, + array $options = [] + ): MongoDB\Database + +Parameters +---------- + +``$databaseName`` : string + The name of the database to select. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - readConcern + - :php:`MongoDB\Driver\ReadConcern ` + - The default read concern to use for database operations. Defaults to + the client's read concern. + + * - readPreference + - :php:`MongoDB\Driver\ReadPreference ` + - The default read preference to use for database operations. Defaults to + the client's read preference. + + * - typeMap + - array + - The default type map to use for database operations. Defaults to the + client's type map. + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - The default write concern to use for database operations. Defaults to + the client's write concern. + +Return Values +------------- + +A :phpclass:`MongoDB\Database` object. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-invalidargumentexception.rst + +Behavior +-------- + +The selected database inherits options such as read preference and type mapping +from the :phpclass:`Client ` object. Options may be overridden +via the ``$options`` parameter. + +Example +------- + +The following example selects the ``test`` database: + +.. code-block:: php + + selectDatabase('test'); + +The following examples selects the ``test`` database with a custom read +preference: + +.. code-block:: php + + selectDatabase( + 'test', + [ + 'readPreference' => new MongoDB\Driver\ReadPreference('primaryPreferred'), + ] + ); + +See Also +-------- + +- :phpmethod:`MongoDB\Client::__get()` +- :phpmethod:`MongoDB\Database::__construct()` diff --git a/source/reference/method/MongoDBClient-startSession.txt b/source/reference/method/MongoDBClient-startSession.txt new file mode 100644 index 00000000..0e3d8eb1 --- /dev/null +++ b/source/reference/method/MongoDBClient-startSession.txt @@ -0,0 +1,88 @@ +=============================== +MongoDB\\Client::startSession() +=============================== + +.. versionadded:: 1.3 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Client::startSession() + + Start a new client session for use with this client. + + .. code-block:: php + + function startSession(array $options = []): MongoDB\Driver\Session + +Parameters +---------- + +``$options`` : array + An array specifying the desired options. Refer to the + :php:`MongoDB\Driver\Manager::startSession() ` + extension documentation for a list of supported options. + +Return Values +------------- + +A :php:`MongoDB\Driver\Session ` object. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-driver-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Example +------- + +The following example starts a new session: + +.. code-block:: php + + startSession(); + + var_dump($session); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Driver\Session)#2043 (4) { + ["logicalSessionId"]=> + array(1) { + ["id"]=> + object(MongoDB\BSON\Binary)#225 (2) { + ["data"]=> + string(16) "................" + ["type"]=> + int(4) + } + } + ["clusterTime"]=> + NULL + ["causalConsistency"]=> + bool(true) + ["operationTime"]=> + NULL + } + +See Also +-------- + +- :php:`MongoDB\Driver\Manager::startSession() + ` +- :ref:`Causal Consistency ` in the MongoDB manual diff --git a/source/reference/method/MongoDBClient-watch.txt b/source/reference/method/MongoDBClient-watch.txt new file mode 100644 index 00000000..336f38cc --- /dev/null +++ b/source/reference/method/MongoDBClient-watch.txt @@ -0,0 +1,204 @@ +======================== +MongoDB\\Client::watch() +======================== + +.. versionadded:: 1.4 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Client::watch() + + Executes a :manual:`change stream ` operation on the client. + The change stream can be watched for cluster-level changes. + + .. code-block:: php + + function watch( + array $pipeline = [], + array $options = [] + ): MongoDB\ChangeStream + +Parameters +---------- + +``$pipeline`` : array|object + The pipeline of stages to append to an initial ``$changeStream`` stage. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - batchSize + - integer + - .. include:: /includes/extracts/watch-option-batchSize.rst + + * - codec + - MongoDB\\Codec\\DocumentCodec + - .. include:: /includes/extracts/common-option-codec.rst + + .. versionadded:: 1.17 + + * - collation + - array|object + - .. include:: /includes/extracts/common-option-collation.rst + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/common-option-comment-string-before-4.4.rst + + .. versionadded:: 1.13 + + * - fullDocument + - string + - .. include:: /includes/extracts/watch-option-fullDocument.rst + + * - fullDocumentBeforeChange + - string + - .. include:: /includes/extracts/watch-option-fullDocumentBeforeChange.rst + + * - maxAwaitTimeMS + - integer + - .. include:: /includes/extracts/watch-option-maxAwaitTimeMS.rst + + * - readConcern + - :php:`MongoDB\Driver\ReadConcern ` + - .. include:: /includes/extracts/client-option-readConcern.rst + + * - readPreference + - :php:`MongoDB\Driver\ReadPreference ` + - .. include:: /includes/extracts/client-option-readPreference.rst + + This is used for both the initial change stream aggregation and for + server selection during an automatic resume. + + * - resumeAfter + - array|object + - .. include:: /includes/extracts/watch-option-resumeAfter.rst + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + * - showExpandedEvents + - boolean + - .. include:: /includes/extracts/watch-option-showExpandedEvents.rst + + * - startAfter + - array|object + - .. include:: /includes/extracts/watch-option-startAfter.rst + + * - startAtOperationTime + - :php:`MongoDB\BSON\TimestampInterface ` + - .. include:: /includes/extracts/watch-option-startAtOperationTime.rst + + * - typeMap + - array + - .. include:: /includes/extracts/client-option-typeMap.rst + +Return Values +------------- + +A :phpclass:`MongoDB\ChangeStream` object, which allows for iteration of +events in the change stream via the :php:`Iterator ` interface. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unexpectedvalueexception.rst +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Examples +-------- + +This example reports events while iterating a change stream. + +.. code-block:: php + + watch(); + + for ($changeStream->rewind(); true; $changeStream->next()) { + if ( ! $changeStream->valid()) { + continue; + } + + $event = $changeStream->current(); + + if ($event['operationType'] === 'invalidate') { + break; + } + + $ns = sprintf('%s.%s', $event['ns']['db'], $event['ns']['coll']); + $id = json_encode($event['documentKey']['_id']); + + switch ($event['operationType']) { + case 'delete': + printf("Deleted document in %s with _id: %s\n\n", $ns, $id); + break; + + case 'insert': + printf("Inserted new document in %s\n", $ns); + echo json_encode($event['fullDocument']), "\n\n"; + break; + + case 'replace': + printf("Replaced new document in %s with _id: %s\n", $ns, $id); + echo json_encode($event['fullDocument']), "\n\n"; + break; + + case 'update': + printf("Updated document in %s with _id: %s\n", $ns, $id); + echo json_encode($event['updateDescription']), "\n\n"; + break; + } + } + +Assuming that a document was inserted, updated, and deleted while the above +script was iterating the change stream, the output would then resemble: + +.. code-block:: none + + Inserted new document in app.user + {"_id":{"$oid":"5b329b6674083047cc05e607"},"username":"bob"} + + Inserted new document in app.products + {"_id":{"$oid":"5b329b6a74083047cc05e608"},"name":"Widget","quantity":5} + + Inserted new document in logs.messages + {"_id":{"$oid":"5b329b7374083047cc05e609"},"msg":"bob purchased a widget"} + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::watch()` +- :phpmethod:`MongoDB\Database::watch()` +- :manual:`Aggregation Pipeline ` documentation in + the MongoDB Manual +- :manual:`Change Streams ` documentation in the MongoDB manual +- :manual:`Change Events ` documentation in the + MongoDB manual diff --git a/source/reference/method/MongoDBClient__construct.txt b/source/reference/method/MongoDBClient__construct.txt new file mode 100644 index 00000000..79e5daa8 --- /dev/null +++ b/source/reference/method/MongoDBClient__construct.txt @@ -0,0 +1,340 @@ +============================== +MongoDB\\Client::__construct() +============================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Client::__construct() + + Constructs a new :phpclass:`Client ` instance. + + .. code-block:: php + + function __construct( + ?string $uri = null, + array $uriOptions = [], + array $driverOptions = [] + ) + +Parameters +---------- + +``$uri`` : string + The MongoDB connection string. Refer to + :manual:`Connection Strings ` in the MongoDB + manual for more information. + + Defaults to ``"mongodb://127.0.0.1:27017"`` if unspecified. + + Any special characters in the URI components need to be encoded according to + `RFC 3986 `_. This is particularly + relevant to the username and password, which can often include special + characters such as ``@``, ``:``, or ``%``. When connecting via a Unix domain + socket, the socket path may contain special characters such as slashes and + must be encoded. The :php:`rawurlencode() ` function may be used + to encode constituent parts of the URI. + +``$uriOptions`` : array + Specifies additional URI options, such as authentication credentials or query + string parameters. The options specified in ``$uriOptions`` take precedence + over any analogous options present in the ``$uri`` string and do not need to + be encoded according to `RFC 3986 `_. + + Refer to the :php:`MongoDB\Driver\Manager::__construct() + ` extension documentation for a list of + supported options. + +``$driverOptions`` : array + Specifies options specific to the PHP driver. In addition to driver options + supported by the :php:`extension `, the library + additionally supports specifying a default + :php:`type map ` + to apply to the cursors it creates. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - autoEncryption + - array + - Options to configure client-side field-level encryption in the driver. + Refer to the + :php:`extension documentation ` + for a list of supported encryption options. + + If a :phpclass:`MongoDB\Client` is provided for the ``keyVaultClient`` + option, it will be unwrapped into a + :php:`MongoDB\Driver\Manager ` for the + extension. + + .. versionadded:: 1.6 + + * - driver + - array + - Additional driver metadata to be passed on to the server handshake. + This is an array containing ``name``, ``version``, and ``platform`` + string fields. For example: + + .. code-block:: php + + [ + 'name' => 'my-driver', + 'version' => '1.2.3-dev', + 'platform' => 'some-platform', + ] + + .. note:: + + This feature is primarily designed for custom drivers and ODMs, + which may want to identify themselves to the server for diagnostic + purposes. Applications wishing to identify themselves should use the + ``appName`` URI option instead of this option. + + .. versionadded:: 1.7 + + * - serverApi + - :php:`MongoDB\Driver\ServerApi ` + - Used to declare an API version on the client. Refer to the + :manual:`Stable API ` page in the Server manual for + additional information. + + .. versionadded:: 1.9 + + * - typeMap + - array + - Default :php:`type map ` + to apply to cursors, which determines how BSON documents are converted + to PHP values. The library uses the following type map by default: + + .. code-block:: php + + [ + 'array' => 'MongoDB\Model\BSONArray', + 'document' => 'MongoDB\Model\BSONDocument', + 'root' => 'MongoDB\Model\BSONDocument', + ] + + * - allow_invalid_hostname + - boolean + - Disables hostname validation if ``true``. Defaults to ``false``. + + Allowing invalid hostnames may expose the driver to a + `man-in-the-middle attack `__. + + .. deprecated:: 1.6 + + This option has been deprecated. Use the + ``tlsAllowInvalidHostnames`` URI option instead. + + * - ca_dir + - string + - Path to a correctly hashed certificate directory. The system + certificate store will be used by default. + + Falls back to the deprecated ``capath`` SSL context option if not + specified. + + * - ca_file + - string + - Path to a certificate authority file. The system certificate store will + be used by default. + + Falls back to the deprecated ``cafile`` SSL context option if not + specified. + + .. deprecated:: 1.6 + + This option has been deprecated. Use the ``tlsCAFile`` URI option + instead. + + * - crl_file + - string + - Path to a certificate revocation list file. + + * - pem_file + - string + - Path to a PEM encoded certificate to use for client authentication. + + Falls back to the deprecated ``local_cert`` SSL context option if not + specified. + + .. deprecated:: 1.6 + + This option has been deprecated. Use the ``tlsCertificateKeyFile`` + URI option instead. + + * - pem_pwd + - string + - Passphrase for the PEM encoded certificate (if applicable). + + Falls back to the deprecated ``passphrase`` SSL context option if not + specified. + + .. deprecated:: 1.6 + + This option has been deprecated. Use the + ``tlsCertificateKeyFilePassword`` URI option instead. + + * - weak_cert_validation + - boolean + - Disables certificate validation ``true``. Defaults to ``false``. + + Falls back to the deprecated ``allow_self_signed`` SSL context option + if not specified. + + .. deprecated:: 1.6 + + This option has been deprecated. Use the + ``tlsAllowInvalidCertificates`` URI option instead. + + * - context + - resource + - :php:`SSL context options ` to be used as + fallbacks for other driver options (as specified). Note that the driver + does not consult the default stream context. + + This option is supported for backwards compatibility, but should be + considered deprecated. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Behavior +-------- + +A :php:`MongoDB\Driver\Manager ` is constructed +internally. Per the `Server Discovery and Monitoring +`_ +specification, :php:`MongoDB\Driver\Manager::__construct() +` performs no I/O. Connections will be +initialized on demand, when the first operation is executed. + +Examples +-------- + +.. start-connecting-include + +Connecting to a Standalone server +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If you do not specify a ``$uri`` value, the driver connects to a standalone +:program:`mongod` on ``127.0.0.1`` via port ``27017``. To connect to a different +server, pass the corresponding connection string as the first parameter when +creating the :phpclass:`Client ` instance: + +.. code-block:: php + + 'secondaryPreferred', + ] + ); + +Connecting with SSL and Authentication +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following example demonstrates how to connect to a MongoDB replica set with +SSL and authentication, as is used for `MongoDB Atlas +`_: + +.. code-block:: php + + 'myUsername', + 'password' => 'myPassword', + 'ssl' => true, + 'replicaSet' => 'myReplicaSet', + 'authSource' => 'admin', + ], + ); + +The driver supports additional :php:`SSL options +`, +which may be specified in the constructor's ``$driverOptions`` parameter. Those +options are covered in the :php:`MongoDB\Driver\Manager::__construct() +` documentation. + +.. end-connecting-include + +Specifying a Custom Type Map +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +By default, the |php-library| deserializes BSON documents and arrays +as :phpclass:`MongoDB\Model\BSONDocument` and +:phpclass:`MongoDB\Model\BSONArray` objects, respectively. The following +example demonstrates how to have the library unserialize everything as a PHP +array, as was done in the legacy ``mongo`` extension. + +.. code-block:: php + + [ + 'root' => 'array', + 'document' => 'array', + 'array' => 'array', + ], + ] + ); + +See Also +-------- + +- :php:`MongoDB\Driver\Manager::__construct() + ` +- :manual:`Connection String URI Format ` in the + MongoDB manual +- `Server Discovery and Monitoring + `_ + specification diff --git a/source/reference/method/MongoDBClient__get.txt b/source/reference/method/MongoDBClient__get.txt new file mode 100644 index 00000000..d391b12a --- /dev/null +++ b/source/reference/method/MongoDBClient__get.txt @@ -0,0 +1,71 @@ +======================== +MongoDB\\Client::__get() +======================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Client::__get() + + Selects a database on the server. This :php:`magic method ` is + an alias for the :phpmethod:`selectDatabase() + ` method. + + .. code-block:: php + + function __get(string $databaseName): MongoDB\Database + +Parameters +---------- + +``$databaseName`` : string + The name of the database to select. + +Return Values +------------- + +A :phpclass:`MongoDB\Database` object. + +Behavior +-------- + +The selected database inherits options such as read preference and type mapping +from the :phpclass:`Client ` object. If you wish to override +any options, use the :phpmethod:`MongoDB\Client::selectDatabase()` method. + +.. note:: + + To select databases whose names contain special characters, such as + ``-``, use complex syntax, as in ``$client->{'that-database'}``. + + Alternatively, :phpmethod:`MongoDB\Client::selectDatabase()` supports + selecting databases whose names contain special characters. + +Examples +-------- + +The following example selects the ``test`` and ``another-app`` databases: + +.. code-block:: php + + test; + $anotherApp = $client->{'another-app'}; + +See Also +-------- + +- :phpmethod:`MongoDB\Client::selectDatabase()` +- :phpmethod:`MongoDB\Database::__construct()` +- :php:`Property Overloading ` in the PHP Manual diff --git a/source/reference/method/MongoDBCollection-aggregate.txt b/source/reference/method/MongoDBCollection-aggregate.txt new file mode 100644 index 00000000..acbbee08 --- /dev/null +++ b/source/reference/method/MongoDBCollection-aggregate.txt @@ -0,0 +1,194 @@ +================================ +MongoDB\\Collection::aggregate() +================================ + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::aggregate() + + Executes an :manual:`aggregation framework pipeline + ` operation on the collection. + + .. code-block:: php + + function aggregate( + array $pipeline, + array $options = [] + ): Traversable + +Parameters +---------- + +``$pipeline`` : array + Specifies an :manual:`aggregation pipeline ` + operation. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - allowDiskUse + - boolean + - Enables writing to temporary files. When set to ``true``, aggregation + stages can write data to the ``_tmp`` sub-directory in the ``dbPath`` + directory. + + * - batchSize + - integer + - Specifies the batch size for the cursor, which will apply to both the + initial ``aggregate`` command and any subsequent ``getMore`` commands. + This determines the maximum number of documents to return in each + response from the server. + + A batchSize of ``0`` is special in that and will only apply to the + initial ``aggregate`` command; subsequent ``getMore`` commands will use + the server's default batch size. This may be useful for quickly + returning a cursor or failure from ``aggregate`` without doing + significant server-side work. + + * - bypassDocumentValidation + - boolean + - If ``true``, allows the write operation to circumvent document level + validation. Defaults to ``false``. + + This only applies when using the :ref:`$out ` and + :ref:`$out ` stages. + + * - codec + - MongoDB\\Codec\\DocumentCodec + - .. include:: /includes/extracts/collection-option-codec.rst + + .. versionadded:: 1.17 + + * - collation + - array|object + - .. include:: /includes/extracts/collection-option-collation.rst + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + The comment can be any valid BSON type for server versions 4.4 and + above. Earlier server versions only support string values. + + .. versionadded:: 1.3 + + * - explain + - boolean + - Specifies whether or not to return the information on the processing of + the pipeline. + + .. versionadded:: 1.4 + + * - hint + - string|array|object + - .. include:: /includes/extracts/common-option-hint.rst + + .. versionadded:: 1.3 + + * - let + - array|object + - .. include:: /includes/extracts/common-option-let.rst + + .. versionadded:: 1.9 + + * - maxTimeMS + - integer + - .. include:: /includes/extracts/common-option-maxTimeMS.rst + + * - readConcern + - :php:`MongoDB\Driver\ReadConcern ` + - .. include:: /includes/extracts/collection-option-readConcern.rst + + .. include:: /includes/extracts/common-option-readConcern-transaction.rst + + * - readPreference + - :php:`MongoDB\Driver\ReadPreference ` + - .. include:: /includes/extracts/collection-option-readPreference.rst + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + .. versionadded:: 1.3 + + * - typeMap + - array + - .. include:: /includes/extracts/collection-option-typeMap.rst + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - .. include:: /includes/extracts/collection-option-writeConcern.rst + + .. include:: /includes/extracts/common-option-writeConcern-transaction.rst + + This only applies when a :ref:`$out ` or + :ref:`$merge ` stage is specified. + +Return Values +------------- + +A :php:`MongoDB\Driver\Cursor ` or +:php:`ArrayIterator ` object. In both cases, the return value +will be :php:`Traversable `. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unexpectedvalueexception.rst +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +.. _php-coll-agg-method-behavior: + +Behavior +-------- + +:phpmethod:`MongoDB\Collection::aggregate()`'s returns a +:php:`MongoDB\Driver\Cursor ` object. + +Examples +-------- + +The following aggregation example uses a collection called ``names`` and groups +the ``first_name`` field together, counts the total number of results in each +group, and sorts the results by name. + +.. code-block:: php + + test->names; + + $cursor = $collection->aggregate( + [ + ['$group' => ['_id' => '$first_name', 'name_count' => ['$sum' => 1]]], + ['$sort' => ['_id' => 1]], + ] + ); + +See Also +-------- + +- :phpmethod:`MongoDB\Database::aggregate()` +- :manual:`aggregate ` command reference in the + MongoDB manual +- :manual:`Aggregation Pipeline ` documentation in + the MongoDB Manual diff --git a/source/reference/method/MongoDBCollection-bulkWrite.txt b/source/reference/method/MongoDBCollection-bulkWrite.txt new file mode 100644 index 00000000..ad31f062 --- /dev/null +++ b/source/reference/method/MongoDBCollection-bulkWrite.txt @@ -0,0 +1,150 @@ +================================ +MongoDB\\Collection::bulkWrite() +================================ + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::bulkWrite() + + Executes multiple write operations. + + .. code-block:: php + + function bulkWrite( + array $operations, + array $options = [] + ): MongoDB\BulkWriteResult + +Parameters +---------- + +``$operations`` : array + An array containing the write operations to perform. + :phpmethod:`MongoDB\Collection::bulkWrite()` supports + :phpmethod:`MongoDB\Collection::deleteMany()`, + :phpmethod:`MongoDB\Collection::deleteOne()`, + :phpmethod:`MongoDB\Collection::insertOne()`, + :phpmethod:`MongoDB\Collection::replaceOne()`, + :phpmethod:`MongoDB\Collection::updateMany()`, and + :phpmethod:`MongoDB\Collection::updateOne()` operations in the + following array structure: + + .. code-block:: php + + [ + [ 'deleteMany' => [ $filter ] ], + [ 'deleteOne' => [ $filter ] ], + [ 'insertOne' => [ $document ] ], + [ 'replaceOne' => [ $filter, $replacement, $options ] ], + [ 'updateMany' => [ $filter, $update, $options ] ], + [ 'updateOne' => [ $filter, $update, $options ] ], + ] + + Arguments correspond to the respective operation methods. However, the + ``writeConcern`` option is specified as a top-level option to + :phpmethod:`MongoDB\Collection::bulkWrite()` instead of each individual + operation. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - bypassDocumentValidation + - boolean + - If ``true``, allows the write operation to circumvent document level + validation. Defaults to ``false``. + + * - codec + - MongoDB\\Codec\\DocumentCodec + - .. include:: /includes/extracts/collection-option-codec.rst + + Bulk writes use the codec for ``insertOne`` and ``replaceOne`` + operations. + + .. versionadded:: 1.17 + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.13 + + * - let + - array|object + - .. include:: /includes/extracts/common-option-let.rst + + .. versionadded:: 1.13 + + * - ordered + - boolean + - If ``true``: when a single write fails, the operation will stop without + performing the remaining writes and throw an exception. + + If ``false``: when a single write fails, the operation will continue + with the remaining writes, if any, and throw an exception. + + The default is ``true``. + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + .. versionadded:: 1.3 + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - .. include:: /includes/extracts/collection-option-writeConcern.rst + + .. include:: /includes/extracts/common-option-writeConcern-transaction.rst + +Return Values +------------- + +A :phpclass:`MongoDB\BulkWriteResult` object, which encapsulates a +:php:`MongoDB\Driver\WriteResult ` object. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-bulkwriteexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Behavior +-------- + +.. include:: /includes/extracts/bulkwriteexception-result.rst +.. include:: /includes/extracts/bulkwriteexception-ordered.rst + +.. todo: add output and examples + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::deleteMany()` +- :phpmethod:`MongoDB\Collection::deleteOne()` +- :phpmethod:`MongoDB\Collection::insertMany()` +- :phpmethod:`MongoDB\Collection::insertOne()` +- :phpmethod:`MongoDB\Collection::replaceOne()` +- :phpmethod:`MongoDB\Collection::updateMany()` +- :phpmethod:`MongoDB\Collection::updateOne()` +- :doc:`/tutorial/crud` diff --git a/source/reference/method/MongoDBCollection-count.txt b/source/reference/method/MongoDBCollection-count.txt new file mode 100644 index 00000000..388f5bda --- /dev/null +++ b/source/reference/method/MongoDBCollection-count.txt @@ -0,0 +1,131 @@ +============================ +MongoDB\\Collection::count() +============================ + +.. deprecated:: 1.4 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::count() + + Count the number of documents that match the filter criteria. + + .. code-block:: php + + function count( + array|object $filter = [], + array $options = [] + ): integer + +Parameters +---------- + +``$filter`` : array|object + The filter criteria that specifies the documents to count. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - collation + - array|object + - .. include:: /includes/extracts/collection-option-collation.rst + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.13 + + * - hint + - string|array|object + - .. include:: /includes/extracts/common-option-hint.rst + + .. versionchanged:: 1.2 + + If a document is provided, it is passed to the command as-is. + Previously, the library would convert the key pattern to an index + name. + + * - limit + - integer + - The maximum number of matching documents to return. + + * - maxTimeMS + - integer + - .. include:: /includes/extracts/common-option-maxTimeMS.rst + + * - readConcern + - :php:`MongoDB\Driver\ReadConcern ` + - .. include:: /includes/extracts/collection-option-readConcern.rst + + .. include:: /includes/extracts/common-option-readConcern-transaction.rst + + * - readPreference + - :php:`MongoDB\Driver\ReadPreference ` + - .. include:: /includes/extracts/collection-option-readPreference.rst + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + .. versionadded:: 1.3 + + * - skip + - integer + - The number of matching documents to skip before returning results. + +Return Values +------------- + +The number of documents matching the filter criteria. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unexpectedvalueexception.rst +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Behavior +-------- + +This method is deprecated and cannot be executed within a transaction. It has +always been implemented using the :manual:`count ` +command. The behavior of the ``count`` command differs depending on the options +passed to it and may or may not provide an accurate count. When no query filter +is provided, the ``count`` command provides an estimate using collection +metadata. Even when provided with a query filter the ``count`` command can +return inaccurate results with a sharded cluster if orphaned documents exist or +if a chunk migration is in progress. The +:phpmethod:`MongoDB\Collection::countDocuments()` method avoids these sharded +cluster problems entirely. + +.. include:: /includes/extracts/note-bson-comparison.rst + +See Also +-------- + +- :manual:`count ` command reference in the MongoDB + manual +- :phpmethod:`MongoDB\Collection::countDocuments()` +- :phpmethod:`MongoDB\Collection::estimatedDocumentCount()` diff --git a/source/reference/method/MongoDBCollection-countDocuments.txt b/source/reference/method/MongoDBCollection-countDocuments.txt new file mode 100644 index 00000000..dc344f2d --- /dev/null +++ b/source/reference/method/MongoDBCollection-countDocuments.txt @@ -0,0 +1,138 @@ +===================================== +MongoDB\\Collection::countDocuments() +===================================== + +.. versionadded:: 1.4 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::countDocuments() + + Count the number of documents that match the filter criteria. + + .. code-block:: php + + function countDocuments(array|object $filter = [], array $options = []): integer + +Parameters +---------- + +``$filter`` : array|object + The filter criteria that specifies the documents to count. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - collation + - array|object + - .. include:: /includes/extracts/collection-option-collation.rst + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/common-option-comment-string-before-4.4.rst + + * - hint + - string|array|object + - .. include:: /includes/extracts/common-option-hint.rst + + * - limit + - integer + - The maximum number of matching documents to return. + + * - maxTimeMS + - integer + - .. include:: /includes/extracts/common-option-maxTimeMS.rst + + * - readConcern + - :php:`MongoDB\Driver\ReadConcern ` + - .. include:: /includes/extracts/collection-option-readConcern.rst + + .. include:: /includes/extracts/common-option-readConcern-transaction.rst + + * - readPreference + - :php:`MongoDB\Driver\ReadPreference ` + - .. include:: /includes/extracts/collection-option-readPreference.rst + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + * - skip + - integer + - The number of matching documents to skip before returning results. + +Return Values +------------- + +The number of documents matching the filter criteria. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unexpectedvalueexception.rst +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Behavior +-------- + +Internally, this method uses the ``$group`` aggregation pipeline operator to +obtain the result. If a ``filter`` parameter is given, this is converted into +a ``$match`` pipeline operator. Optional ``$skip`` and ``$limit`` stages are +added between ``$match`` and ``group`` if present in the options. + +.. note:: + + This method counts documents on the server side. To obtain an approximate + total number of documents without filters, the + :phpmethod:`MongoDB\Collection::estimatedDocumentCount()` method can be + used. This method estimates the number of documents based on collection + metadata, thus sacrificing accuracy for performance. + +Since this method uses an aggregation pipeline, some query operators accepted +within a :phpmethod:`MongoDB\Collection::count()` ``filter`` cannot be used. +Consider the following alternatives to these restricted operators: + +.. list-table:: + :header-rows: 1 + + * - Restricted + - Alternative Syntax + + * - :query:`$near` + - :query:`$geoWithin` with :query:`$center` + + * - :query:`$nearSphere` + - :query:`$geoWithin` with :query:`$centerSphere` + + * - :query:`$where` + - :query:`$expr` + +.. include:: /includes/extracts/note-bson-comparison.rst + +.. todo: add output and examples + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::estimatedDocumentCount()` diff --git a/source/reference/method/MongoDBCollection-createIndex.txt b/source/reference/method/MongoDBCollection-createIndex.txt new file mode 100644 index 00000000..6a74a5bd --- /dev/null +++ b/source/reference/method/MongoDBCollection-createIndex.txt @@ -0,0 +1,207 @@ +================================== +MongoDB\\Collection::createIndex() +================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::createIndex() + + Create an index for the collection. + + .. code-block:: php + + function createIndex( + array|object $key, + array $options = [] + ): string + +Parameters +---------- + +``$key`` : array|object + Specifies the field or fields to index and the index order. + + For example, the following specifies a descending index on the ``username`` + field: + + .. code-block:: php + + [ 'username' => -1 ] + +``$options`` : array + An array specifying the desired options. + + The ``$options`` parameter accepts both index *and* command options. A + non-exhaustive list of index options follows. For a complete list of index + options, refer to the + :manual:`createIndexes ` command reference + in the MongoDB manual. + + **Index Options** (non-exhaustive) + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - collation + - array|object + - .. include:: /includes/extracts/collection-option-collation.rst + + * - expireAfterSeconds + - integer + - Creates a :manual:`TTL ` index. + + * - name + - string + - A name that uniquely identifies the index. By default, MongoDB creates + index names based on the key. + + * - partialFilterExpression + - array|object + - Creates a :manual:`partial ` index. + + * - sparse + - boolean + - Creates a :manual:`sparse ` index. + + * - unique + - boolean + - Creates a :manual:`unique ` index. + + **Command Options** + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.13 + + * - commitQuorum + - string|integer + - Specifies how many data-bearing members of a replica set, including the + primary, must complete the index builds successfully before the primary + marks the indexes as ready. + + This option accepts the same values for the ``w`` field in a write + concern plus ``"votingMembers"``, which indicates all voting + data-bearing nodes. + + This is not supported for server versions prior to 4.4 and will result + in an exception at execution time if used. + + .. versionadded:: 1.7 + + * - maxTimeMS + - integer + - .. include:: /includes/extracts/common-option-maxTimeMS.rst + + .. versionadded:: 1.3 + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + .. versionadded:: 1.3 + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - .. include:: /includes/extracts/collection-option-writeConcern.rst + + .. include:: /includes/extracts/common-option-writeConcern-transaction.rst + +Return Values +------------- + +The name of the created index as a string. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Examples +-------- + +Create a Compound Index +~~~~~~~~~~~~~~~~~~~~~~~ + +The following example creates a :manual:`compound index ` +on the ``borough`` and ``cuisine`` fields in the ``restaurants`` collection in +the ``test`` database. + +.. code-block:: php + + selectCollection('test', 'restaurants'); + + $indexName = $collection->createIndex(['borough' => 1, 'cuisine' => 1]); + + var_dump($indexName); + +The output would then resemble: + +.. code-block:: none + + string(19) "borough_1_cuisine_1" + +Create a Partial Index +~~~~~~~~~~~~~~~~~~~~~~ + +The following example adds a :manual:`partial index ` on +the ``borough`` field in the ``restaurants`` collection in the ``test`` +database. The partial index indexes only documents where the ``borough`` field +exists. + +.. code-block:: php + + selectCollection('test', 'restaurants'); + + $indexName = $collection->createIndex( + ['borough' => 1], + [ + 'partialFilterExpression' => [ + 'borough' => ['$exists' => true], + ], + ] + ); + + var_dump($indexName); + +The output would then resemble: + +.. code-block:: none + + string(9) "borough_1" + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::createIndexes()` +- :doc:`/tutorial/indexes` +- :manual:`createIndexes ` command reference + in the MongoDB manual +- :manual:`Index ` documentation in the MongoDB Manual diff --git a/source/reference/method/MongoDBCollection-createIndexes.txt b/source/reference/method/MongoDBCollection-createIndexes.txt new file mode 100644 index 00000000..85318b2d --- /dev/null +++ b/source/reference/method/MongoDBCollection-createIndexes.txt @@ -0,0 +1,173 @@ +==================================== +MongoDB\\Collection::createIndexes() +==================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::createIndexes() + + Create one or more indexes for the collection. + + .. code-block:: php + + function createIndexes( + array $indexes, + array $options = [] + ): string[] + +Parameters +---------- + +``$indexes`` : array + The indexes to create on the collection. + + For example, the following specifies a unique index on the ``username`` field + and a compound index on the ``email`` and ``createdAt`` fields: + + .. code-block:: php + + [ + [ 'key' => [ 'username' => -1 ], 'unique' => true ], + [ 'key' => [ 'email' => 1, 'createdAt' => 1 ] ], + ] + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.13 + + * - commitQuorum + - string|integer + - Specifies how many data-bearing members of a replica set, including the + primary, must complete the index builds successfully before the primary + marks the indexes as ready. + + This option accepts the same values for the ``w`` field in a write + concern plus ``"votingMembers"``, which indicates all voting + data-bearing nodes. + + This is not supported for server versions prior to 4.4 and will result + in an exception at execution time if used. + + .. versionadded:: 1.7 + + * - maxTimeMS + - integer + - .. include:: /includes/extracts/common-option-maxTimeMS.rst + + .. versionadded:: 1.3 + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + .. versionadded:: 1.3 + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - .. include:: /includes/extracts/collection-option-writeConcern.rst + + .. include:: /includes/extracts/common-option-writeConcern-transaction.rst + +Return Values +------------- + +The names of the created indexes as an array of strings. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Behavior +-------- + +``$indexes`` parameter +~~~~~~~~~~~~~~~~~~~~~~ + +The ``$indexes`` parameter is an array of index specification documents. Each +element in ``$indexes`` must itself be an array or object with a ``key`` field, +which corresponds to the ``$key`` parameter of :phpmethod:`createIndex() +`. The array or object may include other +fields that correspond to index options accepted by :phpmethod:`createIndex() +`. For a full list of the supported index +creation options, refer to the +:manual:`createIndexes ` command reference +in the MongoDB manual. + +For example, the following ``$indexes`` parameter creates two indexes. The first +is an ascending unique index on the ``username`` field and the second is a +2dsphere index on the ``loc`` field with a custom name: + +.. code-block:: none + + [ + [ 'key' => [ 'username' => 1 ], 'unique' => true ], + [ 'key' => [ 'loc' => '2dsphere' ], 'name' => 'geo_index' ], + ] + +Example +------- + +The following example creates two indexes on the ``restaurants`` collection in +the ``test`` database. One index is a compound index on the ``borough`` and +``cuisine`` fields and the other is 2dsphere index on the ``loc`` field with a +custom name. + +.. code-block:: php + + selectCollection('test', 'restaurants'); + + $indexNames = $collection->createIndexes([ + [ 'key' => [ 'borough' => 1, 'cuisine' => 1] ], + [ 'key' => [ 'loc' => '2dsphere'], 'name' => 'geo_index' ], + ]); + + var_dump($indexNames); + +The output would then resemble: + +.. code-block:: none + + array(2) { + [0]=> + string(19) "borough_1_cuisine_1" + [1]=> + string(9) "geo_index" + } + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::createIndex()` +- :doc:`/tutorial/indexes` +- :manual:`createIndexes ` command reference + in the MongoDB manual +- :manual:`Index ` documentation in the MongoDB Manual diff --git a/source/reference/method/MongoDBCollection-createSearchIndex.txt b/source/reference/method/MongoDBCollection-createSearchIndex.txt new file mode 100644 index 00000000..ae85f97f --- /dev/null +++ b/source/reference/method/MongoDBCollection-createSearchIndex.txt @@ -0,0 +1,116 @@ +======================================== +MongoDB\\Collection::createSearchIndex() +======================================== + +.. versionadded:: 1.17 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::createSearchIndex() + + Create an Atlas Search index for the collection. + + .. code-block:: php + + function createSearchIndex( + array|object $definition, + array $options = [] + ): string + + .. include:: /includes/extracts/note-atlas-search-requirement.rst + +Parameters +---------- + +``$definition`` : array|object + Document describing the index to create. For details on definition syntax, see + :manual:`Search Index Definition Syntax `. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + * - name + - string + - Name of the search index to create. + + You cannot create multiple indexes with the same name on a single + collection. If you do not specify a name, the index is named "default". + +Return Values +------------- + +The name of the created Atlas Search index as a string. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Behavior +-------- + +.. include:: /includes/extracts/note-atlas-search-async.rst + +Examples +-------- + +Create an Index with Dynamic Mappings +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following example creates an Atlas Search index using +`dynamic mappings `__ +to index all document fields containing +`supported data types `__. + +.. code-block:: php + + selectCollection('test', 'articles'); + + $indexName = $collection->createSearchIndex( + ['mappings' => ['dynamic' => true]], + ['name' => 'test-search-index'] + ); + + var_dump($indexName); + +The output would then resemble: + +.. code-block:: none + + string(17) "test-search-index" + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::createSearchIndexes()` +- :phpmethod:`MongoDB\Collection::dropSearchIndex()` +- :phpmethod:`MongoDB\Collection::listSearchIndexes()` +- :phpmethod:`MongoDB\Collection::updateSearchIndex()` +- :manual:`createSearchIndexes ` command + reference in the MongoDB manual +- `Atlas Search `__ documentation in the MongoDB Manual diff --git a/source/reference/method/MongoDBCollection-createSearchIndexes.txt b/source/reference/method/MongoDBCollection-createSearchIndexes.txt new file mode 100644 index 00000000..85d27d84 --- /dev/null +++ b/source/reference/method/MongoDBCollection-createSearchIndexes.txt @@ -0,0 +1,123 @@ +========================================== +MongoDB\\Collection::createSearchIndexes() +========================================== + +.. versionadded:: 1.17 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::createSearchIndexes() + + Create one or more Atlas Search indexes for the collection. + + .. code-block:: php + + function createSearchIndexes( + array $indexes, + array $options = [] + ): string + + .. include:: /includes/extracts/note-atlas-search-requirement.rst + +Parameters +---------- + +``$indexes`` : array + Array of documents describing the indexes to create. + + A required ``definition`` document field describes the index to create. For + details on definition syntax, see + :manual:`Search Index Definition Syntax `. + + An optional ``name`` string field specifies the name of the search index to + create. You cannot create multiple indexes with the same name on a single + collection. If you do not specify a name, the index is named "default". + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + +Return Values +------------- + +The names of the created Atlas Search indexes as an array of strings. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Behavior +-------- + +.. include:: /includes/extracts/note-atlas-search-async.rst + +Examples +-------- + +Create an Index with Dynamic Mappings +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following example creates an Atlas Search index using +`dynamic mappings `__ +to index all document fields containing +`supported data types `__. + +.. code-block:: php + + selectCollection('test', 'articles'); + + $indexNames = $collection->createSearchIndexes( + [ + [ + 'name' => 'test-search-index', + 'definition' => ['mappings' => ['dynamic' => true]], + ], + ] + ); + + var_dump($indexNames); + +The output would then resemble: + +.. code-block:: none + + array(1) { + [0]=> + string(17) "test-search-index" + } + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::createSearchIndex()` +- :phpmethod:`MongoDB\Collection::dropSearchIndex()` +- :phpmethod:`MongoDB\Collection::listSearchIndexes()` +- :phpmethod:`MongoDB\Collection::updateSearchIndex()` +- :manual:`createSearchIndexes ` command + reference in the MongoDB manual +- `Atlas Search `__ documentation in the MongoDB Manual diff --git a/source/reference/method/MongoDBCollection-deleteMany.txt b/source/reference/method/MongoDBCollection-deleteMany.txt new file mode 100644 index 00000000..b82b1c6b --- /dev/null +++ b/source/reference/method/MongoDBCollection-deleteMany.txt @@ -0,0 +1,134 @@ +================================= +MongoDB\\Collection::deleteMany() +================================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::deleteMany() + + Deletes all documents that match the filter criteria. + + .. code-block:: php + + function deleteMany( + array|object $filter, + array $options = [] + ): MongoDB\DeleteResult + +Parameters +---------- + +``$filter`` : array|object + The filter criteria that specifies the documents to delete. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - collation + - array|object + - .. include:: /includes/extracts/collection-option-collation.rst + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.13 + + * - hint + - string|array|object + - .. include:: /includes/extracts/common-option-hint.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.7 + + * - let + - array|object + - .. include:: /includes/extracts/common-option-let.rst + + .. versionadded:: 1.13 + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + .. versionadded:: 1.3 + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - .. include:: /includes/extracts/collection-option-writeConcern.rst + + .. include:: /includes/extracts/common-option-writeConcern-transaction.rst + +Return Values +------------- + +A :phpclass:`MongoDB\DeleteResult` object, which encapsulates a +:php:`MongoDB\Driver\WriteResult ` object. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-bulkwriteexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Behavior +-------- + +.. include:: /includes/extracts/note-bson-comparison.rst +.. include:: /includes/extracts/bulkwriteexception-result.rst + +Example +------- + +The following example deletes all of the documents in the ``users`` collection +that have ``"ny"`` as the value for the ``state`` field: + +.. code-block:: php + + test->users; + $collection->drop(); + + $collection->insertOne(['name' => 'Bob', 'state' => 'ny']); + $collection->insertOne(['name' => 'Alice', 'state' => 'ny']); + $deleteResult = $collection->deleteMany(['state' => 'ny']); + + printf("Deleted %d document(s)\n", $deleteResult->getDeletedCount()); + +The output would then resemble: + +.. code-block:: none + + Deleted 2 document(s) + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::deleteOne()` +- :phpmethod:`MongoDB\Collection::bulkWrite()` +- :doc:`/tutorial/crud` +- :manual:`delete ` command reference in the MongoDB + manual diff --git a/source/reference/method/MongoDBCollection-deleteOne.txt b/source/reference/method/MongoDBCollection-deleteOne.txt new file mode 100644 index 00000000..43209ebd --- /dev/null +++ b/source/reference/method/MongoDBCollection-deleteOne.txt @@ -0,0 +1,136 @@ +================================ +MongoDB\\Collection::deleteOne() +================================ + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::deleteOne() + + Deletes at most one document that matches the filter criteria. If multiple + documents match the filter criteria, only the :term:`first ` + matching document will be deleted. + + .. code-block:: php + + function deleteOne( + array|object $filter, + array $options = [] + ): MongoDB\DeleteResult + +Parameters +---------- + +``$filter`` : array|object + The filter criteria that specifies the documents to delete. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - collation + - array|object + - .. include:: /includes/extracts/collection-option-collation.rst + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.13 + + * - hint + - string|array|object + - .. include:: /includes/extracts/common-option-hint.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.7 + + * - let + - array|object + - .. include:: /includes/extracts/common-option-let.rst + + .. versionadded:: 1.13 + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + .. versionadded:: 1.3 + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - .. include:: /includes/extracts/collection-option-writeConcern.rst + + .. include:: /includes/extracts/common-option-writeConcern-transaction.rst + +Return Values +------------- + +A :phpclass:`MongoDB\DeleteResult` object, which encapsulates a +:php:`MongoDB\Driver\WriteResult ` object. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-bulkwriteexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Behavior +-------- + +.. include:: /includes/extracts/note-bson-comparison.rst +.. include:: /includes/extracts/bulkwriteexception-result.rst + +Example +------- + +The following example deletes one document in the ``users`` collection that has +has ``"ny"`` as the value for the ``state`` field: + +.. code-block:: php + + test->users; + $collection->drop(); + + $collection->insertOne(['name' => 'Bob', 'state' => 'ny']); + $collection->insertOne(['name' => 'Alice', 'state' => 'ny']); + $deleteResult = $collection->deleteOne(['state' => 'ny']); + + printf("Deleted %d document(s)\n", $deleteResult->getDeletedCount()); + +The output would then resemble: + +.. code-block:: none + + Deleted 1 document(s) + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::deleteMany()` +- :phpmethod:`MongoDB\Collection::bulkWrite()` +- :doc:`/tutorial/crud` +- :manual:`delete ` command reference in the MongoDB + manual diff --git a/source/reference/method/MongoDBCollection-distinct.txt b/source/reference/method/MongoDBCollection-distinct.txt new file mode 100644 index 00000000..f8bcd4b0 --- /dev/null +++ b/source/reference/method/MongoDBCollection-distinct.txt @@ -0,0 +1,321 @@ +=============================== +MongoDB\\Collection::distinct() +=============================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::distinct() + + Finds the distinct values for a specified field across the collection. + + .. code-block:: php + + function distinct( + string $fieldName, + array|object $filter = [], + array $options = [] + ): mixed[] + +Parameters +---------- + +``$fieldName`` : string + The field for which to return distinct values. + +``$filter`` : array|object + The filter criteria that specifies the documents from which to retrieve the + distinct values. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - collation + - array|object + - .. include:: /includes/extracts/collection-option-collation.rst + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.13 + + * - maxTimeMS + - integer + - .. include:: /includes/extracts/common-option-maxTimeMS.rst + + * - readConcern + - :php:`MongoDB\Driver\ReadConcern ` + - .. include:: /includes/extracts/collection-option-readConcern.rst + + .. include:: /includes/extracts/common-option-readConcern-transaction.rst + + * - readPreference + - :php:`MongoDB\Driver\ReadPreference ` + - .. include:: /includes/extracts/collection-option-readPreference.rst + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + .. versionadded:: 1.3 + + * - typeMap + - array + - .. include:: /includes/extracts/collection-option-typeMap.rst + + .. versionadded:: 1.5 + +Return Values +------------- + +An array of the distinct values. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unexpectedvalueexception.rst +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Behavior +-------- + +.. include:: /includes/extracts/note-bson-comparison.rst + +Examples +-------- + +Return Distinct Values for a Field +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following example identifies the distinct values for the ``borough`` field +in the ``restaurants`` collection in the ``test`` database. + +.. code-block:: php + + test->restaurants; + + $distinct = $collection->distinct('borough'); + + var_dump($distinct); + +The output would then resemble: + +.. code-block:: none + + array(6) { + [0]=> + string(5) "Bronx" + [1]=> + string(8) "Brooklyn" + [2]=> + string(9) "Manhattan" + [3]=> + string(7) "Missing" + [4]=> + string(6) "Queens" + [5]=> + string(13) "Staten Island" + } + +Return Distinct Values Using a Filter +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following example identifies the distinct values for the ``cuisine`` field +in the ``restaurants`` collection in the ``test`` database for documents where +the ``borough`` is ``Queens``: + +.. code-block:: php + + test->restaurants; + + $distinct = $collection->distinct('cuisine', ['borough' => 'Queens']); + + var_dump($distinct); + +The output would then resemble: + +.. code-block:: none + + array(75) { + [0]=> + string(6) "Afghan" + [1]=> + string(7) "African" + [2]=> + string(9) "American " + [3]=> + string(8) "Armenian" + [4]=> + string(5) "Asian" + [5]=> + string(10) "Australian" + [6]=> + string(15) "Bagels/Pretzels" + [7]=> + string(6) "Bakery" + [8]=> + string(11) "Bangladeshi" + [9]=> + string(8) "Barbecue" + [10]=> + string(55) "Bottled beverages, including water, sodas, juices, etc." + [11]=> + string(9) "Brazilian" + [12]=> + string(4) "Cafe" + [13]=> + string(16) "Café/Coffee/Tea" + [14]=> + string(5) "Cajun" + [15]=> + string(9) "Caribbean" + [16]=> + string(7) "Chicken" + [17]=> + string(7) "Chinese" + [18]=> + string(13) "Chinese/Cuban" + [19]=> + string(16) "Chinese/Japanese" + [20]=> + string(11) "Continental" + [21]=> + string(6) "Creole" + [22]=> + string(5) "Czech" + [23]=> + string(12) "Delicatessen" + [24]=> + string(6) "Donuts" + [25]=> + string(16) "Eastern European" + [26]=> + string(8) "Egyptian" + [27]=> + string(7) "English" + [28]=> + string(8) "Filipino" + [29]=> + string(6) "French" + [30]=> + string(17) "Fruits/Vegetables" + [31]=> + string(6) "German" + [32]=> + string(5) "Greek" + [33]=> + string(10) "Hamburgers" + [34]=> + string(16) "Hotdogs/Pretzels" + [35]=> + string(31) "Ice Cream, Gelato, Yogurt, Ices" + [36]=> + string(6) "Indian" + [37]=> + string(10) "Indonesian" + [38]=> + string(5) "Irish" + [39]=> + string(7) "Italian" + [40]=> + string(8) "Japanese" + [41]=> + string(13) "Jewish/Kosher" + [42]=> + string(30) "Juice, Smoothies, Fruit Salads" + [43]=> + string(6) "Korean" + [44]=> + string(64) "Latin (Cuban, Dominican, Puerto Rican, South & Central American)" + [45]=> + string(13) "Mediterranean" + [46]=> + string(7) "Mexican" + [47]=> + string(14) "Middle Eastern" + [48]=> + string(8) "Moroccan" + [49]=> + string(25) "Not Listed/Not Applicable" + [50]=> + string(18) "Nuts/Confectionary" + [51]=> + string(5) "Other" + [52]=> + string(9) "Pakistani" + [53]=> + string(16) "Pancakes/Waffles" + [54]=> + string(8) "Peruvian" + [55]=> + string(5) "Pizza" + [56]=> + string(13) "Pizza/Italian" + [57]=> + string(6) "Polish" + [58]=> + string(10) "Portuguese" + [59]=> + string(7) "Russian" + [60]=> + string(6) "Salads" + [61]=> + string(10) "Sandwiches" + [62]=> + string(30) "Sandwiches/Salads/Mixed Buffet" + [63]=> + string(7) "Seafood" + [64]=> + string(9) "Soul Food" + [65]=> + string(18) "Soups & Sandwiches" + [66]=> + string(12) "Southwestern" + [67]=> + string(7) "Spanish" + [68]=> + string(5) "Steak" + [69]=> + string(5) "Tapas" + [70]=> + string(7) "Tex-Mex" + [71]=> + string(4) "Thai" + [72]=> + string(7) "Turkish" + [73]=> + string(10) "Vegetarian" + [74]=> + string(29) "Vietnamese/Cambodian/Malaysia" + } + +See Also +-------- + +- :manual:`distinct ` command reference in the + MongoDB manual diff --git a/source/reference/method/MongoDBCollection-drop.txt b/source/reference/method/MongoDBCollection-drop.txt new file mode 100644 index 00000000..93b6a17c --- /dev/null +++ b/source/reference/method/MongoDBCollection-drop.txt @@ -0,0 +1,137 @@ +=========================== +MongoDB\\Collection::drop() +=========================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::drop() + + Drop the collection. + + .. code-block:: php + + function drop(array $options = []): array|object + +Parameters +---------- + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.13 + + * - encryptedFields + - array|object + - A document describing encrypted fields for queryable encryption. If + omitted, the ``encryptedFieldsMap`` option within the + ``autoEncryption`` driver option will be consulted. If + ``encryptedFieldsMap`` was defined but does not specify this + collection, the library will make a final attempt to consult the + server-side value for ``encryptedFields``. See + `Field Encryption and Queryability `_ + in the MongoDB manual for more information. + + .. note:: + + This option is not passed to the + :manual:`drop ` command. The library uses + it to determine related metadata collections that should be dropped + in addition to an encrypted collection. + + .. versionadded:: 1.13 + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + .. versionadded:: 1.3 + + * - typeMap + - array + - .. include:: /includes/extracts/collection-option-typeMap.rst + + This will be used for the returned command result document. + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - .. include:: /includes/extracts/collection-option-writeConcern.rst + + .. include:: /includes/extracts/common-option-writeConcern-transaction.rst + + + +Return Values +------------- + +An array or object with the result document of the :manual:`drop +` command. The return type will depend on the +``typeMap`` option. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Example +------- + +The following operation drops the ``restaurants`` collection in the ``test`` +database: + +.. code-block:: php + + test->restaurants; + + $result = $collection->drop(); + + var_dump($result); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Model\BSONDocument)#9 (1) { + ["storage":"ArrayObject":private]=> + array(3) { + ["ns"]=> + string(16) "test.restaurants" + ["nIndexesWas"]=> + int(3) + ["ok"]=> + float(1) + } + } + +See Also +-------- + +- :phpmethod:`MongoDB\Database::dropCollection()` +- :manual:`drop ` command reference in the MongoDB + manual diff --git a/source/reference/method/MongoDBCollection-dropIndex.txt b/source/reference/method/MongoDBCollection-dropIndex.txt new file mode 100644 index 00000000..d1aa937c --- /dev/null +++ b/source/reference/method/MongoDBCollection-dropIndex.txt @@ -0,0 +1,128 @@ +================================ +MongoDB\\Collection::dropIndex() +================================ + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::dropIndex() + + Drop an index from the collection. + + .. code-block:: php + + function dropIndex( + string|MongoDB\Model\IndexInfo $indexName, + array $options = [] + ): array|object + +Parameters +---------- + +``$indexName`` : string| :phpclass:`MongoDB\Model\IndexInfo` + The name or model object of the index to drop. View the existing indexes on + the collection by using the :phpmethod:`MongoDB\Collection::listIndexes()` method. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.13 + + * - maxTimeMS + - integer + - .. include:: /includes/extracts/common-option-maxTimeMS.rst + + .. versionadded:: 1.3 + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + .. versionadded:: 1.3 + + * - typeMap + - array + - .. include:: /includes/extracts/collection-option-typeMap.rst + + This will be used for the returned command result document. + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - .. include:: /includes/extracts/collection-option-writeConcern.rst + + .. include:: /includes/extracts/common-option-writeConcern-transaction.rst + +Return Values +------------- + +An array or object with the result document of the :manual:`dropIndexes +` command. The return type will depend on the +``typeMap`` option. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Example +------- + +The following drops an indexes with name ``borough_1`` from the ``restaurants`` +collection in the ``test`` database: + +.. code-block:: php + + test->restaurants; + + $result = $collection->dropIndex('borough_1'); + + var_dump($result); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Model\BSONDocument)#9 (1) { + ["storage":"ArrayObject":private]=> + array(2) { + ["nIndexesWas"]=> + int(2) + ["ok"]=> + float(1) + } + } + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::dropIndexes()` +- :doc:`/tutorial/indexes` +- :manual:`dropIndexes ` command reference in + the MongoDB manual +- :manual:`Index documentation ` in the MongoDB manual diff --git a/source/reference/method/MongoDBCollection-dropIndexes.txt b/source/reference/method/MongoDBCollection-dropIndexes.txt new file mode 100644 index 00000000..6e052cb2 --- /dev/null +++ b/source/reference/method/MongoDBCollection-dropIndexes.txt @@ -0,0 +1,129 @@ +================================== +MongoDB\\Collection::dropIndexes() +================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::dropIndexes() + + Drop all indexes in the collection, except for the required index on the + ``_id`` field. + + .. code-block:: php + + function dropIndexes(array $options = []): array|object + +Parameters +---------- + +``$indexName`` : string| :phpclass:`MongoDB\Model\IndexInfo` + The name or model object of the index to drop. View the existing indexes on + the collection using the :phpmethod:`listIndexes() + ` method. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.13 + + * - maxTimeMS + - integer + - .. include:: /includes/extracts/common-option-maxTimeMS.rst + + .. versionadded:: 1.3 + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + .. versionadded:: 1.3 + + * - typeMap + - array + - .. include:: /includes/extracts/collection-option-typeMap.rst + + This will be used for the returned command result document. + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - .. include:: /includes/extracts/collection-option-writeConcern.rst + + .. include:: /includes/extracts/common-option-writeConcern-transaction.rst + +Return Values +------------- + +An array or object with the result document of the :manual:`dropIndexes +` command. The return type will depend on the +``typeMap`` option. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Example +------- + +The following drops all indexes from the ``restaurants`` collection in the +``test`` database: + +.. code-block:: php + + test->restaurants; + + $result = $collection->dropIndexes(); + + var_dump($result); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Model\BSONDocument)#9 (1) { + ["storage":"ArrayObject":private]=> + array(3) { + ["nIndexesWas"]=> + int(3) + ["msg"]=> + string(38) "non-_id indexes dropped for collection" + ["ok"]=> + float(1) + } + } + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::dropIndex()` +- :doc:`/tutorial/indexes` +- :manual:`dropIndexes ` command reference in + the MongoDB manual +- :manual:`Index documentation ` in the MongoDB manual diff --git a/source/reference/method/MongoDBCollection-dropSearchIndex.txt b/source/reference/method/MongoDBCollection-dropSearchIndex.txt new file mode 100644 index 00000000..fb6be0e0 --- /dev/null +++ b/source/reference/method/MongoDBCollection-dropSearchIndex.txt @@ -0,0 +1,65 @@ +====================================== +MongoDB\\Collection::dropSearchIndex() +====================================== + +.. versionadded:: 1.17 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::dropSearchIndex() + + Drop an Atlas Search index for the collection. + + .. code-block:: php + + function dropSearchIndex(string $name, array $options = []): void + + .. include:: /includes/extracts/note-atlas-search-requirement.rst + +Parameters +---------- + +``$name`` : string + Name of the index to drop. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::createSearchIndex()` +- :phpmethod:`MongoDB\Collection::createSearchIndexes()` +- :phpmethod:`MongoDB\Collection::listSearchIndexes()` +- :phpmethod:`MongoDB\Collection::updateSearchIndex()` +- :manual:`dropSearchIndex ` command + reference in the MongoDB manual +- `Atlas Search `__ documentation in the MongoDB Manual diff --git a/source/reference/method/MongoDBCollection-estimatedDocumentCount.txt b/source/reference/method/MongoDBCollection-estimatedDocumentCount.txt new file mode 100644 index 00000000..1dd1d2a6 --- /dev/null +++ b/source/reference/method/MongoDBCollection-estimatedDocumentCount.txt @@ -0,0 +1,100 @@ +============================================= +MongoDB\\Collection::estimatedDocumentCount() +============================================= + +.. versionadded:: 1.4 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::estimatedDocumentCount() + + Gets an estimated number of documents in the collection using collection metadata. + + .. code-block:: php + + function countDocuments(array $options = []): integer + +Parameters +---------- + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.13 + + * - maxTimeMS + - integer + - .. include:: /includes/extracts/common-option-maxTimeMS.rst + + * - readConcern + - :php:`MongoDB\Driver\ReadConcern ` + - .. include:: /includes/extracts/collection-option-readConcern.rst + + .. include:: /includes/extracts/common-option-readConcern-transaction.rst + + * - readPreference + - :php:`MongoDB\Driver\ReadPreference ` + - .. include:: /includes/extracts/collection-option-readPreference.rst + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + +Return Values +------------- + +An estimated number of documents in the collection. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unexpectedvalueexception.rst +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Behavior +-------- + +This method returns an estimate of the count of documents in the collection +using collection metadata, rather than counting the documents or consulting an +index. This method does not take a ``session`` option and cannot be executed +within a transaction. See +`Count: Behavior `_ +in the MongoDB manual for more information. + +This method is implemented using the :manual:`count ` +command. Due to an oversight in versions 5.0.0-5.0.8 of MongoDB, the ``count`` +command was not included in version "1" of the Stable API. Applications using +this method with the Stable API are recommended to upgrade their server version +to 5.0.9+ or disable strict mode to avoid encountering errors. + +See Also +-------- + +- :manual:`count ` command reference in the MongoDB + manual +- :phpmethod:`MongoDB\Collection::countDocuments()` diff --git a/source/reference/method/MongoDBCollection-explain.txt b/source/reference/method/MongoDBCollection-explain.txt new file mode 100644 index 00000000..03619755 --- /dev/null +++ b/source/reference/method/MongoDBCollection-explain.txt @@ -0,0 +1,318 @@ +============================== +MongoDB\\Collection::explain() +============================== + +.. versionadded:: 1.4 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::explain() + + Explain the given command. + + .. code-block:: php + + function explain( + MongoDB\Operation\Explainable $explainable, + array $options = [] + ): array|object + +Parameters +---------- + +``$explainable`` : ``MongoDB\Operation\Explainable`` + The command to explain. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + Defaults to the ``comment`` of the explained operation (if any). + + .. versionadded:: 1.13 + + * - readPreference + - :php:`MongoDB\Driver\ReadPreference ` + - .. include:: /includes/extracts/collection-option-readPreference.rst + + * - typeMap + - array + - .. include:: /includes/extracts/collection-option-typeMap.rst + + This will be used for the returned command result document. + + * - verbosity + - string + - The verbosity level at which to run the command. See the :manual:`explain + ` command for more information. + +Return Values +------------- + +An array or object with the result document of the :manual:`explain +` command. The return type will depend on the +``typeMap`` option. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Explainable Commands +-------------------- + +Explainable commands include, but are not limited to: + +- ``MongoDB\Operation\Aggregate`` +- ``MongoDB\Operation\Count`` +- ``MongoDB\Operation\DeleteMany`` +- ``MongoDB\Operation\DeleteOne`` +- ``MongoDB\Operation\Distinct`` +- ``MongoDB\Operation\Find`` +- ``MongoDB\Operation\FindOne`` +- ``MongoDB\Operation\FindOneAndDelete`` +- ``MongoDB\Operation\FindOneAndReplace`` +- ``MongoDB\Operation\FindOneAndUpdate`` +- ``MongoDB\Operation\UpdateMany`` +- ``MongoDB\Operation\UpdateOne`` + +Examples +-------- + +This example explains a count command. + +.. code-block:: php + + test->restaurants; + + $count = new MongoDB\Operation\Count( + $collection->getDatabaseName(), + $collection->getCollectionName(), + ['cuisine' => 'Italian'] + ); + + $result = $collection->explain($count); + + var_dump($result); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Model\BSONDocument)#29 (1) { + ["storage":"ArrayObject":private]=> + array(4) { + ["queryPlanner"]=> + object(MongoDB\Model\BSONDocument)#21 (1) { + ["storage":"ArrayObject":private]=> + array(6) { + ["plannerVersion"]=> + int(1) + ["namespace"]=> + string(16) "test.restaurants" + ["indexFilterSet"]=> + bool(false) + ["parsedQuery"]=> + object(MongoDB\Model\BSONDocument)#15 (1) { + ["storage":"ArrayObject":private]=> + array(1) { + ["cuisine"]=> + object(MongoDB\Model\BSONDocument)#14 (1) { + ["storage":"ArrayObject":private]=> + array(1) { + ["$eq"]=> + string(7) "Italian" + } + } + } + } + ["winningPlan"]=> + object(MongoDB\Model\BSONDocument)#19 (1) { + ["storage":"ArrayObject":private]=> + array(2) { + ["stage"]=> + string(5) "COUNT" + ["inputStage"]=> + object(MongoDB\Model\BSONDocument)#18 (1) { + ["storage":"ArrayObject":private]=> + array(3) { + ["stage"]=> + string(8) "COLLSCAN" + ["filter"]=> + object(MongoDB\Model\BSONDocument)#17 (1) { + ["storage":"ArrayObject":private]=> + array(1) { + ["cuisine"]=> + object(MongoDB\Model\BSONDocument)#16 (1) { + ["storage":"ArrayObject":private]=> + array(1) { + ["$eq"]=> + string(7) "Italian" + } + } + } + } + ["direction"]=> + string(7) "forward" + } + } + } + } + ["rejectedPlans"]=> + object(MongoDB\Model\BSONArray)#20 (1) { + ["storage":"ArrayObject":private]=> + array(0) { + } + } + } + } + ["executionStats"]=> + object(MongoDB\Model\BSONDocument)#27 (1) { + ["storage":"ArrayObject":private]=> + array(7) { + ["executionSuccess"]=> + bool(true) + ["nReturned"]=> + int(0) + ["executionTimeMillis"]=> + int(24) + ["totalKeysExamined"]=> + int(0) + ["totalDocsExamined"]=> + int(25359) + ["executionStages"]=> + object(MongoDB\Model\BSONDocument)#25 (1) { + ["storage":"ArrayObject":private]=> + array(14) { + ["stage"]=> + string(5) "COUNT" + ["nReturned"]=> + int(0) + ["executionTimeMillisEstimate"]=> + int(20) + ["works"]=> + int(25361) + ["advanced"]=> + int(0) + ["needTime"]=> + int(25360) + ["needYield"]=> + int(0) + ["saveState"]=> + int(198) + ["restoreState"]=> + int(198) + ["isEOF"]=> + int(1) + ["invalidates"]=> + int(0) + ["nCounted"]=> + int(1069) + ["nSkipped"]=> + int(0) + ["inputStage"]=> + object(MongoDB\Model\BSONDocument)#24 (1) { + ["storage":"ArrayObject":private]=> + array(14) { + ["stage"]=> + string(8) "COLLSCAN" + ["filter"]=> + object(MongoDB\Model\BSONDocument)#23 (1) { + ["storage":"ArrayObject":private]=> + array(1) { + ["cuisine"]=> + object(MongoDB\Model\BSONDocument)#22 (1) { + ["storage":"ArrayObject":private]=> + array(1) { + ["$eq"]=> + string(7) "Italian" + } + } + } + } + ["nReturned"]=> + int(1069) + ["executionTimeMillisEstimate"]=> + int(20) + ["works"]=> + int(25361) + ["advanced"]=> + int(1069) + ["needTime"]=> + int(24291) + ["needYield"]=> + int(0) + ["saveState"]=> + int(198) + ["restoreState"]=> + int(198) + ["isEOF"]=> + int(1) + ["invalidates"]=> + int(0) + ["direction"]=> + string(7) "forward" + ["docsExamined"]=> + int(25359) + } + } + } + } + ["allPlansExecution"]=> + object(MongoDB\Model\BSONArray)#26 (1) { + ["storage":"ArrayObject":private]=> + array(0) { + } + } + } + } + ["serverInfo"]=> + object(MongoDB\Model\BSONDocument)#28 (1) { + ["storage":"ArrayObject":private]=> + array(4) { + ["host"]=> + string(9) "localhost" + ["port"]=> + int(27017) + ["version"]=> + string(5) "3.6.1" + ["gitVersion"]=> + string(40) "025d4f4fe61efd1fb6f0005be20cb45a004093d1" + } + } + ["ok"]=> + float(1) + } + } + +See Also +-------- + +- :manual:`explain ` command reference in the MongoDB + manual diff --git a/source/reference/method/MongoDBCollection-find.txt b/source/reference/method/MongoDBCollection-find.txt new file mode 100644 index 00000000..d6e5a74d --- /dev/null +++ b/source/reference/method/MongoDBCollection-find.txt @@ -0,0 +1,368 @@ +=========================== +MongoDB\\Collection::find() +=========================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::find() + + Finds documents matching the query. + + .. code-block:: php + + function find( + array|object $filter = [], + array $options = [] + ): MongoDB\Driver\Cursor + +Parameters +---------- + +``$filter`` : array|object + The filter criteria that specifies the documents to query. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - allowDiskUse + - boolean + - Enables writing to temporary files. When set to ``true``, queries can + write data to the ``_tmp`` sub-directory in the ``dbPath`` directory. + + * - allowPartialResults + - boolean + - For queries against a sharded collection, returns partial results from + the :program:`mongos` if some shards are unavailable instead of + throwing an error. + + * - batchSize + - integer + - The number of documents to return in the first batch. Defaults to + ``101``. A batchSize of ``0`` means that the cursor will be + established, but no documents will be returned in the first batch. + + Unlike the previous wire protocol version, a batchSize of ``1`` for the + :dbcommand:`find` command does not close the cursor. + + * - codec + - MongoDB\\Codec\\DocumentCodec + - .. include:: /includes/extracts/collection-option-codec.rst + + .. versionadded:: 1.17 + + * - collation + - array|object + - .. include:: /includes/extracts/collection-option-collation.rst + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/common-option-comment-string-before-4.4.rst + + * - cursorType + - integer + - Indicates the type of cursor to use. ``cursorType`` supports the + following values: + + - ``MongoDB\Operation\Find::NON_TAILABLE`` (*default*) + - ``MongoDB\Operation\Find::TAILABLE`` + + * - hint + - string|array|object + - .. include:: /includes/extracts/common-option-hint.rst + + .. versionadded:: 1.2 + + * - let + - array|object + - .. include:: /includes/extracts/common-option-let.rst + + .. versionadded:: 1.13 + + * - limit + - integer + - The maximum number of documents to return. If unspecified, then + defaults to no limit. A limit of ``0`` is equivalent to setting no + limit. + + A negative limit is similar to a positive limit but closes the cursor + after returning a single batch of results. As such, with a negative + limit, if the limited result set does not fit into a single batch, the + number of documents received will be less than the specified limit. By + passing a negative limit, the client indicates to the server that it + will not ask for a subsequent batch via getMore. + + * - max + - array|object + - The exclusive upper bound for a specific index. + + .. versionadded:: 1.2 + + * - maxAwaitTimeMS + - integer + - Positive integer denoting the time limit in milliseconds for the server + to block a getMore operation if no data is available. This option + should only be used if cursorType is TAILABLE_AWAIT. + + .. versionadded:: 1.2 + + * - maxScan + - integer + - Maximum number of documents or index keys to scan when executing the + query. + + .. deprecated:: 1.4 + .. versionadded:: 1.2 + + * - maxTimeMS + - integer + - .. include:: /includes/extracts/common-option-maxTimeMS.rst + + * - min + - array|object + - The inclusive lower bound for a specific index. + + .. versionadded:: 1.2 + + * - modifiers + - array|object + - :manual:`Meta operators ` that + modify the output or behavior of a query. Use of these operators is + deprecated in favor of named options. + + * - noCursorTimeout + - boolean + - Prevents the server from timing out idle cursors after an inactivity + period (10 minutes). + + * - oplogReplay + - boolean + - Internal use for replica sets. To use ``oplogReplay``, you must include + the following condition in the filter: + + .. code-block:: javascript + + { ts: { $gte: } } + + The :php:`MongoDB\BSON\Timestamp ` + class reference describes how to represent MongoDB's BSON timestamp + type with PHP. + + .. deprecated:: 1.7 + + * - projection + - array|object + - The :ref:`projection specification ` to determine which + fields to include in the returned documents. See + :manual:`Project Fields to Return from Query ` + and :manual:`Projection Operators ` in + the MongoDB manual. + + * - readConcern + - :php:`MongoDB\Driver\ReadConcern ` + - .. include:: /includes/extracts/collection-option-readConcern.rst + + .. include:: /includes/extracts/common-option-readConcern-transaction.rst + + * - readPreference + - :php:`MongoDB\Driver\ReadPreference ` + - .. include:: /includes/extracts/collection-option-readPreference.rst + + * - returnKey + - boolean + - If true, returns only the index keys in the resulting documents. + + .. versionadded:: 1.2 + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + .. versionadded:: 1.3 + + * - showRecordId + - boolean + - Determines whether to return the record identifier for each document. + If true, adds a field ``$recordId`` to the returned documents. + + .. versionadded:: 1.2 + + * - skip + - integer + - Number of documents to skip. Defaults to ``0``. + + * - sort + - array|object + - The sort specification for the ordering of the results. + + * - snapshot + - boolean + - Prevents the cursor from returning a document more than once because of + an intervening write operation. + + .. deprecated:: 1.4 + .. versionadded:: 1.2 + + * - typeMap + - array + - .. include:: /includes/extracts/collection-option-typeMap.rst + +Return Values +------------- + +A :php:`MongoDB\Driver\Cursor ` object. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Behavior +-------- + +.. include:: /includes/extracts/note-bson-comparison.rst + +Examples +-------- + +The following example finds restaurants based on the ``cuisine`` and ``borough`` +fields and uses a :manual:`projection +` to limit the fields that are +returned. It also limits the results to 5 documents. + +.. code-block:: php + + test->restaurants; + + $cursor = $collection->find( + [ + 'cuisine' => 'Italian', + 'borough' => 'Manhattan', + ], + [ + 'limit' => 5, + 'projection' => [ + 'name' => 1, + 'borough' => 1, + 'cuisine' => 1, + ], + ] + ); + + foreach ($cursor as $restaurant) { + var_dump($restaurant); + }; + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Model\BSONDocument)#10 (1) { + ["storage":"ArrayObject":private]=> + array(4) { + ["_id"]=> + object(MongoDB\BSON\ObjectId)#8 (1) { + ["oid"]=> + string(24) "576023c6b02fa9281da3f983" + } + ["borough"]=> + string(9) "Manhattan" + ["cuisine"]=> + string(7) "Italian" + ["name"]=> + string(23) "Isle Of Capri Resturant" + } + } + object(MongoDB\Model\BSONDocument)#13 (1) { + ["storage":"ArrayObject":private]=> + array(4) { + ["_id"]=> + object(MongoDB\BSON\ObjectId)#12 (1) { + ["oid"]=> + string(24) "576023c6b02fa9281da3f98d" + } + ["borough"]=> + string(9) "Manhattan" + ["cuisine"]=> + string(7) "Italian" + ["name"]=> + string(18) "Marchis Restaurant" + } + } + object(MongoDB\Model\BSONDocument)#8 (1) { + ["storage":"ArrayObject":private]=> + array(4) { + ["_id"]=> + object(MongoDB\BSON\ObjectId)#10 (1) { + ["oid"]=> + string(24) "576023c6b02fa9281da3f99b" + } + ["borough"]=> + string(9) "Manhattan" + ["cuisine"]=> + string(7) "Italian" + ["name"]=> + string(19) "Forlinis Restaurant" + } + } + object(MongoDB\Model\BSONDocument)#12 (1) { + ["storage":"ArrayObject":private]=> + array(4) { + ["_id"]=> + object(MongoDB\BSON\ObjectId)#13 (1) { + ["oid"]=> + string(24) "576023c6b02fa9281da3f9a8" + } + ["borough"]=> + string(9) "Manhattan" + ["cuisine"]=> + string(7) "Italian" + ["name"]=> + string(22) "Angelo Of Mulberry St." + } + } + object(MongoDB\Model\BSONDocument)#10 (1) { + ["storage":"ArrayObject":private]=> + array(4) { + ["_id"]=> + object(MongoDB\BSON\ObjectId)#8 (1) { + ["oid"]=> + string(24) "576023c6b02fa9281da3f9b4" + } + ["borough"]=> + string(9) "Manhattan" + ["cuisine"]=> + string(7) "Italian" + ["name"]=> + string(16) "V & T Restaurant" + } + } + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::findOne()` +- :manual:`find ` command reference in the MongoDB + manual diff --git a/source/reference/method/MongoDBCollection-findOne.txt b/source/reference/method/MongoDBCollection-findOne.txt new file mode 100644 index 00000000..269d81eb --- /dev/null +++ b/source/reference/method/MongoDBCollection-findOne.txt @@ -0,0 +1,278 @@ +============================== +MongoDB\\Collection::findOne() +============================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::findOne() + + Finds a single document matching the query. + + .. code-block:: php + + function findOne( + array|object $filter = [], + array $options = [] + ): array|object|null + +Parameters +---------- + +``$filter`` : array|object + The filter criteria that specifies the documents to query. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - allowDiskUse + - boolean + - Enables writing to temporary files. When set to ``true``, queries can + write data to the ``_tmp`` sub-directory in the ``dbPath`` directory. + + * - allowPartialResults + - boolean + - For queries against a sharded collection, returns partial results from + the :program:`mongos` if some shards are unavailable instead of + throwing an error. + + * - codec + - MongoDB\\Codec\\DocumentCodec + - .. include:: /includes/extracts/collection-option-codec.rst + + .. versionadded:: 1.17 + + * - collation + - array|object + - .. include:: /includes/extracts/collection-option-collation.rst + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/common-option-comment-string-before-4.4.rst + + * - hint + - string|array|object + - .. include:: /includes/extracts/common-option-hint.rst + + .. versionadded:: 1.2 + + * - let + - array|object + - .. include:: /includes/extracts/common-option-let.rst + + .. versionadded:: 1.13 + + * - max + - array|object + - The exclusive upper bound for a specific index. + + .. versionadded:: 1.2 + + * - maxScan + - integer + - Maximum number of documents or index keys to scan when executing the + query. + + .. deprecated:: 1.4 + .. versionadded:: 1.2 + + * - maxTimeMS + - integer + - .. include:: /includes/extracts/common-option-maxTimeMS.rst + + * - min + - array|object + - The inclusive lower bound for a specific index. + + .. versionadded:: 1.2 + + * - modifiers + - array|object + - :manual:`Meta operators ` that + modify the output or behavior of a query. Use of these operators is + deprecated in favor of named options. + + * - oplogReplay + - boolean + - Internal use for replica sets. To use ``oplogReplay``, you must include + the following condition in the filter: + + .. code-block:: javascript + + { ts: { $gte: } } + + The :php:`MongoDB\BSON\Timestamp ` + class reference describes how to represent MongoDB's BSON timestamp + type with PHP. + + .. deprecated:: 1.7 + + * - projection + - array|object + - The :ref:`projection specification ` to determine which + fields to include in the returned documents. See + :manual:`Project Fields to Return from Query ` + and :manual:`Projection Operators ` in + the MongoDB manual. + + * - readConcern + - :php:`MongoDB\Driver\ReadConcern ` + - .. include:: /includes/extracts/collection-option-readConcern.rst + + .. include:: /includes/extracts/common-option-readConcern-transaction.rst + + * - readPreference + - :php:`MongoDB\Driver\ReadPreference ` + - .. include:: /includes/extracts/collection-option-readPreference.rst + + * - returnKey + - boolean + - If true, returns only the index keys in the resulting documents. + + .. versionadded:: 1.2 + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + .. versionadded:: 1.3 + + * - showRecordId + - boolean + - Determines whether to return the record identifier for each document. + If true, adds a field ``$recordId`` to the returned documents. + + .. versionadded:: 1.2 + + * - skip + - integer + - Number of documents to skip. Defaults to ``0``. + + * - sort + - array|object + - The sort specification for the ordering of the results. + + * - typeMap + - array + - .. include:: /includes/extracts/collection-option-typeMap.rst + + This will be used for the returned result document. + +Return Values +------------- + +An array or object for the :term:`first document ` that matched +the query, or ``null`` if no document matched the query. The return type will +depend on the ``typeMap`` option. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Behavior +-------- + +.. include:: /includes/extracts/note-bson-comparison.rst + +Examples +-------- + +Matching BSON Types in Query Criteria +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In the following example, documents in the ``restaurants`` collection use an +:manual:`ObjectId ` for their identifier (the default) +and documents in the ``zips`` collection use a string. Since ObjectId is a +special BSON type, the query criteria for selecting a restaurant must use the +:php:`MongoDB\BSON\ObjectId ` class. + +.. code-block:: php + + test; + + $zip = $database->zips->findOne(['_id' => '10036']); + + $restaurant = $database->restaurants->findOne([ + '_id' => new MongoDB\BSON\ObjectId('594d5ef280a846852a4b3f70'), + ]); + +Projecting Fields +~~~~~~~~~~~~~~~~~ + +The following example finds a restaurant based on the ``cuisine`` and +``borough`` fields and uses a :manual:`projection +` to limit the fields that are +returned. + +.. code-block:: php + + test->restaurants; + + $restaurant = $collection->findOne( + [ + 'cuisine' => 'Italian', + 'borough' => 'Manhattan', + ], + [ + 'projection' => [ + 'name' => 1, + 'borough' => 1, + 'cuisine' => 1, + ], + ] + ); + + var_dump($restaurant); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Model\BSONDocument)#10 (1) { + ["storage":"ArrayObject":private]=> + array(4) { + ["_id"]=> + object(MongoDB\BSON\ObjectId)#8 (1) { + ["oid"]=> + string(24) "576023c6b02fa9281da3f983" + } + ["borough"]=> + string(9) "Manhattan" + ["cuisine"]=> + string(7) "Italian" + ["name"]=> + string(23) "Isle Of Capri Resturant" + } + } + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::find()` +- :manual:`find ` command reference in the MongoDB + manual diff --git a/source/reference/method/MongoDBCollection-findOneAndDelete.txt b/source/reference/method/MongoDBCollection-findOneAndDelete.txt new file mode 100644 index 00000000..9a7066b7 --- /dev/null +++ b/source/reference/method/MongoDBCollection-findOneAndDelete.txt @@ -0,0 +1,175 @@ +======================================= +MongoDB\\Collection::findOneAndDelete() +======================================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::findOneAndDelete() + + Finds a single document matching the query and deletes it. + + .. code-block:: php + + function findOneAndDelete( + array|object $filter = [], + array $options = [] + ): object|null + +Parameters +---------- + +``$filter`` : array|object + The filter criteria that specifies the documents to delete. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - collation + - array|object + - .. include:: /includes/extracts/collection-option-collation.rst + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.13 + + * - hint + - string|array|object + - .. include:: /includes/extracts/common-option-hint.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.7 + + * - let + - array|object + - .. include:: /includes/extracts/common-option-let.rst + + .. versionadded:: 1.13 + + * - maxTimeMS + - integer + - .. include:: /includes/extracts/common-option-maxTimeMS.rst + + * - projection + - array|object + - The :ref:`projection specification ` to determine which + fields to include in the returned documents. See + :manual:`Project Fields to Return from Query ` + and :manual:`Projection Operators ` in + the MongoDB manual. + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + .. versionadded:: 1.3 + + * - sort + - array|object + - The sort specification for the ordering of the results. + + * - typeMap + - array + - .. include:: /includes/extracts/collection-option-typeMap.rst + + This will be used for the returned result document. + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - .. include:: /includes/extracts/collection-option-writeConcern.rst + + .. include:: /includes/extracts/common-option-writeConcern-transaction.rst + +Return Values +------------- + +An array or object for the document that was deleted, or ``null`` if no document +matched the query. The return type will depend on the ``typeMap`` option. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unexpectedvalueexception.rst +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Behavior +-------- + +.. include:: /includes/extracts/note-bson-comparison.rst + +Examples +-------- + +The following example finds and deletes the document with ``restaurant_id`` of +``"40375376"`` from the ``restaurants`` collection in the ``test`` database: + +.. code-block:: php + + test->restaurants; + + $deletedRestaurant = $collection->findOneAndDelete( + [ 'restaurant_id' => '40375376' ], + [ + 'projection' => [ + 'name' => 1, + 'borough' => 1, + 'restaurant_id' => 1, + ], + ] + ); + + var_dump($deletedRestaurant); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Model\BSONDocument)#17 (1) { + ["storage":"ArrayObject":private]=> + array(4) { + ["_id"]=> + object(MongoDB\BSON\ObjectId)#11 (1) { + ["oid"]=> + string(24) "594d5ef280a846852a4b3f70" + } + ["borough"]=> + string(9) "Manhattan" + ["name"]=> + string(15) "Agra Restaurant" + ["restaurant_id"]=> + string(8) "40375376" + } + } + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::findOneAndReplace()` +- :phpmethod:`MongoDB\Collection::findOneAndUpdate()` +- :manual:`findAndModify ` command reference + in the MongoDB manual diff --git a/source/reference/method/MongoDBCollection-findOneAndReplace.txt b/source/reference/method/MongoDBCollection-findOneAndReplace.txt new file mode 100644 index 00000000..c0a4cef1 --- /dev/null +++ b/source/reference/method/MongoDBCollection-findOneAndReplace.txt @@ -0,0 +1,254 @@ +======================================== +MongoDB\\Collection::findOneAndReplace() +======================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::findOneAndReplace() + + Finds a single document matching the query and replaces it. + + .. code-block:: php + + function findOneAndReplace( + array|object $filter, + array|object $replacement, + array $options = [] + ): object|null + +Parameters +---------- + +``$filter`` : array|object + The filter criteria that specifies the documents to replace. + +``$replacement`` : array|object + The replacement document. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - bypassDocumentValidation + - boolean + - If ``true``, allows the write operation to circumvent document level + validation. Defaults to ``false``. + + * - codec + - MongoDB\\Codec\\DocumentCodec + - .. include:: /includes/extracts/collection-option-codec.rst + + .. versionadded:: 1.17 + + * - collation + - array|object + - .. include:: /includes/extracts/collection-option-collation.rst + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.13 + + * - hint + - string|array|object + - .. include:: /includes/extracts/common-option-hint.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.7 + + * - let + - array|object + - .. include:: /includes/extracts/common-option-let.rst + + .. versionadded:: 1.13 + + * - maxTimeMS + - integer + - .. include:: /includes/extracts/common-option-maxTimeMS.rst + + * - projection + - array|object + - The :ref:`projection specification ` to determine which + fields to include in the returned documents. See + :manual:`Project Fields to Return from Query ` + and :manual:`Projection Operators ` in + the MongoDB manual. + + * - returnDocument + - integer + - Specifies whether to return the document before the replacement is + applied, or after. ``returnDocument`` supports the following values: + + - ``MongoDB\Operation\FindOneAndReplace::RETURN_DOCUMENT_BEFORE`` (*default*) + - ``MongoDB\Operation\FindOneAndReplace::RETURN_DOCUMENT_AFTER`` + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + .. versionadded:: 1.3 + + * - sort + - array|object + - The sort specification for the ordering of the results. + + * - typeMap + - array + - .. include:: /includes/extracts/collection-option-typeMap.rst + + This will be used for the returned result document. + + * - upsert + - boolean + - If set to ``true``, creates a new document when no document matches the + query criteria. The default value is ``false``, which does not insert a + new document when no match is found. + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - .. include:: /includes/extracts/collection-option-writeConcern.rst + + .. include:: /includes/extracts/common-option-writeConcern-transaction.rst + +Return Values +------------- + +An array object for either the original or the replaced document, depending on +the specified value of the ``returnDocument`` option. By default, the original +document is returned. If no document matched the query, ``null`` is returned. +The return type will depend on the ``typeMap`` option. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unexpectedvalueexception.rst +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Behavior +-------- + +.. include:: /includes/extracts/note-bson-comparison.rst + +Examples +-------- + +Consider the following document in the ``restaurants`` collection in the +``test`` database: + +.. code-block:: javascript + + { + "_id" : ObjectId("576023c7b02fa9281da4139e"), + "address" : { + "building" : "977", + "coord" : [ + -74.06940569999999, + 40.6188443 + ], + "street" : "Bay Street", + "zipcode" : "10305" + }, + "borough" : "Staten Island", + "cuisine" : "French", + "grades" : [ + { + "date" : ISODate("2014-08-15T00:00:00Z"), + "grade" : "A", + "score" : 7 + }, + { + "date" : ISODate("2014-02-13T00:00:00Z"), + "grade" : "A", + "score" : 5 + }, + { + "date" : ISODate("2013-06-07T00:00:00Z"), + "grade" : "A", + "score" : 11 + } + ], + "name" : "Zest", + "restaurant_id" : "41220906" + } + +The following operation replaces the document with ``restaurant_id`` of +``"41220906"`` with a new document: + +.. code-block:: php + + teset->restaurants; + + $replacedRestaurant = $collection->findOneAndReplace( + [ 'restaurant_id' => '41220906' ], + [ + 'Borough' => 'Staten Island', + 'cuisine' => 'Italian', + 'grades' => [], + 'name' => 'Staten Island Pastaria', + 'restaurant_id' => '999999999', + ], + [ 'returnDocument' => MongoDB\Operation\FindOneAndReplace::RETURN_DOCUMENT_AFTER ] + ); + + var_dump($replacedRestaurant); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Model\BSONDocument)#18 (1) { + ["storage":"ArrayObject":private]=> + array(6) { + ["_id"]=> + object(MongoDB\BSON\ObjectId)#11 (1) { + ["oid"]=> + string(24) "594d5ef380a846852a4b5837" + } + ["Borough"]=> + string(13) "Staten Island" + ["cuisine"]=> + string(7) "Italian" + ["grades"]=> + object(MongoDB\Model\BSONArray)#17 (1) { + ["storage":"ArrayObject":private]=> + array(0) { + } + } + ["name"]=> + string(22) "Staten Island Pastaria" + ["restaurant_id"]=> + string(9) "999999999" + } + } + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::findOneAndDelete()` +- :phpmethod:`MongoDB\Collection::findOneAndUpdate()` +- :manual:`findAndModify ` command reference + in the MongoDB manual diff --git a/source/reference/method/MongoDBCollection-findOneAndUpdate.txt b/source/reference/method/MongoDBCollection-findOneAndUpdate.txt new file mode 100644 index 00000000..19849ad3 --- /dev/null +++ b/source/reference/method/MongoDBCollection-findOneAndUpdate.txt @@ -0,0 +1,226 @@ +======================================= +MongoDB\\Collection::findOneAndUpdate() +======================================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::findOneAndUpdate() + + Finds a single document matching the query and updates it. + + .. code-block:: php + + function findOneAndUpdate( + array|object $filter, + array|object $update, + array $options = [] + ): object|null + +Parameters +---------- + +``$filter`` : array|object + The filter criteria that specifies the documents to update. + +``$update`` : array|object + Specifies the field and value combinations to update and any relevant update + operators. ``$update`` uses MongoDB's :manual:`update operators + `. Starting with MongoDB 4.2, an `aggregation + pipeline `_ + can be passed as this parameter. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - bypassDocumentValidation + - boolean + - If ``true``, allows the write operation to circumvent document level + validation. Defaults to ``false``. + + * - arrayFilters + - array + - An array of filter documents that determines which array elements to + modify for an update operation on an array field. + + .. versionadded:: 1.3 + + * - collation + - array|object + - .. include:: /includes/extracts/collection-option-collation.rst + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.13 + + * - hint + - string|array|object + - .. include:: /includes/extracts/common-option-hint.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.7 + + * - maxTimeMS + - integer + - .. include:: /includes/extracts/common-option-maxTimeMS.rst + + * - let + - array|object + - .. include:: /includes/extracts/common-option-let.rst + + .. versionadded:: 1.13 + + * - projection + - array|object + - The :ref:`projection specification ` to determine which + fields to include in the returned documents. See + :manual:`Project Fields to Return from Query ` + and :manual:`Projection Operators ` in + the MongoDB manual. + + * - returnDocument + - integer + - Specifies whether to return the document before the update is applied, + or after. ``returnDocument`` supports the following values: + + - ``MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_BEFORE`` (*default*) + - ``MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER`` + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + .. versionadded:: 1.3 + + * - sort + - array|object + - The sort specification for the ordering of the results. + + * - typeMap + - array + - .. include:: /includes/extracts/collection-option-typeMap.rst + + This will be used for the returned result document. + + * - upsert + - boolean + - If set to ``true``, creates a new document when no document matches the + query criteria. The default value is ``false``, which does not insert a + new document when no match is found. + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - .. include:: /includes/extracts/collection-option-writeConcern.rst + + .. include:: /includes/extracts/common-option-writeConcern-transaction.rst + +Return Values +------------- + +An array or object for either the original or the updated document, depending on +the specified value of the ``returnDocument`` option. By default, the original +document is returned. If no document matched the query, ``null`` is returned. +The return type will depend on the ``typeMap`` option. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unexpectedvalueexception.rst +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Behavior +-------- + +.. include:: /includes/extracts/note-bson-comparison.rst + +Examples +-------- + +The following operation updates the restaurant with ``restaurant_id`` of +``"40361708"`` in the ``restaurants`` collection in the ``test`` database by +setting its building number to ``"761"``: + +.. code-block:: php + + test->restaurants; + + $updatedRestaurant = $collection->findOneAndUpdate( + [ 'restaurant_id' => '40361708' ], + [ '$set' => [ 'address.building' => '761' ]], + [ + 'projection' => [ 'address' => 1 ], + 'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER, + ] + ); + + var_dump($updatedRestaurant); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Model\BSONDocument)#20 (1) { + ["storage":"ArrayObject":private]=> + array(2) { + ["_id"]=> + object(MongoDB\BSON\ObjectId)#12 (1) { + ["oid"]=> + string(24) "594d5ef280a846852a4b3dee" + } + ["address"]=> + object(MongoDB\Model\BSONDocument)#19 (1) { + ["storage":"ArrayObject":private]=> + array(4) { + ["building"]=> + string(3) "761" + ["coord"]=> + object(MongoDB\Model\BSONArray)#18 (1) { + ["storage":"ArrayObject":private]=> + array(2) { + [0]=> + float(-73.9925306) + [1]=> + float(40.7309346) + } + } + ["street"]=> + string(8) "Broadway" + ["zipcode"]=> + string(5) "10003" + } + } + } + } + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::findOneAndDelete()` +- :phpmethod:`MongoDB\Collection::findOneAndReplace()` +- :manual:`findAndModify ` command reference + in the MongoDB manual diff --git a/source/reference/method/MongoDBCollection-getCollectionName.txt b/source/reference/method/MongoDBCollection-getCollectionName.txt new file mode 100644 index 00000000..9b629232 --- /dev/null +++ b/source/reference/method/MongoDBCollection-getCollectionName.txt @@ -0,0 +1,53 @@ +======================================== +MongoDB\\Collection::getCollectionName() +======================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::getCollectionName() + + Returns the name of this collection. + + .. code-block:: php + + function getCollectionName(): string + +Return Values +------------- + +The name of this collection as a string. + +Example +------- + +The following returns the collection name for the ``zips`` collection in the +``test`` database. + +.. code-block:: php + + test->zips; + + echo $collection->getCollectionName(); + +The output would then resemble: + +.. code-block:: none + + zips + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::getDatabaseName()` +- :phpmethod:`MongoDB\Collection::getNamespace()` diff --git a/source/reference/method/MongoDBCollection-getDatabaseName.txt b/source/reference/method/MongoDBCollection-getDatabaseName.txt new file mode 100644 index 00000000..5cb4902c --- /dev/null +++ b/source/reference/method/MongoDBCollection-getDatabaseName.txt @@ -0,0 +1,54 @@ +====================================== +MongoDB\\Collection::getDatabaseName() +====================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::getDatabaseName() + + Returns the name of the database containing this collection. + + .. code-block:: php + + function getDatabaseName(): string + +Return Values +------------- + +The name of the database containing this collection as a string. + +Example +------- + +The following returns the database name for the ``zips`` collection in the +``test`` database. + +.. code-block:: php + + test->zips; + + echo $collection->getDatabaseName(); + +The output would then resemble: + +.. code-block:: none + + test + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::getCollectionName()` +- :phpmethod:`MongoDB\Collection::getNamespace()` + diff --git a/source/reference/method/MongoDBCollection-getManager.txt b/source/reference/method/MongoDBCollection-getManager.txt new file mode 100644 index 00000000..427ed29e --- /dev/null +++ b/source/reference/method/MongoDBCollection-getManager.txt @@ -0,0 +1,35 @@ +================================= +MongoDB\\Collection::getManager() +================================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::getManager() + + Accessor for the + :php:`MongoDB\Driver\Manager ` used by this + :phpclass:`Collection `. + + .. code-block:: php + + function getManager(): MongoDB\Manager + +Return Values +------------- + +A :php:`MongoDB\Driver\Manager ` object. + +See Also +-------- + +- :phpmethod:`MongoDB\Client::getManager()` +- :phpmethod:`MongoDB\Database::getManager()` diff --git a/source/reference/method/MongoDBCollection-getNamespace.txt b/source/reference/method/MongoDBCollection-getNamespace.txt new file mode 100644 index 00000000..4003fbd8 --- /dev/null +++ b/source/reference/method/MongoDBCollection-getNamespace.txt @@ -0,0 +1,54 @@ +=================================== +MongoDB\\Collection::getNamespace() +=================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::getNamespace() + + Returns the :term:`namespace` of the collection. A namespace is the canonical + name of an index or collection in MongoDB. + + .. code-block:: php + + function getNamespace(): string + +Return Values +------------- + +The namespace of this collection as a string. + +Example +------- + +The following returns the namespace of the ``zips`` collection in the ``test`` +database. + +.. code-block:: php + + test->zips; + + echo $collection->getNamespace(); + +The output would then resemble: + +.. code-block:: none + + test.zips + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::getCollectionName()` +- :phpmethod:`MongoDB\Collection::getDatabaseName()` diff --git a/source/reference/method/MongoDBCollection-getReadConcern.txt b/source/reference/method/MongoDBCollection-getReadConcern.txt new file mode 100644 index 00000000..0ce0b482 --- /dev/null +++ b/source/reference/method/MongoDBCollection-getReadConcern.txt @@ -0,0 +1,60 @@ +===================================== +MongoDB\\Collection::getReadConcern() +===================================== + +.. versionadded:: 1.2 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::getReadConcern() + + Returns the read concern for this collection. + + .. code-block:: php + + function getReadConcern(): MongoDB\Driver\ReadConcern + +Return Values +------------- + +A :php:`MongoDB\Driver\ReadConcern ` object. + +Example +------- + +.. code-block:: php + + selectCollection('test', 'users', [ + 'readConcern' => new MongoDB\Driver\ReadConcern('majority'), + ]); + + var_dump($collection->getReadConcern()); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Driver\ReadConcern)#5 (1) { + ["level"]=> + string(8) "majority" + } + +See Also +-------- + +- :manual:`Read Concern ` in the MongoDB manual +- :php:`MongoDB\Driver\ReadConcern::isDefault() ` +- :phpmethod:`MongoDB\Client::getReadConcern()` +- :phpmethod:`MongoDB\Database::getReadConcern()` +- :phpmethod:`MongoDB\GridFS\Bucket::getReadConcern()` diff --git a/source/reference/method/MongoDBCollection-getReadPreference.txt b/source/reference/method/MongoDBCollection-getReadPreference.txt new file mode 100644 index 00000000..b14980ae --- /dev/null +++ b/source/reference/method/MongoDBCollection-getReadPreference.txt @@ -0,0 +1,60 @@ +======================================== +MongoDB\\Collection::getReadPreference() +======================================== + +.. versionadded:: 1.2 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::getReadPreference() + + Returns the read preference for this collection. + + .. code-block:: php + + function getReadPreference(): MongoDB\Driver\ReadPreference + +Return Values +------------- + +A :php:`MongoDB\Driver\ReadPreference ` +object. + +Example +------- + +.. code-block:: php + + selectCollection('test', 'users', [ + 'readPreference' => new MongoDB\Driver\ReadPreference('primaryPreferred'), + ]); + + var_dump($collection->getReadPreference()); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Driver\ReadPreference)#5 (1) { + ["mode"]=> + string(16) "primaryPreferred" + } + +See Also +-------- + +- :manual:`Read Preference ` in the MongoDB manual +- :phpmethod:`MongoDB\Client::getReadPreference()` +- :phpmethod:`MongoDB\Database::getReadPreference()` +- :phpmethod:`MongoDB\GridFS\Bucket::getReadPreference()` diff --git a/source/reference/method/MongoDBCollection-getTypeMap.txt b/source/reference/method/MongoDBCollection-getTypeMap.txt new file mode 100644 index 00000000..8cd9240c --- /dev/null +++ b/source/reference/method/MongoDBCollection-getTypeMap.txt @@ -0,0 +1,67 @@ +================================= +MongoDB\\Collection::getTypeMap() +================================= + +.. versionadded:: 1.2 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::getTypeMap() + + Returns the type map for this collection. + + .. code-block:: php + + function getTypeMap(): array + +Return Values +------------- + +A :ref:`type map ` array. + +Example +------- + +.. code-block:: php + + selectCollection('test', 'users', [ + 'typeMap' => [ + 'root' => 'array', + 'document' => 'array', + 'array' => 'array', + ], + ]); + + var_dump($collection->getTypeMap()); + +The output would then resemble: + +.. code-block:: none + + array(3) { + ["root"]=> + string(5) "array" + ["document"]=> + string(5) "array" + ["array"]=> + string(5) "array" + } + +See Also +-------- + +- :doc:`/reference/bson` +- :phpmethod:`MongoDB\Client::getTypeMap()` +- :phpmethod:`MongoDB\Database::getTypeMap()` +- :phpmethod:`MongoDB\GridFS\Bucket::getTypeMap()` diff --git a/source/reference/method/MongoDBCollection-getWriteConcern.txt b/source/reference/method/MongoDBCollection-getWriteConcern.txt new file mode 100644 index 00000000..cc3e5d94 --- /dev/null +++ b/source/reference/method/MongoDBCollection-getWriteConcern.txt @@ -0,0 +1,63 @@ +====================================== +MongoDB\\Collection::getWriteConcern() +====================================== + +.. versionadded:: 1.2 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::getWriteConcern() + + Returns the write concern for this collection. + + .. code-block:: php + + function getWriteConcern(): MongoDB\Driver\WriteConcern + +Return Values +------------- + +A :php:`MongoDB\Driver\WriteConcern ` +object. + +Example +------- + +.. code-block:: php + + selectCollection('test', 'users', [ + 'writeConcern' => new MongoDB\Driver\WriteConcern(1, 0, true), + ]); + + var_dump($collection->getWriteConcern()); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Driver\WriteConcern)#5 (2) { + ["w"]=> + int(1) + ["j"]=> + bool(true) + } + +See Also +-------- + +- :manual:`Write Concern ` in the MongoDB manual +- :php:`MongoDB\Driver\WriteConcern::isDefault() ` +- :phpmethod:`MongoDB\Client::getWriteConcern()` +- :phpmethod:`MongoDB\Database::getWriteConcern()` +- :phpmethod:`MongoDB\GridFS\Bucket::getWriteConcern()` diff --git a/source/reference/method/MongoDBCollection-insertMany.txt b/source/reference/method/MongoDBCollection-insertMany.txt new file mode 100644 index 00000000..bcaec509 --- /dev/null +++ b/source/reference/method/MongoDBCollection-insertMany.txt @@ -0,0 +1,162 @@ +================================= +MongoDB\\Collection::insertMany() +================================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::insertMany() + + Insert multiple documents. + + .. code-block:: php + + function insertMany( + array $documents, + array $options = [] + ): MongoDB\InsertManyResult + +Parameters +---------- + +``$documents`` : array + The documents to insert into the collection. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - bypassDocumentValidation + - boolean + - If ``true``, allows the write operation to circumvent document level + validation. Defaults to ``false``. + + * - codec + - MongoDB\\Codec\\DocumentCodec + - .. include:: /includes/extracts/collection-option-codec.rst + + .. versionadded:: 1.17 + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.13 + + * - ordered + - boolean + - If ``true``: when a single write fails, the operation will stop without + performing the remaining writes and throw an exception. + + If ``false``: when a single write fails, the operation will continue + with the remaining writes, if any, and throw an exception. + + The default is ``true``. + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + .. versionadded:: 1.3 + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - .. include:: /includes/extracts/collection-option-writeConcern.rst + + .. include:: /includes/extracts/common-option-writeConcern-transaction.rst + +Return Values +------------- + +A :phpclass:`MongoDB\InsertManyResult` object, which encapsulates a +:php:`MongoDB\Driver\WriteResult ` object. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-bulkwriteexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Behavior +-------- + +.. include:: /includes/extracts/bulkwriteexception-result.rst +.. include:: /includes/extracts/bulkwriteexception-ordered.rst + +Example +------- + +.. start-crud-include + +The following operation inserts two documents into the ``users`` collection +in the ``test`` database: + +.. code-block:: php + + test->users; + + $insertManyResult = $collection->insertMany([ + [ + 'username' => 'admin', + 'email' => 'admin@example.com', + 'name' => 'Admin User', + ], + [ + 'username' => 'test', + 'email' => 'test@example.com', + 'name' => 'Test User', + ], + ]); + + printf("Inserted %d document(s)\n", $insertManyResult->getInsertedCount()); + + var_dump($insertManyResult->getInsertedIds()); + +The output would then resemble: + +.. code-block:: none + + Inserted 2 document(s) + array(2) { + [0]=> + object(MongoDB\BSON\ObjectId)#11 (1) { + ["oid"]=> + string(24) "579a25921f417dd1e5518141" + } + [1]=> + object(MongoDB\BSON\ObjectId)#12 (1) { + ["oid"]=> + string(24) "579a25921f417dd1e5518142" + } + } + +.. end-crud-include + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::insertOne()` +- :phpmethod:`MongoDB\Collection::bulkWrite()` +- :doc:`/tutorial/crud` +- :manual:`insert ` command reference in the MongoDB + manual diff --git a/source/reference/method/MongoDBCollection-insertOne.txt b/source/reference/method/MongoDBCollection-insertOne.txt new file mode 100644 index 00000000..d4b0d0de --- /dev/null +++ b/source/reference/method/MongoDBCollection-insertOne.txt @@ -0,0 +1,136 @@ +================================ +MongoDB\\Collection::insertOne() +================================ + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::insertOne() + + Insert one document. + + .. code-block:: php + + function insertOne( + array|object $document, + array $options = [] + ): MongoDB\InsertOneResult + +Parameters +---------- + +``$document`` : array|object + The document to insert into the collection. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - bypassDocumentValidation + - boolean + - If ``true``, allows the write operation to circumvent document level + validation. Defaults to ``false``. + + * - codec + - MongoDB\\Codec\\DocumentCodec + - .. include:: /includes/extracts/collection-option-codec.rst + + .. versionadded:: 1.17 + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.13 + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + .. versionadded:: 1.3 + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - .. include:: /includes/extracts/collection-option-writeConcern.rst + + .. include:: /includes/extracts/common-option-writeConcern-transaction.rst + +Return Values +------------- + +A :phpclass:`MongoDB\InsertOneResult` object, which encapsulates a +:php:`MongoDB\Driver\WriteResult ` object. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-bulkwriteexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Behavior +-------- + +.. include:: /includes/extracts/bulkwriteexception-result.rst + +Example +------- + +.. start-crud-include + +The following operation inserts a document into the ``users`` collection in the +``test`` database: + +.. code-block:: php + + test->users; + + $insertOneResult = $collection->insertOne([ + 'username' => 'admin', + 'email' => 'admin@example.com', + 'name' => 'Admin User', + ]); + + printf("Inserted %d document(s)\n", $insertOneResult->getInsertedCount()); + + var_dump($insertOneResult->getInsertedId()); + +The output would then resemble: + +.. code-block:: none + + Inserted 1 document(s) + object(MongoDB\BSON\ObjectId)#11 (1) { + ["oid"]=> + string(24) "579a25921f417dd1e5518141" + } + +.. end-crud-include + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::insertMany()` +- :phpmethod:`MongoDB\Collection::bulkWrite()` +- :doc:`/tutorial/crud` +- :manual:`insert ` command reference in the MongoDB + manual diff --git a/source/reference/method/MongoDBCollection-listIndexes.txt b/source/reference/method/MongoDBCollection-listIndexes.txt new file mode 100644 index 00000000..b65b228b --- /dev/null +++ b/source/reference/method/MongoDBCollection-listIndexes.txt @@ -0,0 +1,137 @@ +================================== +MongoDB\\Collection::listIndexes() +================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::listIndexes() + + Returns information for all indexes for this collection. + + .. code-block:: php + + function listIndexes(array $options = []): MongoDB\Model\IndexInfoIterator + +Parameters +---------- + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.13 + + * - maxTimeMS + - integer + - .. include:: /includes/extracts/common-option-maxTimeMS.rst + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + .. versionadded:: 1.3 + +Return Values +------------- + +A traversable :phpclass:`MongoDB\Model\IndexInfoIterator`, which contains a +:phpclass:`MongoDB\Model\IndexInfo` object for each index for the collection. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Example +------- + +The following example lists all of the indexes for the ``restaurants`` +collection in the ``test`` database: + +.. code-block:: php + + test->restaurants; + + foreach ($collection->listIndexes() as $index) { + var_dump($index); + } + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Model\IndexInfo)#8 (4) { + ["v"]=> + int(1) + ["key"]=> + array(1) { + ["_id"]=> + int(1) + } + ["name"]=> + string(4) "_id_" + ["ns"]=> + string(16) "test.restaurants" + } + object(MongoDB\Model\IndexInfo)#12 (4) { + ["v"]=> + int(1) + ["key"]=> + array(1) { + ["cuisine"]=> + float(-1) + } + ["name"]=> + string(10) "cuisine_-1" + ["ns"]=> + string(16) "test.restaurants" + } + object(MongoDB\Model\IndexInfo)#8 (4) { + ["v"]=> + int(1) + ["key"]=> + array(1) { + ["borough"]=> + float(1) + } + ["name"]=> + string(9) "borough_1" + ["ns"]=> + string(16) "test.restaurants" + } + +See Also +-------- + +- :doc:`/tutorial/indexes` +- :manual:`listIndexes ` command reference in + the MongoDB manual +- :manual:`Index documentation ` in the MongoDB manual +- `Enumerating Collections + `_ + specification diff --git a/source/reference/method/MongoDBCollection-listSearchIndexes.txt b/source/reference/method/MongoDBCollection-listSearchIndexes.txt new file mode 100644 index 00000000..73b58653 --- /dev/null +++ b/source/reference/method/MongoDBCollection-listSearchIndexes.txt @@ -0,0 +1,122 @@ +======================================== +MongoDB\\Collection::listSearchIndexes() +======================================== + +.. versionadded:: 1.17 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::listSearchIndexes() + + Gets index information for one or more search indexes in the collection. + + .. code-block:: php + + function listSearchIndexes(array $options = []): Countable&Iterator + + .. include:: /includes/extracts/note-atlas-search-requirement.rst + +Parameters +---------- + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - batchSize + - integer + - Specifies the batch size for the cursor, which will apply to both the + initial ``aggregate`` command and any subsequent ``getMore`` commands. + This determines the maximum number of documents to return in each + response from the server. + + A batchSize of ``0`` is special in that and will only apply to the + initial ``aggregate`` command; subsequent ``getMore`` commands will use + the server's default batch size. This may be useful for quickly + returning a cursor or failure from ``aggregate`` without doing + significant server-side work. + + * - codec + - MongoDB\\Codec\\DocumentCodec + - .. include:: /includes/extracts/collection-option-codec.rst + + .. versionadded:: 1.17 + + * - collation + - array|object + - .. include:: /includes/extracts/common-option-collation.rst + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + * - maxTimeMS + - integer + - .. include:: /includes/extracts/common-option-maxTimeMS.rst + + * - name + - string + - Name of the index to return information about. + + If name is not specified, information for all indexes on the collection + will be returned. + + * - readConcern + - :php:`MongoDB\Driver\ReadConcern ` + - .. include:: /includes/extracts/collection-option-readConcern.rst + + .. include:: /includes/extracts/common-option-readConcern-transaction.rst + + * - readPreference + - :php:`MongoDB\Driver\ReadPreference ` + - .. include:: /includes/extracts/collection-option-readPreference.rst + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + * - typeMap + - array + - .. include:: /includes/extracts/collection-option-typeMap.rst + +Return Values +------------- + +A list of documents, each of which describes a search index on the collection. +For details on the output fields, see +:manual:`$listSearchIndexes: Output ` +in the MongoDB manual. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::createSearchIndex()` +- :phpmethod:`MongoDB\Collection::createSearchIndexes()` +- :phpmethod:`MongoDB\Collection::dropSearchIndex()` +- :phpmethod:`MongoDB\Collection::updateSearchIndex()` +- :manual:`$listSearchIndexes ` + aggregation pipeline stage reference in the MongoDB manual +- `Atlas Search `__ documentation in the MongoDB Manual diff --git a/source/reference/method/MongoDBCollection-mapReduce.txt b/source/reference/method/MongoDBCollection-mapReduce.txt new file mode 100644 index 00000000..afb57373 --- /dev/null +++ b/source/reference/method/MongoDBCollection-mapReduce.txt @@ -0,0 +1,254 @@ +================================ +MongoDB\\Collection::mapReduce() +================================ + +.. deprecated:: 1.12 + +.. versionadded:: 1.2 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::mapReduce() + + The :manual:`mapReduce ` command allows you to + run map-reduce aggregation operations over a collection. + + .. code-block:: php + + function mapReduce( + MongoDB\BSON\JavascriptInterface $map, + MongoDB\BSON\JavascriptInterface $reduce, + string|array|object $out, + array $options = [] + ): MongoDB\MapReduceResult + +Parameters +---------- + +``$map`` : :php:`MongoDB\BSON\Javascript ` + A JavaScript function that associates or "maps" a value with a key and emits + the key and value pair. + + .. note:: + + Passing a Javascript instance with a scope is deprecated. Put all scope + variables in the ``scope`` option of the MapReduce operation. + +``$reduce`` : :php:`MongoDB\BSON\Javascript ` + A JavaScript function that "reduces" to a single object all the values + associated with a particular key. + + .. note:: + + Passing a Javascript instance with a scope is deprecated. Put all scope + variables in the ``scope`` option of the MapReduce operation. + +``$out`` : string|array|object + Specifies where to output the result of the map-reduce operation. You can + either output to a collection or return the result inline. On a primary member + of a replica set you can output either to a collection or inline, but on a + secondary, only inline output is possible. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - bypassDocumentValidation + - boolean + - If ``true``, allows the write operation to circumvent document level + validation. Defaults to ``false``. + + This only applies when results are output to a collection. + + * - collation + - array|object + - .. include:: /includes/extracts/collection-option-collation.rst + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.13 + + * - finalize + - :php:`MongoDB\BSON\Javascript ` + - Follows the reduce method and modifies the output. + + .. note:: + + Passing a Javascript instance with a scope is deprecated. Put all + scope variables in the ``scope`` option of the MapReduce operation. + + * - jsMode + - boolean + - Specifies whether to convert intermediate data into BSON format between + the execution of the map and reduce functions. + + * - limit + - integer + - Specifies a maximum number of documents for the input into the map + function. + + * - maxTimeMS + - integer + - .. include:: /includes/extracts/common-option-maxTimeMS.rst + + * - query + - array|object + - Specifies the selection criteria using query operators for determining + the documents input to the map function. + + * - readConcern + - :php:`MongoDB\Driver\ReadConcern ` + - .. include:: /includes/extracts/collection-option-readConcern.rst + + .. include:: /includes/extracts/common-option-readConcern-transaction.rst + + * - readPreference + - :php:`MongoDB\Driver\ReadPreference ` + - .. include:: /includes/extracts/collection-option-readPreference.rst + + This option will be ignored when results are output to a collection. + + * - scope + - array|object + - Specifies global variables that are accessible in the map, reduce, and + finalize functions. + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + .. versionadded:: 1.3 + + * - sort + - array|object + - The sort specification for the ordering of the results. + + * - typeMap + - array + - .. include:: /includes/extracts/collection-option-typeMap.rst + + * - verbose + - boolean + - Specifies whether to include the timing information in the result + information. + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - .. include:: /includes/extracts/collection-option-writeConcern.rst + + .. include:: /includes/extracts/common-option-writeConcern-transaction.rst + +Return Values +------------- + +A :phpclass:`MongoDB\MapReduceResult` object, which allows for iteration of +map-reduce results irrespective of the output method (e.g. inline, collection) +via the :php:`IteratorAggregate ` interface. It also +provides access to command statistics. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-unexpectedvalueexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Behavior +-------- + +In MongoDB, the map-reduce operation can write results to a collection +or return the results inline. If you write map-reduce output to a +collection, you can perform subsequent map-reduce operations on the +same input collection that merge replace, merge, or reduce new results +with previous results. See :manual:`Map-Reduce ` and +:manual:`Perform Incremental Map-Reduce ` +for details and examples. + +When returning the results of a map-reduce operation *inline*, the +result documents must be within the :limit:`BSON Document Size` limit, +which is currently 16 megabytes. + +MongoDB supports map-reduce operations on :manual:`sharded collections +`. Map-reduce operations can also output +the results to a sharded collection. See +:manual:`Map-Reduce and Sharded Collections `. + +Example +------- + +This example will use city populations to calculate the overall population of +each state. + +.. code-block:: php + + test->zips; + + $map = new MongoDB\BSON\Javascript('function() { emit(this.state, this.pop); }'); + $reduce = new MongoDB\BSON\Javascript('function(key, values) { return Array.sum(values) }'); + $out = ['inline' => 1]; + + $populations = $collection->mapReduce($map, $reduce, $out); + + foreach ($populations as $pop) { + var_dump($pop); + }; + +The output would then resemble: + +.. code-block:: none + + object(stdClass)#2293 (2) { + ["_id"]=> + string(2) "AK" + ["value"]=> + float(544698) + } + object(stdClass)#2300 (2) { + ["_id"]=> + string(2) "AL" + ["value"]=> + float(4040587) + } + object(stdClass)#2293 (2) { + ["_id"]=> + string(2) "AR" + ["value"]=> + float(2350725) + } + object(stdClass)#2300 (2) { + ["_id"]=> + string(2) "AZ" + ["value"]=> + float(3665228) + } + +See Also +-------- + +- :manual:`mapReduce ` command reference in the MongoDB + manual +- :manual:`Map-Reduce ` documentation in the MongoDB manual + diff --git a/source/reference/method/MongoDBCollection-rename.txt b/source/reference/method/MongoDBCollection-rename.txt new file mode 100644 index 00000000..347c205b --- /dev/null +++ b/source/reference/method/MongoDBCollection-rename.txt @@ -0,0 +1,129 @@ +============================= +MongoDB\\Collection::rename() +============================= + +.. versionadded:: 1.10 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::rename() + + Rename the collection. + + .. code-block:: php + + function rename( + string $toCollectionName, + ?string $toDatabaseName = null, + array $options = [] + ): array|object + +Parameters +---------- + +``$toCollectionName`` : string + The new name of the collection. + +``$toDatabaseName`` : string + The new database name of the collection. If a new database name is not + specified, the database of the original collection will be used. If the new + name specifies a different database, the command copies the collection + to the new database and drops the source collection. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - dropTarget + - boolean + - If ``true``, MongoDB will drop the target before renaming the + collection. The default value is ``false``. + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.13 + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + * - typeMap + - array + - .. include:: /includes/extracts/collection-option-typeMap.rst + + This will be used for the returned command result document. + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - .. include:: /includes/extracts/collection-option-writeConcern.rst + + .. include:: /includes/extracts/common-option-writeConcern-transaction.rst + +Return Values +------------- + +An array or object with the result document of the :manual:`renameCollection +` command. The return type will depend on the +``typeMap`` option. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Example +------- + +The following operation renames the ``restaurants`` collection in the ``test`` +database to ``places``: + +.. code-block:: php + + test->restaurants; + + $result = $collection->rename('places'); + + var_dump($result); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Model\BSONDocument)#9 (1) { + ["storage":"ArrayObject":private]=> + array(1) { + ["ok"]=> + float(1) + } + } + +See Also +-------- + +- :phpmethod:`MongoDB\Database::renameCollection()` +- :manual:`renameCollection ` command reference in the MongoDB + manual diff --git a/source/reference/method/MongoDBCollection-replaceOne.txt b/source/reference/method/MongoDBCollection-replaceOne.txt new file mode 100644 index 00000000..7a5444a1 --- /dev/null +++ b/source/reference/method/MongoDBCollection-replaceOne.txt @@ -0,0 +1,166 @@ +================================= +MongoDB\\Collection::replaceOne() +================================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::replaceOne() + + Replace at most one document that matches the filter criteria. If multiple + documents match the filter criteria, only the :term:`first ` + matching document will be replaced. + + .. code-block:: php + + function replaceOne( + array|object $filter, + array|object $replacement, + array $options = [] + ): MongoDB\UpdateResult + +Parameters +---------- + +``$filter`` : array|object + The filter criteria that specifies the documents to replace. + +``$replacement`` : array|object + The replacement document. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - bypassDocumentValidation + - boolean + - If ``true``, allows the write operation to circumvent document level + validation. Defaults to ``false``. + + * - codec + - MongoDB\\Codec\\DocumentCodec + - .. include:: /includes/extracts/collection-option-codec.rst + + .. versionadded:: 1.17 + + * - collation + - array|object + - .. include:: /includes/extracts/collection-option-collation.rst + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.13 + + * - hint + - string|array|object + - .. include:: /includes/extracts/common-option-hint.rst + + .. include:: /includes/extracts/option-requires-4.2.rst + + .. versionadded:: 1.6 + + * - let + - array|object + - .. include:: /includes/extracts/common-option-let.rst + + .. versionadded:: 1.13 + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + .. versionadded:: 1.3 + + * - upsert + - boolean + - If set to ``true``, creates a new document when no document matches the + query criteria. The default value is ``false``, which does not insert a + new document when no match is found. + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - .. include:: /includes/extracts/collection-option-writeConcern.rst + + .. include:: /includes/extracts/common-option-writeConcern-transaction.rst + +Return Values +------------- + +A :phpclass:`MongoDB\UpdateResult` object, which encapsulates a +:php:`MongoDB\Driver\WriteResult ` object. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-bulkwriteexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Behavior +-------- + +.. include:: /includes/extracts/note-bson-comparison.rst +.. include:: /includes/extracts/bulkwriteexception-result.rst + +Example +------- + +The following example replaces the document with ``restaurant_id`` of +``"40356068"`` in the ``restaurants`` collection in the ``test`` database: + +.. code-block:: php + + test->restaurants; + + $updateResult = $collection->replaceOne( + [ 'restaurant_id' => '40356068' ], + [ + 'name' => 'New Restaurant', + 'restaurant_id' => '99988877', + 'borough' => 'Queens', + 'cuisine' => 'Cafe', + 'grades' => [], + ] + ); + + printf("Matched %d document(s)\n", $updateResult->getMatchedCount()); + printf("Modified %d document(s)\n", $updateResult->getModifiedCount()); + +The output would then resemble: + +.. code-block:: none + + Matched 1 document(s) + Modified 1 document(s) + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::updateMany()` +- :phpmethod:`MongoDB\Collection::updateOne()` +- :phpmethod:`MongoDB\Collection::bulkWrite()` +- :doc:`/tutorial/crud` +- :manual:`update ` command reference in the MongoDB + manual diff --git a/source/reference/method/MongoDBCollection-updateMany.txt b/source/reference/method/MongoDBCollection-updateMany.txt new file mode 100644 index 00000000..9d567ec3 --- /dev/null +++ b/source/reference/method/MongoDBCollection-updateMany.txt @@ -0,0 +1,163 @@ +================================= +MongoDB\\Collection::updateMany() +================================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::updateMany() + + Update all documents that match the filter criteria. + + .. code-block:: php + + function updateMany( + array|object $filter, + array|object $update, + array $options = [] + ): MongoDB\UpdateResult + +Parameters +---------- + +``$filter`` : array|object + The filter criteria that specifies the documents to update. + +``$update`` : array|object + Specifies the field and value combinations to update and any relevant update + operators. ``$update`` uses MongoDB's :manual:`update operators + `. Starting with MongoDB 4.2, an `aggregation + pipeline `_ + can be passed as this parameter. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - arrayFilters + - array + - An array of filter documents that determines which array elements to + modify for an update operation on an array field. + + .. versionadded:: 1.3 + + * - bypassDocumentValidation + - boolean + - If ``true``, allows the write operation to circumvent document level + validation. Defaults to ``false``. + + * - collation + - array|object + - .. include:: /includes/extracts/collection-option-collation.rst + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.13 + + * - hint + - string|array|object + - .. include:: /includes/extracts/common-option-hint.rst + + .. include:: /includes/extracts/option-requires-4.2.rst + + .. versionadded:: 1.6 + + * - let + - array|object + - .. include:: /includes/extracts/common-option-let.rst + + .. versionadded:: 1.13 + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + .. versionadded:: 1.3 + + * - upsert + - boolean + - If set to ``true``, creates a new document when no document matches the + query criteria. The default value is ``false``, which does not insert a + new document when no match is found. + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - .. include:: /includes/extracts/collection-option-writeConcern.rst + + .. include:: /includes/extracts/common-option-writeConcern-transaction.rst + +Return Values +------------- + +A :phpclass:`MongoDB\UpdateResult` object, which encapsulates a +:php:`MongoDB\Driver\WriteResult ` object. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-bulkwriteexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Behavior +-------- + +.. include:: /includes/extracts/note-bson-comparison.rst +.. include:: /includes/extracts/bulkwriteexception-result.rst + +Examples +-------- + +The following example updates all of the documents with the ``borough`` of +``"Queens"`` by setting the ``active`` field to ``true``: + +.. code-block:: php + + test->restaurants; + + $updateResult = $collection->updateMany( + [ 'borough' => 'Queens' ], + [ '$set' => [ 'active' => true ]] + ); + + printf("Matched %d document(s)\n", $updateResult->getMatchedCount()); + printf("Modified %d document(s)\n", $updateResult->getModifiedCount()); + +The output would then resemble: + +.. code-block:: none + + Matched 5656 document(s) + Modified 5656 document(s) + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::replaceOne()` +- :phpmethod:`MongoDB\Collection::updateOne()` +- :phpmethod:`MongoDB\Collection::bulkWrite()` +- :doc:`/tutorial/crud` +- :manual:`update ` command reference in the MongoDB + manual diff --git a/source/reference/method/MongoDBCollection-updateOne.txt b/source/reference/method/MongoDBCollection-updateOne.txt new file mode 100644 index 00000000..42877e73 --- /dev/null +++ b/source/reference/method/MongoDBCollection-updateOne.txt @@ -0,0 +1,165 @@ +================================ +MongoDB\\Collection::updateOne() +================================ + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::updateOne() + + Update at most one document that matches the filter criteria. If multiple + documents match the filter criteria, only the :term:`first ` + matching document will be updated. + + .. code-block:: php + + function updateOne( + array|object $filter, + array|object $update, + array $options = [] + ): MongoDB\UpdateResult + +Parameters +---------- + +``$filter`` : array|object + The filter criteria that specifies the documents to update. + +``$update`` : array|object + Specifies the field and value combinations to update and any relevant update + operators. ``$update`` uses MongoDB's :manual:`update operators + `. Starting with MongoDB 4.2, an `aggregation + pipeline `_ + can be passed as this parameter. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - arrayFilters + - array + - An array of filter documents that determines which array elements to modify + for an update operation on an array field. + + .. versionadded:: 1.3 + + * - bypassDocumentValidation + - boolean + - If ``true``, allows the write operation to circumvent document level + validation. Defaults to ``false``. + + * - collation + - array|object + - .. include:: /includes/extracts/collection-option-collation.rst + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.13 + + * - hint + - string|array|object + - .. include:: /includes/extracts/common-option-hint.rst + + .. include:: /includes/extracts/option-requires-4.2.rst + + .. versionadded:: 1.6 + + * - let + - array|object + - .. include:: /includes/extracts/common-option-let.rst + + .. versionadded:: 1.13 + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + .. versionadded:: 1.3 + + * - upsert + - boolean + - If set to ``true``, creates a new document when no document matches the + query criteria. The default value is ``false``, which does not insert a + new document when no match is found. + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - .. include:: /includes/extracts/collection-option-writeConcern.rst + + .. include:: /includes/extracts/common-option-writeConcern-transaction.rst + +Return Values +------------- + +A :phpclass:`MongoDB\UpdateResult` object, which encapsulates a +:php:`MongoDB\Driver\WriteResult ` object. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-bulkwriteexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Behavior +-------- + +.. include:: /includes/extracts/note-bson-comparison.rst +.. include:: /includes/extracts/bulkwriteexception-result.rst + +Examples +-------- + +The following example updates one document with the ``restaurant_id`` of +``"40356151"`` by setting the ``name`` field to ``"Brunos on Astoria"``: + +.. code-block:: php + + test->restaurants; + + $updateResult = $collection->updateOne( + [ 'restaurant_id' => '40356151' ], + [ '$set' => [ 'name' => 'Brunos on Astoria' ]] + ); + + printf("Matched %d document(s)\n", $updateResult->getMatchedCount()); + printf("Modified %d document(s)\n", $updateResult->getModifiedCount()); + +The output would then resemble: + +.. code-block:: none + + Matched 1 document(s) + Modified 1 document(s) + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::replaceOne()` +- :phpmethod:`MongoDB\Collection::updateMany()` +- :phpmethod:`MongoDB\Collection::bulkWrite()` +- :doc:`/tutorial/crud` +- :manual:`update ` command reference in the MongoDB + manual diff --git a/source/reference/method/MongoDBCollection-updateSearchIndex.txt b/source/reference/method/MongoDBCollection-updateSearchIndex.txt new file mode 100644 index 00000000..63b62167 --- /dev/null +++ b/source/reference/method/MongoDBCollection-updateSearchIndex.txt @@ -0,0 +1,80 @@ +======================================== +MongoDB\\Collection::updateSearchIndex() +======================================== + +.. versionadded:: 1.17 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::updateSearchIndex() + + Update an Atlas Search index for the collection. + + .. code-block:: php + + function updateSearchIndex( + string $name, + array|object $definition, + array $options = [] + ): void + + .. include:: /includes/extracts/note-atlas-search-requirement.rst + +Parameters +---------- + +``$name`` : string + Name of the index to update. + +``$definition`` : array|object + Document describing the updated search index definition. The specified + definition replaces the prior definition in the search index. For details on + definition syntax, see + :manual:`Search Index Definition Syntax `. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Behavior +-------- + +.. include:: /includes/extracts/note-atlas-search-async.rst + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::createSearchIndex()` +- :phpmethod:`MongoDB\Collection::createSearchIndexes()` +- :phpmethod:`MongoDB\Collection::dropSearchIndex()` +- :phpmethod:`MongoDB\Collection::listSearchIndexes()` +- :manual:`updateSearchIndex ` command + reference in the MongoDB manual +- `Atlas Search `__ documentation in the MongoDB Manual diff --git a/source/reference/method/MongoDBCollection-watch.txt b/source/reference/method/MongoDBCollection-watch.txt new file mode 100644 index 00000000..083e129b --- /dev/null +++ b/source/reference/method/MongoDBCollection-watch.txt @@ -0,0 +1,208 @@ +============================ +MongoDB\\Collection::watch() +============================ + +.. versionadded:: 1.3 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::watch() + + Executes a :manual:`change stream ` operation on the + collection. The change stream can be watched for collection-level changes. + + .. code-block:: php + + function watch( + array $pipeline = [], + array $options = [] + ): MongoDB\ChangeStream + +Parameters +---------- + +``$pipeline`` : array|object + The pipeline of stages to append to an initial ``$changeStream`` stage. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - batchSize + - integer + - .. include:: /includes/extracts/watch-option-batchSize.rst + + * - codec + - MongoDB\\Codec\\DocumentCodec + - .. include:: /includes/extracts/collection-option-codec.rst + + .. versionadded:: 1.17 + + * - collation + - array|object + - .. include:: /includes/extracts/common-option-collation.rst + + Starting in MongoDB 4.2, defaults to simple binary comparison if + omitted. In earlier versions, change streams opened on a single + collection would inherit the collection's default collation. + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/common-option-comment-string-before-4.4.rst + + .. versionadded:: 1.13 + + * - fullDocument + - string + - .. include:: /includes/extracts/watch-option-fullDocument.rst + + * - fullDocumentBeforeChange + - string + - .. include:: /includes/extracts/watch-option-fullDocumentBeforeChange.rst + + * - maxAwaitTimeMS + - integer + - .. include:: /includes/extracts/watch-option-maxAwaitTimeMS.rst + + * - readConcern + - :php:`MongoDB\Driver\ReadConcern ` + - .. include:: /includes/extracts/collection-option-readConcern.rst + + * - readPreference + - :php:`MongoDB\Driver\ReadPreference ` + - .. include:: /includes/extracts/collection-option-readPreference.rst + + This is used for both the initial change stream aggregation and for + server selection during an automatic resume. + + * - resumeAfter + - array|object + - .. include:: /includes/extracts/watch-option-resumeAfter.rst + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + * - showExpandedEvents + - boolean + - .. include:: /includes/extracts/watch-option-showExpandedEvents.rst + + * - startAfter + - array|object + - .. include:: /includes/extracts/watch-option-startAfter.rst + + * - startAtOperationTime + - :php:`MongoDB\BSON\TimestampInterface ` + - .. include:: /includes/extracts/watch-option-startAtOperationTime.rst + + * - typeMap + - array + - .. include:: /includes/extracts/collection-option-typeMap.rst + +Return Values +------------- + +A :phpclass:`MongoDB\ChangeStream` object, which allows for iteration of +events in the change stream via the :php:`Iterator ` interface. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unexpectedvalueexception.rst +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Examples +-------- + +This example reports events while iterating a change stream. + +.. code-block:: php + + test->inventory; + + $changeStream = $collection->watch(); + + for ($changeStream->rewind(); true; $changeStream->next()) { + if ( ! $changeStream->valid()) { + continue; + } + + $event = $changeStream->current(); + + if ($event['operationType'] === 'invalidate') { + break; + } + + $ns = sprintf('%s.%s', $event['ns']['db'], $event['ns']['coll']); + $id = json_encode($event['documentKey']['_id']); + + switch ($event['operationType']) { + case 'delete': + printf("Deleted document in %s with _id: %s\n\n", $ns, $id); + break; + + case 'insert': + printf("Inserted new document in %s\n", $ns); + echo json_encode($event['fullDocument']), "\n\n"; + break; + + case 'replace': + printf("Replaced new document in %s with _id: %s\n", $ns, $id); + echo json_encode($event['fullDocument']), "\n\n"; + break; + + case 'update': + printf("Updated document in %s with _id: %s\n", $ns, $id); + echo json_encode($event['updateDescription']), "\n\n"; + break; + } + } + +Assuming that a document was inserted, updated, and deleted while the above +script was iterating the change stream, the output would then resemble: + +.. code-block:: none + + Inserted new document in test.user + {"_id":{"$oid":"5b329c4874083047cc05e60a"},"username":"bob"} + + Inserted new document in test.products + {"_id":{"$oid":"5b329c4d74083047cc05e60b"},"name":"Widget","quantity":5} + + Updated document in test.user with _id: {"$oid":"5b329a4f74083047cc05e603"} + {"updatedFields":{"username":"robert"},"removedFields":[]} + +See Also +-------- + +- :phpmethod:`MongoDB\Client::watch()` +- :phpmethod:`MongoDB\Database::watch()` +- :manual:`Aggregation Pipeline ` documentation in + the MongoDB Manual +- :manual:`Change Streams ` documentation in the MongoDB manual +- :manual:`Change Events ` documentation in the + MongoDB manual diff --git a/source/reference/method/MongoDBCollection-withOptions.txt b/source/reference/method/MongoDBCollection-withOptions.txt new file mode 100644 index 00000000..8123904b --- /dev/null +++ b/source/reference/method/MongoDBCollection-withOptions.txt @@ -0,0 +1,96 @@ +================================== +MongoDB\\Collection::withOptions() +================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::withOptions() + + Returns a clone of the Collection object, but with different options. + + .. code-block:: php + + function withOptions(array $options = []): MongoDB\Collection + +Parameters +---------- + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - codec + - MongoDB\\Codec\\DocumentCodec + - The default :doc:`codec ` to use for collection + operations. Defaults to the original collection's codec. + + .. versionadded:: 1.17 + + * - readConcern + - :php:`MongoDB\Driver\ReadConcern ` + - The default read concern to use for collection operations. Defaults to + the original collection's read concern. + + * - readPreference + - :php:`MongoDB\Driver\ReadPreference ` + - The default read preference to use for collection operations. Defaults + to the original collection's read preference. + + * - typeMap + - array + - The :php:`type map + ` + to apply to cursors, which determines how BSON documents are converted + to PHP values. Defaults to the original collection's type map. + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - The default write concern to use for collection operations. Defaults to + the original collection's write concern. + +Return Values +------------- + +A :phpclass:`MongoDB\Collection` object. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-invalidargumentexception.rst + +Example +------- + +The following example clones an existing Collection object with a new read +preference: + +.. code-block:: php + + selectCollection('test', 'restaurants'); + + $newCollection = $sourceCollection->withOptions([ + 'readPreference' => new MongoDB\Driver\ReadPreference('primaryPreferred'), + ]); + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::__construct()` diff --git a/source/reference/method/MongoDBCollection__construct.txt b/source/reference/method/MongoDBCollection__construct.txt new file mode 100644 index 00000000..a7480447 --- /dev/null +++ b/source/reference/method/MongoDBCollection__construct.txt @@ -0,0 +1,111 @@ +================================== +MongoDB\\Collection::__construct() +================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Collection::__construct() + + Constructs a new :phpclass:`Collection ` instance. + + .. code-block:: php + + function __construct( + MongoDB\Driver\Manager $manager, + string $databaseName, + string $collectionName, + array $options = [] + ) + + This constructor has the following parameters: + +``$manager`` : :php:`MongoDB\Driver\Manager ` + The :php:`Manager ` instance from the driver. The + manager maintains connections between the driver and your MongoDB instances. + +``$databaseName`` : string + The name of the database. + +``$collectionName`` : string + The name of the collection. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - codec + - MongoDB\\Codec\\DocumentCodec + - The default :doc:`codec ` to use for collection + operations. + + .. versionadded:: 1.17 + + * - readConcern + - :php:`MongoDB\Driver\ReadConcern ` + - The default read concern to use for collection operations. Defaults to + the manager's read concern. + + * - readPreference + - :php:`MongoDB\Driver\ReadPreference ` + - The default read preference to use for collection operations. Defaults + to the manager's read preference. + + * - typeMap + - array + - Default :php:`type map + ` + to apply to cursors, which determines how BSON documents are converted + to PHP values. The library uses the following type map by default: + + .. code-block:: php + + [ + 'array' => 'MongoDB\Model\BSONArray', + 'document' => 'MongoDB\Model\BSONDocument', + 'root' => 'MongoDB\Model\BSONDocument', + ] + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - The default write concern to use for collection operations. Defaults + to the manager's write concern. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-invalidargumentexception.rst + +Behavior +-------- + +If you construct a Collection explicitly, the Collection inherits any options +from the :php:`MongoDB\Driver\Manager ` object. +If you select the Collection from a :phpclass:`Client ` or +:phpclass:`Database ` object, the Collection inherits its +options from that object. + +.. todo: add an example + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::withOptions()` +- :phpmethod:`MongoDB\Client::selectCollection()` +- :phpmethod:`MongoDB\Database::selectCollection()` +- :phpmethod:`MongoDB\Database::__get()` diff --git a/source/reference/method/MongoDBDatabase-aggregate.txt b/source/reference/method/MongoDBDatabase-aggregate.txt new file mode 100644 index 00000000..8c022586 --- /dev/null +++ b/source/reference/method/MongoDBDatabase-aggregate.txt @@ -0,0 +1,177 @@ +============================== +MongoDB\\Database::aggregate() +============================== + +.. versionadded:: 1.5 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Database::aggregate() + + Runs a specified :manual:`admin/diagnostic pipeline + ` which does + not require an underlying collection. For aggregations on collection data, + see :phpmethod:`MongoDB\Collection::aggregate()`. + + .. code-block:: php + + function aggregate( + array $pipeline, + array $options = [] + ): Traversable + +Parameters +---------- + +``$pipeline`` : array + Specifies an :manual:`aggregation pipeline ` + operation. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - allowDiskUse + - boolean + - Enables writing to temporary files. When set to ``true``, aggregation + stages can write data to the ``_tmp`` sub-directory in the ``dbPath`` + directory. + + * - batchSize + - integer + - Specifies the batch size for the cursor, which will apply to both the + initial ``aggregate`` command and any subsequent ``getMore`` commands. + This determines the maximum number of documents to return in each + response from the server. + + A batchSize of ``0`` is special in that and will only apply to the + initial ``aggregate`` command; subsequent ``getMore`` commands will use + the server's default batch size. This may be useful for quickly + returning a cursor or failure from ``aggregate`` without doing + significant server-side work. + + * - bypassDocumentValidation + - boolean + - If ``true``, allows the write operation to circumvent document level + validation. Defaults to ``false``. + + This only applies when using the :ref:`$out ` and + :ref:`$out ` stages. + + * - codec + - MongoDB\\Codec\\DocumentCodec + - .. include:: /includes/extracts/common-option-codec.rst + + .. versionadded:: 1.17 + + * - collation + - array|object + - .. include:: /includes/extracts/common-option-collation.rst + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + The comment can be any valid BSON type for server versions 4.4 and + above. Earlier server versions only support string values. + + * - explain + - boolean + - Specifies whether or not to return the information on the processing of + the pipeline. + + * - hint + - string|array|object + - .. include:: /includes/extracts/common-option-hint.rst + + * - let + - array|object + - .. include:: /includes/extracts/common-option-let.rst + + .. versionadded:: 1.9 + + * - maxTimeMS + - integer + - .. include:: /includes/extracts/common-option-maxTimeMS.rst + + * - readConcern + - :php:`MongoDB\Driver\ReadConcern ` + - .. include:: /includes/extracts/database-option-readConcern.rst + + * - readPreference + - :php:`MongoDB\Driver\ReadPreference ` + - .. include:: /includes/extracts/database-option-readPreference.rst + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + * - typeMap + - array + - .. include:: /includes/extracts/database-option-typeMap.rst + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - .. include:: /includes/extracts/database-option-writeConcern.rst + +Return Values +------------- + +A :php:`MongoDB\Driver\Cursor ` or +:php:`ArrayIterator ` object. In both cases, the return value +will be :php:`Traversable `. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unexpectedvalueexception.rst +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +.. _php-db-agg-method-behavior: + +Examples +-------- + +The following aggregation example lists all running commands using the +``$currentOp`` aggregation pipeline stage, then filters this list to only show +running command operations. + +.. code-block:: php + + admin; + + $cursor = $database->aggregate( + [ + ['$currentOp' => []], + ['$match' => ['op' => 'command'], + ] + ); + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::aggregate()` +- :manual:`aggregate ` command reference in the + MongoDB manual +- :manual:`Aggregation Pipeline ` documentation in + the MongoDB Manual diff --git a/source/reference/method/MongoDBDatabase-command.txt b/source/reference/method/MongoDBDatabase-command.txt new file mode 100644 index 00000000..86243d73 --- /dev/null +++ b/source/reference/method/MongoDBDatabase-command.txt @@ -0,0 +1,173 @@ +============================ +MongoDB\\Database::command() +============================ + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Database::command() + + Execute a :manual:`command ` on the database. This is + generally used to execute commands that do not have a corresponding helper + method within the library. + + .. code-block:: php + + function command( + array|object $command, + array $options = [] + ): MongoDB\Driver\Cursor + +Parameters +---------- + +``$command`` : array|object + The :manual:`database command ` document. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - readPreference + - :php:`MongoDB\Driver\ReadPreference ` + - .. include:: /includes/extracts/database-option-readPreference.rst + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + .. versionadded:: 1.3 + + * - typeMap + - array + - .. include:: /includes/extracts/database-option-typeMap.rst + +Return Values +------------- + +A :php:`MongoDB\Driver\Cursor ` object. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Example +------- + +Most database commands return a single result document, which can be obtained by +converting the returned cursor to an array and accessing its first element. The +following example executes a :manual:`ping ` command +and prints its result document: + +.. code-block:: php + + test; + + $cursor = $database->command(['ping' => 1]); + + var_dump($cursor->toArray()[0]); + +The output would resemble: + +.. code-block:: none + + object(MongoDB\Model\BSONDocument)#11 (1) { + ["storage":"ArrayObject":private]=> + array(1) { + ["ok"]=> + float(1) + } + } + +Some database commands return a cursor with multiple results. The following +example executes :manual:`listCollections `, +which returns a cursor containing a result document for each collection in the +``test`` database. Note that this example is illustrative; applications would +generally use :phpmethod:`MongoDB\Database::listCollections()` in practice. + +.. code-block:: php + + test; + + $cursor = $database->command(['listCollections' => 1]); + + var_dump($cursor->toArray()); + +The output would resemble: + +.. code-block:: none + + array(3) { + [0]=> + object(MongoDB\Model\BSONDocument)#11 (1) { + ["storage":"ArrayObject":private]=> + array(2) { + ["name"]=> + string(11) "restaurants" + ["options"]=> + object(MongoDB\Model\BSONDocument)#3 (1) { + ["storage":"ArrayObject":private]=> + array(0) { + } + } + } + } + [1]=> + object(MongoDB\Model\BSONDocument)#13 (1) { + ["storage":"ArrayObject":private]=> + array(2) { + ["name"]=> + string(5) "users" + ["options"]=> + object(MongoDB\Model\BSONDocument)#12 (1) { + ["storage":"ArrayObject":private]=> + array(0) { + } + } + } + } + [2]=> + object(MongoDB\Model\BSONDocument)#15 (1) { + ["storage":"ArrayObject":private]=> + array(2) { + ["name"]=> + string(6) "restos" + ["options"]=> + object(MongoDB\Model\BSONDocument)#14 (1) { + ["storage":"ArrayObject":private]=> + array(0) { + } + } + } + } + } + +See Also +-------- + +- :doc:`/tutorial/commands` +- :manual:`Database Commands ` in the MongoDB manual +- :php:`MongoDB\Driver\Cursor ` +- :php:`MongoDB\Driver\Manager::executeCommand() + ` diff --git a/source/reference/method/MongoDBDatabase-createCollection.txt b/source/reference/method/MongoDBDatabase-createCollection.txt new file mode 100644 index 00000000..8b49e901 --- /dev/null +++ b/source/reference/method/MongoDBDatabase-createCollection.txt @@ -0,0 +1,380 @@ +===================================== +MongoDB\\Database::createCollection() +===================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Database::createCollection() + + Explicitly creates a collection. + + .. code-block:: php + + function createCollection( + string $collectionName, + array $options = [] + ): array|object + + MongoDB creates collections implicitly when you first reference the + collection in a command, such as when inserting a document into a new + collection. You may also explicitly create a collection with specific options + using the :phpmethod:`MongoDB\Database::createCollection()` method, or using + :manual:`db.createCollection() ` in + the MongoDB shell. + + Explicitly creating collections enables you to create + :manual:`capped collections `, specify + :manual:`document validation criteria `, + or configure your storage engine or indexing options. + +Parameters +---------- + +``$collectionName`` : string + The name of the collection to create. + +``$options`` : array + An array specifying the desired options. + + .. note:: + + Not all options are available on all versions of MongoDB. Refer to the + :manual:`create ` command reference in the + MongoDB manual for compatibility considerations. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - autoIndexId + - boolean + - Specify ``false`` to disable the automatic creation of an index on the + ``_id`` field. + + .. important:: + + For replica sets, do not set ``autoIndexId`` to ``false``. + + .. deprecated:: 1.4 + This option has been deprecated since MongoDB 3.2. As of MongoDB + 4.0, this option cannot be ``false`` when creating a replicated + collection (i.e. a collection outside of the ``local`` database in + any mongod mode). + + * - capped + - boolean + - To create a capped collection, specify ``true``. If you specify + ``true``, you must also set a maximum size in the ``size`` option. + + * - changeStreamPreAndPostImages + - document + - Used to configure support for pre- and post-images in change streams. + See the :manual:`create ` command + documentation for more information. + + .. include:: /includes/extracts/option-requires-6.0.rst + + .. versionadded:: 1.13 + + * - clusteredIndex + - document + - A clustered index specification. See + :manual:`Clustered Collections ` or the + :manual:`create ` command documentation for + more information. + + .. include:: /includes/extracts/option-requires-5.3.rst + + .. versionadded:: 1.13 + + * - collation + - array|object + - .. include:: /includes/extracts/common-option-collation.rst + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.13 + + * - encryptedFields + - document + - A document describing encrypted fields for queryable encryption. If + omitted, the ``encryptedFieldsMap`` option within the + ``autoEncryption`` driver option will be consulted. See + `Field Encryption and Queryability `_ + in the MongoDB manual for more information. + + .. include:: /includes/extracts/option-requires-7.0.rst + + .. versionadded:: 1.13 + + * - expireAfterSeconds + - integer + - Used to automatically delete documents in time series collections. See + the :manual:`create ` command documentation + for more information. + + .. include:: /includes/extracts/option-requires-5.0.rst + + .. versionadded:: 1.9 + + * - flags + - integer + - Available for the MMAPv1 storage engine only to set the + ``usePowerOf2Sizes`` and ``noPadding`` flags. + + The library provides constants that you can combine with a + :php:`bitwise OR operator ` to set the flag + values: + + - ``MongoDB\Operation\CreateCollection::USE_POWER_OF_2_SIZES``: ``1`` + - ``MongoDB\Operation\CreateCollection::NO_PADDING``: ``2`` + + Defaults to ``1``. + + .. note:: + + MongoDB 3.0 and later ignores the ``usePowerOf2Sizes`` flag. See + :manual:`collMod ` and + :manual:`db.createCollection() + ` for more information. + + * - indexOptionDefaults + - array|object + - Allows users to specify a default configuration for indexes when + creating a collection. + + The ``indexOptionDefaults`` option accepts a ``storageEngine`` + document, which should take the following form: + + .. code-block:: none + + { : } + + Storage engine configurations specified when creating indexes are + validated and logged to the :term:`oplog` during replication to support + replica sets with members that use different storage engines. + + * - max + - integer + - The maximum number of documents allowed in the capped collection. The + ``size`` option takes precedence over this limit. If a capped + collection reaches the ``size`` limit before it reaches the maximum + number of documents, MongoDB removes old documents. If you prefer to + use the ``max`` limit, ensure that the ``size`` limit, which is + required for a capped collection, is sufficient to contain the maximum + number of documents. + + * - maxTimeMS + - integer + - .. include:: /includes/extracts/common-option-maxTimeMS.rst + + * - pipeline + - array + - An array that consists of the aggregation pipeline stage(s), which will + be applied to the collection or view specified by ``viewOn``. See the + :manual:`create ` command documentation for + more information. + + .. versionadded:: 1.13 + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + .. versionadded:: 1.3 + + * - size + - integer + - Specify a maximum size in bytes for a capped collection. Once a capped + collection reaches its maximum size, MongoDB removes the older + documents to make space for the new documents. The ``size`` option is + required for capped collections and ignored for other collections. + + * - storageEngine + - array|object + - Available for the WiredTiger storage engine only. + + Allows users to specify configuration to the storage engine on a + per-collection basis when creating a collection. The value of the + ``storageEngine`` option should take the following form: + + .. code-block:: none + + { : } + + Storage engine configurations specified when creating collections are + validated and logged to the :term:`oplog` during replication to support + replica sets with members that use different storage engines. + + * - timeseries + - array|object + - An object containing options for creating time series collections. See + the :manual:`create ` command documentation + for supported options. + + .. include:: /includes/extracts/option-requires-5.0.rst + + .. versionadded:: 1.9 + + * - typeMap + - array + - .. include:: /includes/extracts/database-option-typeMap.rst + + This will be used for the returned command result document. + + * - validationAction + - string + - Determines whether to ``error`` on invalid documents or just ``warn`` + about the violations but allow invalid documents to be inserted. + + .. important:: + + Validation of documents only applies to those documents as + determined by the ``validationLevel``. + + .. list-table:: + :header-rows: 1 + + * - ``validationAction`` + - Description + + * - ``"error"`` + - **Default**. Documents must pass validation before the write + occurs. Otherwise, the write operation fails. + + * - ``"warn"`` + - Documents do not have to pass validation. If the document fails + validation, the write operation logs the validation failure. + + * - validationLevel + - string + - Determines how strictly MongoDB applies the validation rules to + existing documents during an update. + + .. list-table:: + :header-rows: 1 + + * - ``validationLevel`` + - Description + + * - ``"off"`` + - No validation for inserts or updates. + + * - ``"strict"`` + - **Default**. Apply validation rules to all inserts and all updates. + + * - ``"moderate"`` + - Apply validation rules to inserts and to updates on existing + *valid* documents. Do not apply rules to updates on existing + *invalid* documents. + + * - validator + - array|object + - Allows users to specify :manual:`validation rules or expressions + ` for the collection. For more information, + see :manual:`Document Validation ` in the + MongoDB manual. + + The ``validator`` option takes an array that specifies the validation + rules or expressions. You can specify the expressions using the same + operators as MongoDB's + :manual:`query operators ` with the + exception of :query:`$near`, :query:`$nearSphere`, + :query:`$text`, and :query:`$where`. + + .. note:: + + - Validation occurs during updates and inserts. Existing documents + do not undergo validation checks until modification. + + - You cannot specify a validator for collections in the ``admin``, + ``local``, and ``config`` databases. + + - You cannot specify a validator for ``system.*`` collections. + + * - viewOn + - string + - The name of the source collection or view from which to create the view. + + .. note:: + + The name is not the full namespace of the collection or view (i.e. + it does not include the database name). Views must be created in the + same databases as the source collection or view. + + .. versionadded:: 1.13 + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - .. include:: /includes/extracts/database-option-writeConcern.rst + +Return Values +------------- + +An array or object with the result document of the :manual:`create +` command. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Example +------- + +The following example creates a ``users`` collection in the ``test`` +database with document validation criteria: + +.. code-block:: php + + test; + + $result = $db->createCollection('users', [ + 'validator' => [ + 'username' => ['$type' => 'string'], + 'email' => ['$regex' => '@mongodb\.com$'], + ], + ]); + + var_dump($result); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Model\BSONDocument)#11 (1) { + ["storage":"ArrayObject":private]=> + array(1) { + ["ok"]=> + float(1) + } + } + +See Also +-------- + +- :manual:`create ` command reference in the MongoDB + manual +- :manual:`db.createCollection() ` +- :manual:`Time Series Collections ` diff --git a/source/reference/method/MongoDBDatabase-createEncryptedCollection.txt b/source/reference/method/MongoDBDatabase-createEncryptedCollection.txt new file mode 100644 index 00000000..e6a266fb --- /dev/null +++ b/source/reference/method/MongoDBDatabase-createEncryptedCollection.txt @@ -0,0 +1,162 @@ +============================================== +MongoDB\\Database::createEncryptedCollection() +============================================== + +.. versionadded:: 1.16 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Database::createEncryptedCollection() + + Explicitly creates an encrypted collection. + + .. code-block:: php + + function createEncryptedCollection( + string $collectionName, + MongoDB\Driver\ClientEncryption $clientEncryption, + string $kmsProvider, + ?array $masterKey, + array $options + ): array + + This method will automatically create data keys for any encrypted fields + where ``keyId`` is ``null``. Data keys will be created using + :php:`MongoDB\Driver\ClientEncryption::createDataKey() ` + and the provided ``$kmsProvider`` and ``$masterKey`` parameters. A copy of + the modified ``encryptedFields`` option will be returned in addition to the + result from creating the collection. + + This method does not affect any auto encryption settings on existing + :phpclass:`MongoDB\Client` objects. Users must configure auto encryption + after creating the encrypted collection with ``createEncryptedCollection()``. + +Parameters +---------- + +``$collectionName`` : string + The name of the encrypted collection to create. + +``$clientEncryption`` : :php:`MongoDB\Driver\ClientEncryption ` + The ClientEncryption object used to create data keys. + +``$kmsProvider`` : string + KMS provider (e.g. "local", "aws") that will be used to encrypt new data keys. + This corresponds to the ``$kmsProvider`` parameter for + :php:`MongoDB\Driver\ClientEncryption::createDataKey() `. + +``$masterKey`` : array|null + KMS-specific key options that will be used to encrypt new data keys. This + corresponds to the ``masterKey`` option for + :php:`MongoDB\Driver\ClientEncryption::createDataKey() `. + + If ``$kmsProvider`` is "local", this should be ``null``. + +``$options`` : array + An array specifying the desired options. + + The ``$options`` parameter supports the same options as + :phpmethod:`MongoDB\Database::createCollection()`. The ``encryptedFields`` + option is required. + +Return Values +------------- + +A tuple (i.e. two-element array) containing the result document from the +:manual:`create ` command (an array or object +according to the ``typeMap`` option) and the modified ``encryptedFields`` +option. + +Errors/Exceptions +----------------- + +:phpclass:`MongoDB\Exception\CreateEncryptedCollectionException` if any error +is encountered creating data keys or the collection. The original exception and +modified ``encryptedFields`` option can be accessed via the ``getPrevious()`` +and ``getEncryptedFields()`` methods, respectively. + +.. include:: /includes/extracts/error-invalidargumentexception.rst + +Example +------- + +The following example creates an encrypted ``users`` collection in the ``test`` +database. The ``ssn`` field within the ``users`` collection will be defined as +an encrypted string field. + +.. code-block:: php + + createClientEncryption([ + 'keyVaultNamespace' => 'keyvault.datakeys', + 'kmsProviders' => [ + 'local' => ['key' => new MongoDB\BSON\Binary(base64_decode(LOCAL_MASTERKEY), 0)], + ], + ); + + [$result, $encryptedFields] = $client->test->createEncryptedCollection( + 'users', + $clientEncryption, + 'local', + null, + [ + 'encryptedFields' => [ + 'fields' => [ + ['path' => 'ssn', 'bsonType' => 'string', 'keyId' => null], + ], + ], + ] + ); + +If the encrypted collection was successfully created, ``$result`` will contain +the response document from the ``create`` command and +``$encryptedFields['fields'][0]['keyId']`` will contain a +:php:`MongoDB\BSON\Binary ` object with subtype 4 +(i.e. UUID). + +The modified ``encryptedFields`` option can then be used to construct a new +:phpclass:`MongoDB\Client` with auto encryption enabled. + +.. code-block:: php + + [ + 'keyVaultNamespace' => 'keyvault.datakeys', + 'kmsProviders' => [ + 'local' => ['key' => new MongoDB\BSON\Binary(base64_decode(LOCAL_MASTERKEY), 0)], + ], + 'encryptedFieldsMap' => [ + 'test.users' => $encryptedFields, + ], + ], + ] + ); + +See Also +-------- + +- :phpmethod:`MongoDB\Database::createCollection()` +- :phpmethod:`MongoDB\Client::createClientEncryption()` +- :php:`MongoDB\Driver\ClientEncryption::createDataKey() ` +- :manual:`create ` command reference in the MongoDB + manual diff --git a/source/reference/method/MongoDBDatabase-drop.txt b/source/reference/method/MongoDBDatabase-drop.txt new file mode 100644 index 00000000..da1c8ba0 --- /dev/null +++ b/source/reference/method/MongoDBDatabase-drop.txt @@ -0,0 +1,110 @@ +========================= +MongoDB\\Database::drop() +========================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Database::drop() + + Drop the database. + + .. code-block:: php + + function drop(array $options = []): array|object + +Parameters +---------- + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.13 + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + .. versionadded:: 1.3 + + * - typeMap + - array + - .. include:: /includes/extracts/database-option-typeMap.rst + + This will be used for the returned command result document. + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - .. include:: /includes/extracts/database-option-writeConcern.rst + +Return Values +------------- + +An array or object with the result document of the :manual:`dropDatabase +` command. The return type will depend on the +``typeMap`` option. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Example +------- + +The following example drops the ``test`` database: + +.. code-block:: php + + test; + + $result = $db->drop(); + + var_dump($result); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Model\BSONDocument)#8 (1) { + ["storage":"ArrayObject":private]=> + array(2) { + ["dropped"]=> + string(4) "test" + ["ok"]=> + float(1) + } + } + +See Also +-------- + +- :phpmethod:`MongoDB\Client::dropDatabase()` +- :manual:`dropDatabase ` command reference in + the MongoDB manual diff --git a/source/reference/method/MongoDBDatabase-dropCollection.txt b/source/reference/method/MongoDBDatabase-dropCollection.txt new file mode 100644 index 00000000..71beda83 --- /dev/null +++ b/source/reference/method/MongoDBDatabase-dropCollection.txt @@ -0,0 +1,138 @@ +=================================== +MongoDB\\Database::dropCollection() +=================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Database::dropCollection() + + Drop a collection within the current database. + + .. code-block:: php + + function dropCollection( + string $collectionName, + array $options = [] + ): array|object + +Parameters +---------- + +``$collectionName`` : string + The name of the collection to drop. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.13 + + * - encryptedFields + - array|object + - A document describing encrypted fields for queryable encryption. If + omitted, the ``encryptedFieldsMap`` option within the + ``autoEncryption`` driver option will be consulted. If + ``encryptedFieldsMap`` was defined but does not specify this + collection, the library will make a final attempt to consult the + server-side value for ``encryptedFields``. See + `Field Encryption and Queryability `_ + in the MongoDB manual for more information. + + .. note:: + + This option is not passed to the + :manual:`drop ` command. The library uses + it to determine related metadata collections that should be dropped + in addition to an encrypted collection. + + .. versionadded:: 1.13 + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + .. versionadded:: 1.3 + + * - typeMap + - array + - .. include:: /includes/extracts/database-option-typeMap.rst + + This will be used for the returned command result document. + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - .. include:: /includes/extracts/database-option-writeConcern.rst + +Return Values +------------- + +An array or object with the result document of the :manual:`drop +` command. The return type will depend on the +``typeMap`` option. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Example +------- + +The following example drops the ``users`` collection in the ``test`` database: + +.. code-block:: php + + test; + + $result = $db->dropCollection('users'); + + var_dump($result); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Model\BSONDocument)#8 (1) { + ["storage":"ArrayObject":private]=> + array(3) { + ["ns"]=> + string(10) "test.users" + ["nIndexesWas"]=> + int(1) + ["ok"]=> + float(1) + } + } + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::drop()` +- :manual:`drop ` command reference in the MongoDB + manual diff --git a/source/reference/method/MongoDBDatabase-getDatabaseName.txt b/source/reference/method/MongoDBDatabase-getDatabaseName.txt new file mode 100644 index 00000000..fcbd0ce8 --- /dev/null +++ b/source/reference/method/MongoDBDatabase-getDatabaseName.txt @@ -0,0 +1,46 @@ +==================================== +MongoDB\\Database::getDatabaseName() +==================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Database::getDatabaseName() + + Returns the name of this database. + + .. code-block:: php + + function getDatabaseName(): string + +Return Values +------------- + +The name of this database as a string. + +Example +------- + +The following example prints the name of a database object: + +.. code-block:: php + + test; + + echo $db->getDatabaseName(); + +The output would then resemble: + +.. code-block:: none + + test diff --git a/source/reference/method/MongoDBDatabase-getManager.txt b/source/reference/method/MongoDBDatabase-getManager.txt new file mode 100644 index 00000000..91e013ae --- /dev/null +++ b/source/reference/method/MongoDBDatabase-getManager.txt @@ -0,0 +1,35 @@ +=============================== +MongoDB\\Database::getManager() +=============================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Database::getManager() + + Accessor for the + :php:`MongoDB\Driver\Manager ` used by this + :phpclass:`Database `. + + .. code-block:: php + + function getManager(): MongoDB\Manager + +Return Values +------------- + +A :php:`MongoDB\Driver\Manager ` object. + +See Also +-------- + +- :phpmethod:`MongoDB\Client::getManager()` +- :phpmethod:`MongoDB\Collection::getManager()` diff --git a/source/reference/method/MongoDBDatabase-getReadConcern.txt b/source/reference/method/MongoDBDatabase-getReadConcern.txt new file mode 100644 index 00000000..4915fcc4 --- /dev/null +++ b/source/reference/method/MongoDBDatabase-getReadConcern.txt @@ -0,0 +1,60 @@ +=================================== +MongoDB\\Database::getReadConcern() +=================================== + +.. versionadded:: 1.2 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Database::getReadConcern() + + Returns the read concern for this database. + + .. code-block:: php + + function getReadConcern(): MongoDB\Driver\ReadConcern + +Return Values +------------- + +A :php:`MongoDB\Driver\ReadConcern ` object. + +Example +------- + +.. code-block:: php + + selectDatabase('test', [ + 'readConcern' => new MongoDB\Driver\ReadConcern('majority'), + ]); + + var_dump($database->getReadConcern()); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Driver\ReadConcern)#5 (1) { + ["level"]=> + string(8) "majority" + } + +See Also +-------- + +- :manual:`Read Concern ` in the MongoDB manual +- :php:`MongoDB\Driver\ReadConcern::isDefault() ` +- :phpmethod:`MongoDB\Client::getReadConcern()` +- :phpmethod:`MongoDB\Collection::getReadConcern()` +- :phpmethod:`MongoDB\GridFS\Bucket::getReadConcern()` diff --git a/source/reference/method/MongoDBDatabase-getReadPreference.txt b/source/reference/method/MongoDBDatabase-getReadPreference.txt new file mode 100644 index 00000000..633633eb --- /dev/null +++ b/source/reference/method/MongoDBDatabase-getReadPreference.txt @@ -0,0 +1,60 @@ +====================================== +MongoDB\\Database::getReadPreference() +====================================== + +.. versionadded:: 1.2 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Database::getReadPreference() + + Returns the read preference for this database. + + .. code-block:: php + + function getReadPreference(): MongoDB\Driver\ReadPreference + +Return Values +------------- + +A :php:`MongoDB\Driver\ReadPreference ` +object. + +Example +------- + +.. code-block:: php + + selectDatabase('test', [ + 'readPreference' => new MongoDB\Driver\ReadPreference('primaryPreferred'), + ]); + + var_dump($database->getReadPreference()); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Driver\ReadPreference)#5 (1) { + ["mode"]=> + string(16) "primaryPreferred" + } + +See Also +-------- + +- :manual:`Read Preference ` in the MongoDB manual +- :phpmethod:`MongoDB\Client::getReadPreference()` +- :phpmethod:`MongoDB\Collection::getReadPreference()` +- :phpmethod:`MongoDB\GridFS\Bucket::getReadPreference()` diff --git a/source/reference/method/MongoDBDatabase-getTypeMap.txt b/source/reference/method/MongoDBDatabase-getTypeMap.txt new file mode 100644 index 00000000..a30f4f0d --- /dev/null +++ b/source/reference/method/MongoDBDatabase-getTypeMap.txt @@ -0,0 +1,67 @@ +=============================== +MongoDB\\Database::getTypeMap() +=============================== + +.. versionadded:: 1.2 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Database::getTypeMap() + + Returns the type map for this database. + + .. code-block:: php + + function getTypeMap(): array + +Return Values +------------- + +A :ref:`type map ` array. + +Example +------- + +.. code-block:: php + + selectDatabase('test', [ + 'typeMap' => [ + 'root' => 'array', + 'document' => 'array', + 'array' => 'array', + ], + ]); + + var_dump($database->getTypeMap()); + +The output would then resemble: + +.. code-block:: none + + array(3) { + ["root"]=> + string(5) "array" + ["document"]=> + string(5) "array" + ["array"]=> + string(5) "array" + } + +See Also +-------- + +- :doc:`/reference/bson` +- :phpmethod:`MongoDB\Client::getTypeMap()` +- :phpmethod:`MongoDB\Collection::getTypeMap()` +- :phpmethod:`MongoDB\GridFS\Bucket::getTypeMap()` diff --git a/source/reference/method/MongoDBDatabase-getWriteConcern.txt b/source/reference/method/MongoDBDatabase-getWriteConcern.txt new file mode 100644 index 00000000..40419a4b --- /dev/null +++ b/source/reference/method/MongoDBDatabase-getWriteConcern.txt @@ -0,0 +1,63 @@ +==================================== +MongoDB\\Database::getWriteConcern() +==================================== + +.. versionadded:: 1.2 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Database::getWriteConcern() + + Returns the write concern for this database. + + .. code-block:: php + + function getWriteConcern(): MongoDB\Driver\WriteConcern + +Return Values +------------- + +A :php:`MongoDB\Driver\WriteConcern ` +object. + +Example +------- + +.. code-block:: php + + selectDatabase('test', [ + 'writeConcern' => new MongoDB\Driver\WriteConcern(1, 0, true), + ]); + + var_dump($database->getWriteConcern()); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Driver\WriteConcern)#5 (2) { + ["w"]=> + int(1) + ["j"]=> + bool(true) + } + +See Also +-------- + +- :manual:`Write Concern ` in the MongoDB manual +- :php:`MongoDB\Driver\WriteConcern::isDefault() ` +- :phpmethod:`MongoDB\Client::getWriteConcern()` +- :phpmethod:`MongoDB\Collection::getWriteConcern()` +- :phpmethod:`MongoDB\GridFS\Bucket::getWriteConcern()` diff --git a/source/reference/method/MongoDBDatabase-listCollectionNames.txt b/source/reference/method/MongoDBDatabase-listCollectionNames.txt new file mode 100644 index 00000000..d094028d --- /dev/null +++ b/source/reference/method/MongoDBDatabase-listCollectionNames.txt @@ -0,0 +1,142 @@ +======================================== +MongoDB\\Database::listCollectionNames() +======================================== + +.. versionadded:: 1.7 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Database::listCollectionNames() + + Returns names for all collections in this database. + + .. code-block:: php + + function listCollectionNames(array $options = []): Iterator + +Parameters +---------- + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - authorizedCollections + - boolean + - A flag that determines which collections are returned based on the user + privileges when access control is enabled. For more information, see + the :manual:`listCollections ` + command documentation. + + For servers < 4.0, this option is ignored. + + .. versionadded:: 1.12 + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.13 + + * - filter + - array|object + - A query expression to filter the list of collections. + + You can specify a query expression for collection fields (e.g. + ``name``, ``options``). + + * - maxTimeMS + - integer + - .. include:: /includes/extracts/common-option-maxTimeMS.rst + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + +Return Values +------------- + +An :php:`Iterator `, which provides the name of each +collection in the database. + +Example +------- + +The following example lists all of the collections in the ``test`` database: + +.. code-block:: php + + test; + + foreach ($database->listCollectionNames() as $collectionName) { + var_dump($collectionName); + } + +The output would then resemble: + +.. code-block:: none + + string(11) "restaurants" + string(5) "users" + string(6) "restos" + +The following example lists all collections whose name starts with ``"rest"`` +in the ``test`` database: + +.. code-block:: php + + test; + + $collections = $database->listCollectionNames([ + 'filter' => [ + 'name' => new MongoDB\BSON\Regex('^rest.*'), + ], + ]); + + foreach ($collections as $collectionName) { + var_dump($collectionName); + } + +The output would then resemble: + +.. code-block:: none + + string(11) "restaurants" + string(6) "restos" + +.. note:: + + When enumerating collection names, a filter expression can only filter based + on a collection's name and type. No other fields are available. + +See Also +-------- + +- :phpmethod:`MongoDB\Database::listCollections()` +- :manual:`listCollections ` command + reference in the MongoDB manual +- `Enumerating Collections + `_ + specification diff --git a/source/reference/method/MongoDBDatabase-listCollections.txt b/source/reference/method/MongoDBDatabase-listCollections.txt new file mode 100644 index 00000000..511b8995 --- /dev/null +++ b/source/reference/method/MongoDBDatabase-listCollections.txt @@ -0,0 +1,168 @@ +==================================== +MongoDB\\Database::listCollections() +==================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Database::listCollections() + + Returns information for all collections in this database. + + .. code-block:: php + + function listCollections(array $options = []): MongoDB\Model\CollectionInfoIterator + +Parameters +---------- + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - authorizedCollections + - boolean + - A flag that determines which collections are returned based on the user + privileges when access control is enabled. For more information, see + the :manual:`listCollections ` + command documentation. + + For servers < 4.0, this option is ignored. + + .. versionadded:: 1.12 + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.13 + + * - filter + - array|object + - A query expression to filter the list of collections. + + You can specify a query expression for collection fields (e.g. + ``name``, ``options``). + + * - maxTimeMS + - integer + - .. include:: /includes/extracts/common-option-maxTimeMS.rst + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + .. versionadded:: 1.3 + +Return Values +------------- + +A traversable :phpclass:`MongoDB\Model\CollectionInfoIterator`, which contains +a :phpclass:`MongoDB\Model\CollectionInfo` object for each collection in the +database. + +Example +------- + +The following example lists all of the collections in the ``test`` database: + +.. code-block:: php + + test; + + foreach ($database->listCollections() as $collectionInfo) { + var_dump($collectionInfo); + } + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Model\CollectionInfo)#3 (2) { + ["name"]=> + string(11) "restaurants" + ["options"]=> + array(0) { + } + } + object(MongoDB\Model\CollectionInfo)#3 (2) { + ["name"]=> + string(5) "users" + ["options"]=> + array(0) { + } + } + object(MongoDB\Model\CollectionInfo)#3 (2) { + ["name"]=> + string(6) "restos" + ["options"]=> + array(0) { + } + } + +The following example lists all collections whose name starts with ``"rest"`` +in the ``test`` database: + +.. code-block:: php + + test; + + $collections = $database->listCollections([ + 'filter' => [ + 'name' => new MongoDB\BSON\Regex('^rest.*'), + ], + ]); + + foreach ($collections as $collectionInfo) { + var_dump($collectionInfo); + } + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Model\CollectionInfo)#3 (2) { + ["name"]=> + string(11) "restaurants" + ["options"]=> + array(0) { + } + } + object(MongoDB\Model\CollectionInfo)#3 (2) { + ["name"]=> + string(6) "restos" + ["options"]=> + array(0) { + } + } + +See Also +-------- + +- :phpmethod:`MongoDB\Database::listCollectionNames()` +- :manual:`listCollections ` command + reference in the MongoDB manual +- `Enumerating Collections + `_ + specification diff --git a/source/reference/method/MongoDBDatabase-modifyCollection.txt b/source/reference/method/MongoDBDatabase-modifyCollection.txt new file mode 100644 index 00000000..6aa036ff --- /dev/null +++ b/source/reference/method/MongoDBDatabase-modifyCollection.txt @@ -0,0 +1,121 @@ +===================================== +MongoDB\\Database::modifyCollection() +===================================== + +.. versionadded:: 1.4 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Database::modifyCollection() + + Modifies a collection or view according to the specified + ``$collectionOptions``. + + .. code-block:: php + + function modifyCollection( + string $collectionName, + array $collectionOptions, + array $options = [] + ): array|object + +Parameters +---------- + +``$collectionName`` : string + The name of the collection or view to modify. + +``$collectionOptions`` : array + Collection or view options to assign. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.13 + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + * - typeMap + - array + - .. include:: /includes/extracts/database-option-typeMap.rst + + This will be used for the returned command result document. + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - .. include:: /includes/extracts/database-option-writeConcern.rst + +Return Values +------------- + +An array or object with the result document of the :manual:`collMod +` command. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Example +------- + +The following example changes the expiration time of a TTL collection in the +``test`` database: + +.. code-block:: php + + test; + + $result = $db->modifyCollection('users', [ + 'keyPattern' => ['lastAccess' => 1], + 'expireAfterSeconds' => 1000 + ]); + + var_dump($result); + +The output would then resemble: + +.. code-block:: none + + object(stdClass)#2779 { + ["expireAfterSeconds_old"]=> + int(3) + ["expireAfterSeconds_new"]=> + int(1000) + ["ok"]=> + float(1) + } + +See Also +-------- + +- :manual:`collMod ` command reference in the MongoDB + manual diff --git a/source/reference/method/MongoDBDatabase-renameCollection.txt b/source/reference/method/MongoDBDatabase-renameCollection.txt new file mode 100644 index 00000000..8c07952d --- /dev/null +++ b/source/reference/method/MongoDBDatabase-renameCollection.txt @@ -0,0 +1,131 @@ +===================================== +MongoDB\\Database::renameCollection() +===================================== + +.. versionadded:: 1.10 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Database::renameCollection() + + Rename a collection within the current database. + + .. code-block:: php + + function renameCollection( + string $fromCollectionName, + string $toCollectionName, + ?string $toDatabaseName = null, + array $options = [] + ): array|object + +Parameters +---------- + +``$fromCollectionName`` : string + The name of the collection to rename. + +``$toCollectionName`` : string + The new name of the collection. + +``$toDatabaseName`` : string + The new database name of the collection. If a new database name is not + specified, the current database will be used. If the new name specifies a + different database, the command copies the collection to the new database + and drops the source collection. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/option-requires-4.4.rst + + .. versionadded:: 1.13 + + * - dropTarget + - boolean + - If ``true``, MongoDB will drop the target before renaming the + collection. The default value is ``false``. + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + * - typeMap + - array + - .. include:: /includes/extracts/database-option-typeMap.rst + + This will be used for the returned command result document. + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - .. include:: /includes/extracts/database-option-writeConcern.rst + +Return Values +------------- + +An array or object with the result document of the :manual:`renameCollection +` command. The return type will depend on the +``typeMap`` option. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Example +------- + +The following example renames the ``restaurants`` collection in the ``test`` +database to ``places``: + +.. code-block:: php + + test; + + $result = $db->renameCollection('restaurants', 'places'); + + var_dump($result); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Model\BSONDocument)#8 (1) { + ["storage":"ArrayObject":private]=> + array(1) { + ["ok"]=> + float(1) + } + } + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::rename()` +- :manual:`renameCollection ` command reference in the MongoDB + manual diff --git a/source/reference/method/MongoDBDatabase-selectCollection.txt b/source/reference/method/MongoDBDatabase-selectCollection.txt new file mode 100644 index 00000000..b88179cd --- /dev/null +++ b/source/reference/method/MongoDBDatabase-selectCollection.txt @@ -0,0 +1,122 @@ +===================================== +MongoDB\\Database::selectCollection() +===================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Database::selectCollection() + + Selects a collection within the database. + + .. code-block:: php + + function selectCollection( + string $collectionName, + array $options = [] + ): MongoDB\Collection + +Parameters +---------- + +``$collectionName`` : string + The name of the collection to select. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - codec + - MongoDB\\Codec\\DocumentCodec + - The default :doc:`codec ` to use for collection + operations. + + .. versionadded:: 1.17 + + * - readConcern + - :php:`MongoDB\Driver\ReadConcern ` + - The default read concern to use for collection operations. Defaults to + the database's read concern. + + * - readPreference + - :php:`MongoDB\Driver\ReadPreference ` + - The default read preference to use for collection operations. Defaults + to the database's read preference. + + * - typeMap + - array + - The default type map to use for collection operations. Defaults to the + database's type map. + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - The default write concern to use for collection operations. Defaults to + the database's write concern. + +Return Values +------------- + +A :phpclass:`MongoDB\Collection` object. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-invalidargumentexception.rst + +Behavior +-------- + +The selected collection inherits options such as read preference and type +mapping from the :phpclass:`Database ` object. Options may be +overridden via the ``$options`` parameter. + +Example +------- + +The following example selects the ``users`` collection in the ``test`` database: + +.. code-block:: php + + test; + + $collection = $db->selectCollection('users'); + +The following example selects the ``users`` collection in the ``test`` +database with a custom read preference: + +.. code-block:: php + + test; + + $users = $db->selectCollection( + 'users', + [ + 'readPreference' => new MongoDB\Driver\ReadPreference('primaryPreferred'), + ] + ); + +See Also +-------- + +- :phpmethod:`MongoDB\Database::__get()` +- :phpmethod:`MongoDB\Client::selectCollection()` +- :phpmethod:`MongoDB\Collection::__construct()` diff --git a/source/reference/method/MongoDBDatabase-selectGridFSBucket.txt b/source/reference/method/MongoDBDatabase-selectGridFSBucket.txt new file mode 100644 index 00000000..6c624aa3 --- /dev/null +++ b/source/reference/method/MongoDBDatabase-selectGridFSBucket.txt @@ -0,0 +1,130 @@ +======================================= +MongoDB\\Database::selectGridFSBucket() +======================================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Database::selectGridFSBucket() + + Selects a GridFS bucket within the database. + + .. code-block:: php + + function selectGridFSBucket(array $options = []): MongoDB\GridFS\Bucket + +Parameters +---------- + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - bucketName + - string + - The bucket name, which will be used as a prefix for the files and + chunks collections. Defaults to ``"fs"``. + + * - chunkSizeBytes + - integer + - The chunk size in bytes. Defaults to ``261120`` (i.e. 255 KiB). + + * - codec + - MongoDB\\Codec\\DocumentCodec + - The default :doc:`codec ` to use for bucket methods + that return a file document (e.g. :phpmethod:`MongoDB\GridFS\Bucket::find()`). + + .. versionadded:: 1.17 + + * - disableMD5 + - boolean + - Whether to disable automatic MD5 generation when storing files. + + Defaults to ``false``. + + .. versionadded:: 1.4 + + * - readConcern + - :php:`MongoDB\Driver\ReadConcern ` + - The default read concern to use for bucket operations. Defaults to the + database's read concern. + + * - readPreference + - :php:`MongoDB\Driver\ReadPreference ` + - The default read preference to use for bucket operations. Defaults to + the database's read concern. + + * - typeMap + - array + - The default type map to use for bucket operations. Defaults to the + database's type map. + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - The default write concern to use for bucket operations. Defaults to the + database's write concern. + +Return Values +------------- + +A :phpclass:`MongoDB\GridFS\Bucket` object. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-invalidargumentexception.rst + +Behavior +-------- + +The selected bucket inherits options such as read preference and type +mapping from the :phpclass:`Database ` object. Options may be +overridden via the ``$options`` parameter. + +Example +------- + +The following example selects the default ``fs.files`` bucket in the ``test`` +database: + +.. code-block:: php + + test; + + $bucket = $db->selectGridFSBucket(); + +The following example selects the custom ``images.files`` bucket in the ``test`` +database with a custom read preference: + +.. code-block:: php + + test; + + $imagesBucket = $db->selectGridFSBucket([ + 'bucketName' => 'images', + 'readPreference' => new MongoDB\Driver\ReadPreference('primaryPreferred'), + ]); + +See Also +-------- + +- :phpmethod:`MongoDB\GridFS\Bucket::__construct()` diff --git a/source/reference/method/MongoDBDatabase-watch.txt b/source/reference/method/MongoDBDatabase-watch.txt new file mode 100644 index 00000000..d8c53763 --- /dev/null +++ b/source/reference/method/MongoDBDatabase-watch.txt @@ -0,0 +1,203 @@ +========================== +MongoDB\\Database::watch() +========================== + +.. versionadded:: 1.4 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Database::watch() + + Executes a :manual:`change stream ` operation on the + database. The change stream can be watched for database-level changes. + + .. code-block:: php + + function watch( + array $pipeline = [], + array $options = [] + ): MongoDB\ChangeStream + +Parameters +---------- + +``$pipeline`` : array|object + The pipeline of stages to append to an initial ``$changeStream`` stage. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - batchSize + - integer + - .. include:: /includes/extracts/watch-option-batchSize.rst + + * - codec + - MongoDB\\Codec\\DocumentCodec + - .. include:: /includes/extracts/common-option-codec.rst + + .. versionadded:: 1.17 + + * - collation + - array|object + - .. include:: /includes/extracts/common-option-collation.rst + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/common-option-comment-string-before-4.4.rst + + .. versionadded:: 1.13 + + * - fullDocument + - string + - .. include:: /includes/extracts/watch-option-fullDocument.rst + + * - fullDocumentBeforeChange + - string + - .. include:: /includes/extracts/watch-option-fullDocumentBeforeChange.rst + + * - maxAwaitTimeMS + - integer + - .. include:: /includes/extracts/watch-option-maxAwaitTimeMS.rst + + * - readConcern + - :php:`MongoDB\Driver\ReadConcern ` + - .. include:: /includes/extracts/database-option-readConcern.rst + + * - readPreference + - :php:`MongoDB\Driver\ReadPreference ` + - .. include:: /includes/extracts/database-option-readPreference.rst + + This is used for both the initial change stream aggregation and for + server selection during an automatic resume. + + * - resumeAfter + - array|object + - .. include:: /includes/extracts/watch-option-resumeAfter.rst + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + * - showExpandedEvents + - boolean + - .. include:: /includes/extracts/watch-option-showExpandedEvents.rst + + * - startAfter + - array|object + - .. include:: /includes/extracts/watch-option-startAfter.rst + + * - startAtOperationTime + - :php:`MongoDB\BSON\TimestampInterface ` + - .. include:: /includes/extracts/watch-option-startAtOperationTime.rst + + * - typeMap + - array + - .. include:: /includes/extracts/database-option-typeMap.rst + +Return Values +------------- + +A :phpclass:`MongoDB\ChangeStream` object, which allows for iteration of +events in the change stream via the :php:`Iterator ` interface. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unexpectedvalueexception.rst +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Examples +-------- + +This example reports events while iterating a change stream. + +.. code-block:: php + + test; + + $changeStream = $database->watch(); + + for ($changeStream->rewind(); true; $changeStream->next()) { + if ( ! $changeStream->valid()) { + continue; + } + + $event = $changeStream->current(); + + if ($event['operationType'] === 'invalidate') { + break; + } + + $ns = sprintf('%s.%s', $event['ns']['db'], $event['ns']['coll']); + $id = json_encode($event['documentKey']['_id']); + + switch ($event['operationType']) { + case 'delete': + printf("Deleted document in %s with _id: %s\n\n", $ns, $id); + break; + + case 'insert': + printf("Inserted new document in %s\n", $ns); + echo json_encode($event['fullDocument']), "\n\n"; + break; + + case 'replace': + printf("Replaced new document in %s with _id: %s\n", $ns, $id); + echo json_encode($event['fullDocument']), "\n\n"; + break; + + case 'update': + printf("Updated document in %s with _id: %s\n", $ns, $id); + echo json_encode($event['updateDescription']), "\n\n"; + break; + } + } + +Assuming that a document was inserted, updated, and deleted while the above +script was iterating the change stream, the output would then resemble: + +.. code-block:: none + + Inserted new document in test.inventory + {"_id":{"$oid":"5a81fc0d6118fd1af1790d32"},"name":"Widget","quantity":5} + + Updated document in test.inventory with _id: {"$oid":"5a81fc0d6118fd1af1790d32"} + {"updatedFields":{"quantity":4},"removedFields":[]} + + Deleted document in test.inventory with _id: {"$oid":"5a81fc0d6118fd1af1790d32"} + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::watch()` +- :phpmethod:`MongoDB\Client::watch()` +- :manual:`Aggregation Pipeline ` documentation in + the MongoDB Manual +- :manual:`Change Streams ` documentation in the MongoDB manual +- :manual:`Change Events ` documentation in the + MongoDB manual diff --git a/source/reference/method/MongoDBDatabase-withOptions.txt b/source/reference/method/MongoDBDatabase-withOptions.txt new file mode 100644 index 00000000..f601a977 --- /dev/null +++ b/source/reference/method/MongoDBDatabase-withOptions.txt @@ -0,0 +1,89 @@ +================================ +MongoDB\\Database::withOptions() +================================ + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Database::withOptions() + + Returns a clone of the Database object, but with different options. + + .. code-block:: php + + function withOptions(array $options = []): MongoDB\Database + +Parameters +---------- + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - readConcern + - :php:`MongoDB\Driver\ReadConcern ` + - The default read concern to use for database operations. Defaults to + the original database's read concern. + + * - readPreference + - :php:`MongoDB\Driver\ReadPreference ` + - The default read preference to use for database operations. Defaults to + the original database's read preference. + + * - typeMap + - array + - The :php:`type map + ` + to apply to cursors, which determines how BSON documents are converted + to PHP values. Defaults to the original database's type map. + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - The default write concern to use for database operations. Defaults to + the original database's write concern. + +Return Values +------------- + +A :phpclass:`MongoDB\Database` object. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-invalidargumentexception.rst + +Example +------- + +The following example clones an existing Database object with a new read +preference: + +.. code-block:: php + + test; + + $newDb = $db->withOptions([ + 'readPreference' => new MongoDB\Driver\ReadPreference('primaryPreferred'), + ]); + +See Also +-------- + +- :phpmethod:`MongoDB\Database::__construct()` diff --git a/source/reference/method/MongoDBDatabase__construct.txt b/source/reference/method/MongoDBDatabase__construct.txt new file mode 100644 index 00000000..f25e6c4b --- /dev/null +++ b/source/reference/method/MongoDBDatabase__construct.txt @@ -0,0 +1,97 @@ +================================ +MongoDB\\Database::__construct() +================================ + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Database::__construct() + + Constructs a new :phpclass:`Database ` instance. + + .. code-block:: php + + function __construct( + MongoDB\Driver\Manager $manager, + string $databaseName, + array $options = [] + ) + +Parameters +---------- + +``$manager`` : :php:`MongoDB\Driver\Manager ` + The :php:`Manager ` instance from the extension. The + manager maintains connections between the driver and MongoDB. + +``$databaseName`` : string + The name of the database. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - readConcern + - :php:`MongoDB\Driver\ReadConcern ` + - The default read concern to use for database operations. Defaults to + the manager's read concern. + + * - readPreference + - :php:`MongoDB\Driver\ReadPreference ` + - The default read preference to use for database operations. Defaults to + the manager's read preference. + + * - typeMap + - array + - Default :php:`type map + ` + to apply to cursors, which determines how BSON documents are converted + to PHP values. The library uses the following type map by default: + + .. code-block:: php + + [ + 'array' => 'MongoDB\Model\BSONArray', + 'document' => 'MongoDB\Model\BSONDocument', + 'root' => 'MongoDB\Model\BSONDocument', + ] + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - The default write concern to use for database operations. Defaults to + the manager's write concern. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-invalidargumentexception.rst + +Behavior +-------- + +If you construct a Database explicitly, the Database inherits any options from +the :php:`MongoDB\Driver\Manager ` object. If +you select the Database from a :phpclass:`Client ` object, the +Database inherits its options from that object. + +See Also +-------- + +- :phpmethod:`MongoDB\Database::withOptions()` +- :phpmethod:`MongoDB\Client::selectDatabase()` +- :phpmethod:`MongoDB\Client::__get()` diff --git a/source/reference/method/MongoDBDatabase__get.txt b/source/reference/method/MongoDBDatabase__get.txt new file mode 100644 index 00000000..e71c42d4 --- /dev/null +++ b/source/reference/method/MongoDBDatabase__get.txt @@ -0,0 +1,71 @@ +========================== +MongoDB\\Database::__get() +========================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Database::__get() + + Select a collection within the database. + + .. code-block:: php + + function __get(string $collectionName): MongoDB\Collection + +Parameters +---------- + +``$collectionName`` : string + The name of the database to select. + +Return Values +------------- + +A :phpclass:`MongoDB\Collection` object. + +Behavior +-------- + +The selected collection inherits options such as read preference and type +mapping from the :phpclass:`Database ` object. If you wish to +override any options, use the :phpmethod:`MongoDB\Database::selectCollection()` +method. + +.. note:: + + To select collections whose names contain special characters, such as + ``.``, use complex syntax, as in ``$database->{'that.database'}``. + + Alternatively, :phpmethod:`MongoDB\Database::selectCollection()` supports + selecting collections whose names contain special characters. + +Examples +-------- + +The following example selects the ``users`` and ``system.profile`` +collections from the ``test`` database: + +.. code-block:: php + + test; + + $users = $db->users; + $systemProfile = $db->{'system.profile'}; + +See Also +-------- + +- :phpmethod:`MongoDB\Database::selectCollection()` +- :phpmethod:`MongoDB\Client::selectCollection()` +- :php:`Property Overloading ` in the PHP Manual diff --git a/source/reference/method/MongoDBDeleteResult-getDeletedCount.txt b/source/reference/method/MongoDBDeleteResult-getDeletedCount.txt new file mode 100644 index 00000000..02810569 --- /dev/null +++ b/source/reference/method/MongoDBDeleteResult-getDeletedCount.txt @@ -0,0 +1,40 @@ +======================================== +MongoDB\\DeleteResult::getDeletedCount() +======================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\DeleteResult::getDeletedCount() + + Return the number of documents that were deleted. + + .. code-block:: php + + function getDeletedCount(): integer + + This method should only be called if the write was acknowledged. + +Return Values +------------- + +The number of documents that were deleted. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-badmethodcallexception-write-result.rst + +See Also +-------- + +- :php:`MongoDB\Driver\WriteResult::getDeletedCount() + ` diff --git a/source/reference/method/MongoDBDeleteResult-isAcknowledged.txt b/source/reference/method/MongoDBDeleteResult-isAcknowledged.txt new file mode 100644 index 00000000..5e3cbb4e --- /dev/null +++ b/source/reference/method/MongoDBDeleteResult-isAcknowledged.txt @@ -0,0 +1,34 @@ +======================================= +MongoDB\\DeleteResult::isAcknowledged() +======================================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\DeleteResult::isAcknowledged() + + Return whether the write was acknowledged. + + .. code-block:: php + + function isAcknowledged(): boolean + +Return Values +------------- + +A boolean indicating whether the write was acknowledged. + +See Also +-------- + +- :php:`MongoDB\Driver\WriteResult::isAcknowledged() + ` +- :manual:`Write Concern ` in the MongoDB manual diff --git a/source/reference/method/MongoDBGridFSBucket-delete.txt b/source/reference/method/MongoDBGridFSBucket-delete.txt new file mode 100644 index 00000000..9c876c60 --- /dev/null +++ b/source/reference/method/MongoDBGridFSBucket-delete.txt @@ -0,0 +1,57 @@ +================================= +MongoDB\\GridFS\\Bucket::delete() +================================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\GridFS\Bucket::delete() + + Delete a file and its chunks from the GridFS bucket. + + .. code-block:: php + + function delete($id): void + +Parameters +---------- + +``$id`` : mixed + The ``_id`` of the file to delete. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-gridfs-filenotfoundexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Behavior +-------- + +If the files collection document is not found, this method will still attempt to +delete orphaned chunks. + +Examples +-------- + +.. code-block:: php + + test->selectGridFSBucket(); + + $stream = fopen('php://temp', 'w+b'); + fwrite($stream, "foobar"); + rewind($stream); + + $id = $bucket->uploadFromStream('filename', $stream); + + $bucket->delete($id); diff --git a/source/reference/method/MongoDBGridFSBucket-downloadToStream.txt b/source/reference/method/MongoDBGridFSBucket-downloadToStream.txt new file mode 100644 index 00000000..217fc262 --- /dev/null +++ b/source/reference/method/MongoDBGridFSBucket-downloadToStream.txt @@ -0,0 +1,73 @@ +=========================================== +MongoDB\\GridFS\\Bucket::downloadToStream() +=========================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\GridFS\Bucket::downloadToStream() + + Selects a GridFS file by its ``_id`` and copies its contents to a writable + stream. + + .. code-block:: php + + function downloadToStream($id, $destination): void + +Parameters +---------- + +``$id`` : mixed + The ``_id`` of the file to download. + +``$destination`` : resource + Writable stream, to which the GridFS file's contents will be written. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-gridfs-filenotfoundexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Examples +-------- + +.. code-block:: php + + test->selectGridFSBucket(); + + $stream = fopen('php://temp', 'w+b'); + fwrite($stream, "foobar"); + rewind($stream); + + $id = $bucket->uploadFromStream('filename', $stream); + + $destination = fopen('php://temp', 'w+b'); + + $bucket->downloadToStream($id, $destination); + + var_dump(stream_get_contents($destination, -1, 0)); + +The output would then resemble: + +.. code-block:: none + + string(6) "foobar" + +See Also +-------- + +- :phpmethod:`MongoDB\GridFS\Bucket::downloadToStreamByName()` +- :phpmethod:`MongoDB\GridFS\Bucket::openDownloadStream()` +- :phpmethod:`MongoDB\GridFS\Bucket::openDownloadStreamByName()` diff --git a/source/reference/method/MongoDBGridFSBucket-downloadToStreamByName.txt b/source/reference/method/MongoDBGridFSBucket-downloadToStreamByName.txt new file mode 100644 index 00000000..d520793a --- /dev/null +++ b/source/reference/method/MongoDBGridFSBucket-downloadToStreamByName.txt @@ -0,0 +1,104 @@ +================================================= +MongoDB\\GridFS\\Bucket::downloadToStreamByName() +================================================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\GridFS\Bucket::downloadToStreamByName() + + Selects a GridFS file by its ``filename`` and copies its contents to a + writable stream. + + .. code-block:: php + + function downloadToStreamByName( + string $filename, + resource $destination, + array $options = [] + ): void + +Parameters +---------- + +``$filename`` : string + The ``filename`` of the file to download. + +``$destination`` : resource + Writable stream, to which the GridFS file's contents will be written. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - revision + - integer + - The revision of the file to retrieve. Files with the same ``filename`` + will be differentiated by their ``uploadDate`` field. + + Revision numbers are defined as follows: + + - 0 = the original stored file + - 1 = the first revision + - 2 = the second revision + - etc... + - -2 = the second most recent revision + - -1 = the most recent revision + + Defaults to -1 (i.e. the most recent revision). + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-gridfs-filenotfoundexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Examples +-------- + +.. code-block:: php + + test->selectGridFSBucket(); + + $stream = fopen('php://temp', 'w+b'); + fwrite($stream, "foobar"); + rewind($stream); + + $bucket->uploadFromStream('filename', $stream); + + $destination = fopen('php://temp', 'w+b'); + + $bucket->downloadToStreamByName('filename', $destination); + + var_dump(stream_get_contents($destination, -1, 0)); + +The output would then resemble: + +.. code-block:: none + + string(6) "foobar" + +See Also +-------- + +- :phpmethod:`MongoDB\GridFS\Bucket::downloadToStream()` +- :phpmethod:`MongoDB\GridFS\Bucket::openDownloadStream()` +- :phpmethod:`MongoDB\GridFS\Bucket::openDownloadStreamByName()` diff --git a/source/reference/method/MongoDBGridFSBucket-drop.txt b/source/reference/method/MongoDBGridFSBucket-drop.txt new file mode 100644 index 00000000..324db854 --- /dev/null +++ b/source/reference/method/MongoDBGridFSBucket-drop.txt @@ -0,0 +1,46 @@ +=============================== +MongoDB\\GridFS\\Bucket::drop() +=============================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\GridFS\Bucket::drop() + + Drops the files and chunks collections associated with this GridFS bucket. + + .. code-block:: php + + function drop(): void + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Examples +-------- + +.. code-block:: php + + test; + + $bucket = $database->selectGridFSBucket(); + + $stream = fopen('php://temp', 'w+b'); + fwrite($stream, "foobar"); + rewind($stream); + + $bucket->uploadFromStream('filename', $stream); + + $bucket->drop(); diff --git a/source/reference/method/MongoDBGridFSBucket-find.txt b/source/reference/method/MongoDBGridFSBucket-find.txt new file mode 100644 index 00000000..85344f7a --- /dev/null +++ b/source/reference/method/MongoDBGridFSBucket-find.txt @@ -0,0 +1,295 @@ +=============================== +MongoDB\\GridFS\\Bucket::find() +=============================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\GridFS\Bucket::find() + + Finds documents from the GridFS bucket's files collection matching the query. + + .. code-block:: php + + function find( + array|object $filter = [], + array $options = [] + ): MongoDB\Driver\Cursor + +Parameters +---------- + +``$filter`` : array|object + The filter criteria that specifies the documents to query. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - allowDiskUse + - boolean + - Enables writing to temporary files. When set to ``true``, queries can + write data to the ``_tmp`` sub-directory in the ``dbPath`` directory. + + * - allowPartialResults + - boolean + - For queries against a sharded collection, returns partial results from + the :program:`mongos` if some shards are unavailable instead of + throwing an error. + + * - batchSize + - integer + - The number of documents to return in the first batch. Defaults to + ``101``. A batchSize of ``0`` means that the cursor will be + established, but no documents will be returned in the first batch. + + Unlike the previous wire protocol version, a batchSize of ``1`` for the + :dbcommand:`find` command does not close the cursor. + + * - codec + - MongoDB\\Codec\\DocumentCodec + - .. include:: /includes/extracts/bucket-option-codec.rst + + .. versionadded:: 1.17 + + * - collation + - array|object + - .. include:: /includes/extracts/common-option-collation.rst + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/common-option-comment-string-before-4.4.rst + + * - cursorType + - integer + - Indicates the type of cursor to use. ``cursorType`` supports the + following values: + + - ``MongoDB\Operation\Find::NON_TAILABLE`` (*default*) + - ``MongoDB\Operation\Find::TAILABLE`` + + * - hint + - string|array|object + - .. include:: /includes/extracts/common-option-hint.rst + + .. versionadded:: 1.2 + + * - let + - array|object + - .. include:: /includes/extracts/common-option-let.rst + + .. versionadded:: 1.13 + + * - limit + - integer + - The maximum number of documents to return. If unspecified, then + defaults to no limit. A limit of ``0`` is equivalent to setting no + limit. + + A negative limit is similar to a positive limit but closes the cursor + after returning a single batch of results. As such, with a negative + limit, if the limited result set does not fit into a single batch, the + number of documents received will be less than the specified limit. By + passing a negative limit, the client indicates to the server that it + will not ask for a subsequent batch via getMore. + + * - max + - array|object + - The exclusive upper bound for a specific index. + + .. versionadded:: 1.2 + + * - maxAwaitTimeMS + - integer + - Positive integer denoting the time limit in milliseconds for the server + to block a getMore operation if no data is available. This option + should only be used if cursorType is TAILABLE_AWAIT. + + .. versionadded:: 1.2 + + * - maxScan + - integer + - Maximum number of documents or index keys to scan when executing the + query. + + .. deprecated:: 1.4 + .. versionadded:: 1.2 + + * - maxTimeMS + - integer + - .. include:: /includes/extracts/common-option-maxTimeMS.rst + + * - min + - array|object + - The inclusive lower bound for a specific index. + + .. versionadded:: 1.2 + + * - modifiers + - array|object + - :manual:`Meta operators ` that + modify the output or behavior of a query. Use of these operators is + deprecated in favor of named options. + + * - noCursorTimeout + - boolean + - Prevents the server from timing out idle cursors after an inactivity + period (10 minutes). + + * - oplogReplay + - boolean + - Internal use for replica sets. To use ``oplogReplay``, you must include + the following condition in the filter: + + .. code-block:: javascript + + { ts: { $gte: } } + + The :php:`MongoDB\BSON\Timestamp ` + class reference describes how to represent MongoDB's BSON timestamp + type with PHP. + + .. deprecated:: 1.7 + + * - projection + - array|object + - The :ref:`projection specification ` to determine which + fields to include in the returned documents. See + :manual:`Project Fields to Return from Query ` + and :manual:`Projection Operators ` in + the MongoDB manual. + + * - readConcern + - :php:`MongoDB\Driver\ReadConcern ` + - .. include:: /includes/extracts/bucket-option-readConcern.rst + + .. include:: /includes/extracts/common-option-readConcern-transaction.rst + + * - readPreference + - :php:`MongoDB\Driver\ReadPreference ` + - .. include:: /includes/extracts/bucket-option-readPreference.rst + + * - returnKey + - boolean + - If true, returns only the index keys in the resulting documents. + + .. versionadded:: 1.2 + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + .. versionadded:: 1.3 + + * - showRecordId + - boolean + - Determines whether to return the record identifier for each document. + If true, adds a field ``$recordId`` to the returned documents. + + .. versionadded:: 1.2 + + * - skip + - integer + - Number of documents to skip. Defaults to ``0``. + + * - sort + - array|object + - The sort specification for the ordering of the results. + + * - snapshot + - boolean + - Prevents the cursor from returning a document more than once because of + an intervening write operation. + + .. deprecated:: 1.4 + .. versionadded:: 1.2 + + * - typeMap + - array + - .. include:: /includes/extracts/bucket-option-typeMap.rst + +Return Values +------------- + +A :php:`MongoDB\Driver\Cursor ` object. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Behavior +-------- + +.. include:: /includes/extracts/note-bson-comparison.rst + +Examples +-------- + +.. code-block:: php + + test->selectGridFSBucket(); + + $stream = fopen('php://temp', 'w+b'); + fwrite($stream, "foobar"); + rewind($stream); + + $bucket->uploadFromStream('b', $stream); + + $cursor = $bucket->find( + ['length' => ['$lte' => 6]], + [ + 'projection' => [ + 'filename' => 1, + 'length' => 1, + '_id' => 0, + ], + 'sort' => ['length' => -1], + ] + ); + + var_dump($cursor->toArray()); + +The output would then resemble: + +.. code-block:: none + + array(1) { + [0]=> + object(MongoDB\Model\BSONDocument)#3015 (1) { + ["storage":"ArrayObject":private]=> + array(2) { + ["filename"]=> + string(1) "b" + ["length"]=> + int(6) + } + } + } + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::find()` +- :phpmethod:`MongoDB\GridFS\Bucket::findOne()` diff --git a/source/reference/method/MongoDBGridFSBucket-findOne.txt b/source/reference/method/MongoDBGridFSBucket-findOne.txt new file mode 100644 index 00000000..7bcc6860 --- /dev/null +++ b/source/reference/method/MongoDBGridFSBucket-findOne.txt @@ -0,0 +1,246 @@ +================================== +MongoDB\\GridFS\\Bucket::findOne() +================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\GridFS\Bucket::findOne() + + Finds a single document from the GridFS bucket's files collection matching + the query. + + .. code-block:: php + + function findOne( + array|object $filter = [], + array $options = [] + ): array|object|null + +Parameters +---------- + +``$filter`` : array|object + The filter criteria that specifies the documents to query. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - allowDiskUse + - boolean + - Enables writing to temporary files. When set to ``true``, queries can + write data to the ``_tmp`` sub-directory in the ``dbPath`` directory. + + * - allowPartialResults + - boolean + - For queries against a sharded collection, returns partial results from + the :program:`mongos` if some shards are unavailable instead of + throwing an error. + + * - codec + - MongoDB\\Codec\\DocumentCodec + - .. include:: /includes/extracts/bucket-option-codec.rst + + .. versionadded:: 1.17 + + * - collation + - array|object + - .. include:: /includes/extracts/common-option-collation.rst + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + .. include:: /includes/extracts/common-option-comment-string-before-4.4.rst + + * - hint + - string|array|object + - .. include:: /includes/extracts/common-option-hint.rst + + .. versionadded:: 1.2 + + * - let + - array|object + - .. include:: /includes/extracts/common-option-let.rst + + .. versionadded:: 1.13 + + * - max + - array|object + - The exclusive upper bound for a specific index. + + .. versionadded:: 1.2 + + * - maxScan + - integer + - Maximum number of documents or index keys to scan when executing the + query. + + .. deprecated:: 1.4 + .. versionadded:: 1.2 + + * - maxTimeMS + - integer + - .. include:: /includes/extracts/common-option-maxTimeMS.rst + + * - min + - array|object + - The inclusive lower bound for a specific index. + + .. versionadded:: 1.2 + + * - modifiers + - array|object + - :manual:`Meta operators ` that + modify the output or behavior of a query. Use of these operators is + deprecated in favor of named options. + + * - oplogReplay + - boolean + - Internal use for replica sets. To use ``oplogReplay``, you must include + the following condition in the filter: + + .. code-block:: javascript + + { ts: { $gte: } } + + The :php:`MongoDB\BSON\Timestamp ` + class reference describes how to represent MongoDB's BSON timestamp + type with PHP. + + .. deprecated:: 1.7 + + * - projection + - array|object + - The :ref:`projection specification ` to determine which + fields to include in the returned documents. See + :manual:`Project Fields to Return from Query ` + and :manual:`Projection Operators ` in + the MongoDB manual. + + * - readConcern + - :php:`MongoDB\Driver\ReadConcern ` + - .. include:: /includes/extracts/bucket-option-readConcern.rst + + .. include:: /includes/extracts/common-option-readConcern-transaction.rst + + * - readPreference + - :php:`MongoDB\Driver\ReadPreference ` + - .. include:: /includes/extracts/bucket-option-readPreference.rst + + * - returnKey + - boolean + - If true, returns only the index keys in the resulting documents. + + .. versionadded:: 1.2 + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + .. versionadded:: 1.3 + + * - showRecordId + - boolean + - Determines whether to return the record identifier for each document. + If true, adds a field ``$recordId`` to the returned documents. + + .. versionadded:: 1.2 + + * - skip + - integer + - Number of documents to skip. Defaults to ``0``. + + * - sort + - array|object + - The sort specification for the ordering of the results. + + * - typeMap + - array + - .. include:: /includes/extracts/bucket-option-typeMap.rst + + This will be used for the returned result document. + +Return Values +------------- + +An array or object for the :term:`first document ` that matched +the query, or ``null`` if no document matched the query. The return type will +depend on the ``typeMap`` option. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Behavior +-------- + +.. include:: /includes/extracts/note-bson-comparison.rst + +Examples +-------- + +.. code-block:: php + + test->selectGridFSBucket(); + + $stream = fopen('php://temp', 'w+b'); + fwrite($stream, "foobar"); + rewind($stream); + + $bucket->uploadFromStream('b', $stream); + + $fileDocument = $bucket->findOne( + ['length' => ['$lte' => 6]], + [ + 'projection' => [ + 'filename' => 1, + 'length' => 1, + '_id' => 0, + ], + 'sort' => ['length' => -1], + ] + ); + + var_dump($fileDocument); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Model\BSONDocument)#3004 (1) { + ["storage":"ArrayObject":private]=> + array(2) { + ["filename"]=> + string(1) "b" + ["length"]=> + int(6) + } + } + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::findOne()` +- :phpmethod:`MongoDB\GridFS\Bucket::find()` diff --git a/source/reference/method/MongoDBGridFSBucket-getBucketName.txt b/source/reference/method/MongoDBGridFSBucket-getBucketName.txt new file mode 100644 index 00000000..96a61c4d --- /dev/null +++ b/source/reference/method/MongoDBGridFSBucket-getBucketName.txt @@ -0,0 +1,44 @@ +======================================== +MongoDB\\GridFS\\Bucket::getBucketName() +======================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\GridFS\Bucket::getBucketName() + + Returns the name of this bucket. + + .. code-block:: php + + function getBucketName(): string + +Return Values +------------- + +The name of this bucket as a string. + +Examples +-------- + +.. code-block:: php + + test->selectGridFSBucket(); + + var_dump($bucket->getBucketName()); + +The output would then resemble: + +.. code-block:: none + + string(2) "fs" diff --git a/source/reference/method/MongoDBGridFSBucket-getChunkSizeBytes.txt b/source/reference/method/MongoDBGridFSBucket-getChunkSizeBytes.txt new file mode 100644 index 00000000..2a9ff6da --- /dev/null +++ b/source/reference/method/MongoDBGridFSBucket-getChunkSizeBytes.txt @@ -0,0 +1,46 @@ +============================================ +MongoDB\\GridFS\\Bucket::getChunkSizeBytes() +============================================ + +.. versionchanged:: 1.2 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\GridFS\Bucket::getChunkSizeBytes() + + Returns the chunk size of this bucket in bytes. + + .. code-block:: php + + function getChunkSizeBytes(): integer + +Return Values +------------- + +The chunk size of this bucket in bytes. + +Examples +-------- + +.. code-block:: php + + test->selectGridFSBucket(); + + var_dump($bucket->getChunkSizeBytes()); + +The output would then resemble: + +.. code-block:: none + + int(261120) diff --git a/source/reference/method/MongoDBGridFSBucket-getChunksCollection.txt b/source/reference/method/MongoDBGridFSBucket-getChunksCollection.txt new file mode 100644 index 00000000..ce1c97b9 --- /dev/null +++ b/source/reference/method/MongoDBGridFSBucket-getChunksCollection.txt @@ -0,0 +1,46 @@ +============================================== +MongoDB\\GridFS\\Bucket::getChunksCollection() +============================================== + +.. versionadded:: 1.2 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\GridFS\Bucket::getChunksCollection() + + Returns the chunks collection used by the bucket. + + .. code-block:: php + + function getChunksCollection(): MongoDB\Collection + +Return Values +------------- + +A :phpclass:`MongoDB\Collection` object for the chunks collection. + +Examples +-------- + +.. code-block:: php + + test->selectGridFSBucket(); + + var_dump((string) $bucket->getChunksCollection()); + +The output would then resemble: + +.. code-block:: none + + string(14) "test.fs.chunks" diff --git a/source/reference/method/MongoDBGridFSBucket-getDatabaseName.txt b/source/reference/method/MongoDBGridFSBucket-getDatabaseName.txt new file mode 100644 index 00000000..22703fdd --- /dev/null +++ b/source/reference/method/MongoDBGridFSBucket-getDatabaseName.txt @@ -0,0 +1,45 @@ +========================================== +MongoDB\\GridFS\\Bucket::getDatabaseName() +========================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\GridFS\Bucket::getDatabaseName() + + Returns the name of the database containing this bucket. + + .. code-block:: php + + function getDatabaseName(): string + +Return Values +------------- + +The name of the database containing this bucket as a string. + +Examples +-------- + +.. code-block:: php + + test->selectGridFSBucket(); + + var_dump($bucket->getDatabaseName()); + +The output would then resemble: + +.. code-block:: none + + string(4) "test" + diff --git a/source/reference/method/MongoDBGridFSBucket-getFileDocumentForStream.txt b/source/reference/method/MongoDBGridFSBucket-getFileDocumentForStream.txt new file mode 100644 index 00000000..9dc275ca --- /dev/null +++ b/source/reference/method/MongoDBGridFSBucket-getFileDocumentForStream.txt @@ -0,0 +1,81 @@ +=================================================== +MongoDB\\GridFS\\Bucket::getFileDocumentForStream() +=================================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\GridFS\Bucket::getFileDocumentForStream() + + Gets the file document of the GridFS file associated with a stream. + + .. code-block:: php + + function getFileDocumentForStream(resource $stream): array|object + +Parameters +---------- + +``$stream`` : resource + The GridFS stream resource. + +Return Values +------------- + +The metadata document associated with the GridFS stream. The return type will +depend on the bucket's ``typeMap`` option. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Examples +-------- + +.. code-block:: php + + test->selectGridFSBucket(); + + $stream = $bucket->openUploadStream('filename'); + + $fileDocument = $bucket->getFileDocumentForStream($stream); + + var_dump($fileDocument); + + fclose($stream); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Model\BSONDocument)#4956 (1) { + ["storage":"ArrayObject":private]=> + array(3) { + ["_id"]=> + object(MongoDB\BSON\ObjectId)#4955 (1) { + ["oid"]=> + string(24) "5acfb05b7e21e83b5a29037c" + } + ["chunkSize"]=> + int(261120) + ["filename"]=> + string(8) "filename" + } + } + +See Also +-------- + +- :phpmethod:`MongoDB\GridFS\Bucket::getFileIdForStream()` diff --git a/source/reference/method/MongoDBGridFSBucket-getFileIdForStream.txt b/source/reference/method/MongoDBGridFSBucket-getFileIdForStream.txt new file mode 100644 index 00000000..0107b3d8 --- /dev/null +++ b/source/reference/method/MongoDBGridFSBucket-getFileIdForStream.txt @@ -0,0 +1,72 @@ +============================================= +MongoDB\\GridFS\\Bucket::getFileIdForStream() +============================================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\GridFS\Bucket::getFileIdForStream() + + Gets the file document's ID of the GridFS file associated with a stream. + + .. code-block:: php + + function getFileIdForStream(resource $stream): mixed + +Parameters +---------- + +``$stream`` : resource + The GridFS stream resource. + +Return Values +------------- + +The ``_id`` field of the metadata document associated with the GridFS stream. +The return type will depend on the bucket's ``typeMap`` option. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-gridfs-corruptfileexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Examples +-------- + +.. code-block:: php + + test->selectGridFSBucket(); + + $stream = $bucket->openUploadStream('filename'); + + $id = $bucket->getFileIdForStream($stream); + + var_dump($id); + + fclose($stream); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\BSON\ObjectId)#3005 (1) { + ["oid"]=> + string(24) "5acfb37d7e21e83cdb3e1583" + } + +See Also +-------- + +- :phpmethod:`MongoDB\GridFS\Bucket::getFileDocumentForStream()` diff --git a/source/reference/method/MongoDBGridFSBucket-getFilesCollection.txt b/source/reference/method/MongoDBGridFSBucket-getFilesCollection.txt new file mode 100644 index 00000000..510cfad1 --- /dev/null +++ b/source/reference/method/MongoDBGridFSBucket-getFilesCollection.txt @@ -0,0 +1,49 @@ +============================================= +MongoDB\\GridFS\\Bucket::getFilesCollection() +============================================= + +.. versionadded:: 1.2 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\GridFS\Bucket::getFilesCollection() + + Returns the files collection used by the bucket. + + .. code-block:: php + + function getFilesCollection(): MongoDB\Collection + +Return Values +------------- + +A :phpclass:`MongoDB\Collection` object for the files collection. + +Examples +-------- + +.. code-block:: php + + test->selectGridFSBucket(); + + $filesCollection = $bucket->getFilesCollection(); + + var_dump($filesCollection->getCollectionName()); + +The output would then resemble: + +.. code-block:: none + + string(8) "fs.files" + diff --git a/source/reference/method/MongoDBGridFSBucket-getReadConcern.txt b/source/reference/method/MongoDBGridFSBucket-getReadConcern.txt new file mode 100644 index 00000000..d1d4c610 --- /dev/null +++ b/source/reference/method/MongoDBGridFSBucket-getReadConcern.txt @@ -0,0 +1,61 @@ +========================================= +MongoDB\\GridFS\\Bucket::getReadConcern() +========================================= + +.. versionadded:: 1.2 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\GridFS\Bucket::getReadConcern() + + Returns the read concern for this GridFS bucket. + + .. code-block:: php + + function getReadConcern(): MongoDB\Driver\ReadConcern + +Return Values +------------- + +A :php:`MongoDB\Driver\ReadConcern ` object. + +Example +------- + +.. code-block:: php + + selectDatabase('test'); + $bucket = $database->selectGridFSBucket([ + 'readConcern' => new MongoDB\Driver\ReadConcern('majority'), + ]); + + var_dump($bucket->getReadConcern()); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Driver\ReadConcern)#3 (1) { + ["level"]=> + string(8) "majority" + } + +See Also +-------- + +- :manual:`Read Concern ` in the MongoDB manual +- :php:`MongoDB\Driver\ReadConcern::isDefault() ` +- :phpmethod:`MongoDB\Client::getReadConcern()` +- :phpmethod:`MongoDB\Collection::getReadConcern()` +- :phpmethod:`MongoDB\Database::getReadConcern()` diff --git a/source/reference/method/MongoDBGridFSBucket-getReadPreference.txt b/source/reference/method/MongoDBGridFSBucket-getReadPreference.txt new file mode 100644 index 00000000..6843cc93 --- /dev/null +++ b/source/reference/method/MongoDBGridFSBucket-getReadPreference.txt @@ -0,0 +1,61 @@ +============================================ +MongoDB\\GridFS\\Bucket::getReadPreference() +============================================ + +.. versionadded:: 1.2 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\GridFS\Bucket::getReadPreference() + + Returns the read preference for this GridFS bucket. + + .. code-block:: php + + function getReadPreference(): MongoDB\Driver\ReadPreference + +Return Values +------------- + +A :php:`MongoDB\Driver\ReadPreference ` +object. + +Example +------- + +.. code-block:: php + + selectDatabase('test'); + $bucket = $database->selectGridFSBucket([ + 'readPreference' => new MongoDB\Driver\ReadPreference('primaryPreferred'), + ]); + + var_dump($bucket->getReadPreference()); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Driver\ReadPreference)#3 (1) { + ["mode"]=> + string(16) "primaryPreferred" + } + +See Also +-------- + +- :manual:`Read Preference ` in the MongoDB manual +- :phpmethod:`MongoDB\Client::getReadPreference()` +- :phpmethod:`MongoDB\Collection::getReadPreference()` +- :phpmethod:`MongoDB\Database::getReadPreference()` diff --git a/source/reference/method/MongoDBGridFSBucket-getTypeMap.txt b/source/reference/method/MongoDBGridFSBucket-getTypeMap.txt new file mode 100644 index 00000000..1005f2a2 --- /dev/null +++ b/source/reference/method/MongoDBGridFSBucket-getTypeMap.txt @@ -0,0 +1,68 @@ +===================================== +MongoDB\\GridFS\\Bucket::getTypeMap() +===================================== + +.. versionadded:: 1.2 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\GridFS\Bucket::getTypeMap() + + Returns the type map for this GridFS bucket. + + .. code-block:: php + + function getTypeMap(): array + +Return Values +------------- + +A :ref:`type map ` array. + +Example +------- + +.. code-block:: php + + selectDatabase('test'); + $bucket = $database->selectGridFSBucket([ + 'typeMap' => [ + 'root' => 'array', + 'document' => 'array', + 'array' => 'array', + ], + ]); + + var_dump($bucket->getTypeMap()); + +The output would then resemble: + +.. code-block:: none + + array(3) { + ["root"]=> + string(5) "array" + ["document"]=> + string(5) "array" + ["array"]=> + string(5) "array" + } + +See Also +-------- + +- :doc:`/reference/bson` +- :phpmethod:`MongoDB\Client::getTypeMap()` +- :phpmethod:`MongoDB\Collection::getTypeMap()` +- :phpmethod:`MongoDB\Database::getTypeMap()` diff --git a/source/reference/method/MongoDBGridFSBucket-getWriteConcern.txt b/source/reference/method/MongoDBGridFSBucket-getWriteConcern.txt new file mode 100644 index 00000000..21e535af --- /dev/null +++ b/source/reference/method/MongoDBGridFSBucket-getWriteConcern.txt @@ -0,0 +1,64 @@ +========================================== +MongoDB\\GridFS\\Bucket::getWriteConcern() +========================================== + +.. versionadded:: 1.2 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\GridFS\Bucket::getWriteConcern() + + Returns the write concern for this GridFS bucket. + + .. code-block:: php + + function getWriteConcern(): MongoDB\Driver\WriteConcern + +Return Values +------------- + +A :php:`MongoDB\Driver\WriteConcern ` +object. + +Example +------- + +.. code-block:: php + + selectDatabase('test'); + $bucket = $database->selectGridFSBucket([ + 'writeConcern' => new MongoDB\Driver\WriteConcern(1, 0, true), + ]); + + var_dump($bucket->getWriteConcern()); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Driver\WriteConcern)#3 (2) { + ["w"]=> + int(1) + ["j"]=> + bool(true) + } + +See Also +-------- + +- :manual:`Write Concern ` in the MongoDB manual +- :php:`MongoDB\Driver\WriteConcern::isDefault() ` +- :phpmethod:`MongoDB\Client::getWriteConcern()` +- :phpmethod:`MongoDB\Collection::getWriteConcern()` +- :phpmethod:`MongoDB\Database::getWriteConcern()` diff --git a/source/reference/method/MongoDBGridFSBucket-openDownloadStream.txt b/source/reference/method/MongoDBGridFSBucket-openDownloadStream.txt new file mode 100644 index 00000000..bfabc282 --- /dev/null +++ b/source/reference/method/MongoDBGridFSBucket-openDownloadStream.txt @@ -0,0 +1,71 @@ +============================================= +MongoDB\\GridFS\\Bucket::openDownloadStream() +============================================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\GridFS\Bucket::openDownloadStream() + + Selects a GridFS file by its ``_id`` and opens it as a readable stream. + + .. code-block:: php + + function openDownloadStream($id): resource + +Parameters +---------- + +``$id`` : mixed + The ``_id`` of the file to download. + +Return Values +------------- + +A readable stream resource. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-gridfs-filenotfoundexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Examples +-------- + +.. code-block:: php + + test->selectGridFSBucket(); + + $uploadStream = fopen('php://temp', 'w+b'); + fwrite($uploadStream, "foobar"); + rewind($uploadStream); + + $id = $bucket->uploadFromStream('filename', $uploadStream); + + $downloadStream = $bucket->openDownloadStream($id); + + var_dump(stream_get_contents($downloadStream)); + +The output would then resemble: + +.. code-block:: none + + string(6) "foobar" + +See Also +-------- + +- :phpmethod:`MongoDB\GridFS\Bucket::downloadToStream()` +- :phpmethod:`MongoDB\GridFS\Bucket::downloadToStreamByName()` +- :phpmethod:`MongoDB\GridFS\Bucket::openDownloadStreamByName()` diff --git a/source/reference/method/MongoDBGridFSBucket-openDownloadStreamByName.txt b/source/reference/method/MongoDBGridFSBucket-openDownloadStreamByName.txt new file mode 100644 index 00000000..287cf4b5 --- /dev/null +++ b/source/reference/method/MongoDBGridFSBucket-openDownloadStreamByName.txt @@ -0,0 +1,99 @@ +=================================================== +MongoDB\\GridFS\\Bucket::openDownloadStreamByName() +=================================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\GridFS\Bucket::openDownloadStreamByName() + + Selects a GridFS file by its ``filename`` and opens it as a readable stream. + + .. code-block:: php + + function openDownloadStreamByName( + string $filename, + array $options = [] + ): resource + +Parameters +---------- + +``$filename`` : string + The ``filename`` of the file to download. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - revision + - integer + - The revision of the file to retrieve. Files with the same ``filename`` + will be differentiated by their ``uploadDate`` field. + + Revision numbers are defined as follows: + + - 0 = the original stored file + - 1 = the first revision + - 2 = the second revision + - etc... + - -2 = the second most recent revision + - -1 = the most recent revision + + Defaults to -1 (i.e. the most recent revision). + +Return Values +------------- + +A readable stream resource. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-gridfs-filenotfoundexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Examples +-------- + +.. code-block:: php + + test->selectGridFSBucket(); + + $stream = fopen('php://temp', 'w+b'); + fwrite($stream, "foobar"); + rewind($stream); + + $bucket->uploadFromStream('filename', $stream); + + var_dump(stream_get_contents($bucket->openDownloadStreamByName('filename'))); + +The output would then resemble: + +.. code-block:: none + + string(6) "foobar" + +See Also +-------- + +- :phpmethod:`MongoDB\GridFS\Bucket::downloadToStream()` +- :phpmethod:`MongoDB\GridFS\Bucket::downloadToStreamByName()` +- :phpmethod:`MongoDB\GridFS\Bucket::openDownloadStream()` diff --git a/source/reference/method/MongoDBGridFSBucket-openUploadStream.txt b/source/reference/method/MongoDBGridFSBucket-openUploadStream.txt new file mode 100644 index 00000000..3a0ea02e --- /dev/null +++ b/source/reference/method/MongoDBGridFSBucket-openUploadStream.txt @@ -0,0 +1,103 @@ +=========================================== +MongoDB\\GridFS\\Bucket::openUploadStream() +=========================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\GridFS\Bucket::openUploadStream() + + Opens a writable stream for a new GridFS file. + + .. code-block:: php + + function openUploadStream( + string $filename, + array $options = [] + ): resource + +Parameters +---------- + +``$filename`` : string + The ``filename`` of the file to create. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - _id + - mixed + - Value to use as the file document identifier. Defaults to a new + :php:`MongoDB\BSON\ObjectId ` object. + + * - chunkSizeBytes + - integer + - The chunk size in bytes. Defaults to the bucket's ``chunkSizeBytes`` + option. + + * - disableMD5 + - boolean + - Whether to disable automatic MD5 generation when storing files. + + Defaults to ``false``. + + .. versionadded:: 1.4 + + * - metadata + - array|object + - User data for the ``metadata`` field of the file document. If not + specified, the ``metadata`` field will not be set on the file document. + +Return Values +------------- + +A writable stream resource. + +Behavior +-------- + +Chunk documents will be created as data is written to the writable stream. The +metadata document will be created when the writable stream is closed. + +Examples +-------- + +.. code-block:: php + + test->selectGridFSBucket(); + + $uploadStream = $bucket->openUploadStream('filename'); + fwrite($uploadStream, 'foobar'); + fclose($uploadStream); + + $downloadStream = $bucket->openDownloadStreamByName('filename'); + var_dump(stream_get_contents($downloadStream)); + +The output would then resemble: + +.. code-block:: none + + string(6) "foobar" + +See Also +-------- + +- :phpmethod:`MongoDB\GridFS\Bucket::uploadFromStream()` diff --git a/source/reference/method/MongoDBGridFSBucket-rename.txt b/source/reference/method/MongoDBGridFSBucket-rename.txt new file mode 100644 index 00000000..75545a8a --- /dev/null +++ b/source/reference/method/MongoDBGridFSBucket-rename.txt @@ -0,0 +1,62 @@ +================================= +MongoDB\\GridFS\\Bucket::rename() +================================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\GridFS\Bucket::rename() + + Selects a GridFS file by its ``_id`` and alters its ``filename``. + + .. code-block:: php + + function rename($id, string $newFilename): void + +Parameters +---------- + +``$id`` : mixed + The ``_id`` of the file to rename. + +``$newFilename`` : string + The new ``filename`` value. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-gridfs-filenotfoundexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Examples +-------- + +.. code-block:: php + + test->selectGridFSBucket(); + + $stream = fopen('php://temp', 'w+b'); + fwrite($stream, "foobar"); + rewind($stream); + + $id = $bucket->uploadFromStream('a', $stream); + + $bucket->rename($id, 'b'); + + var_dump(stream_get_contents($bucket->openDownloadStreamByName('b'))); + +The output would then resemble: + +.. code-block:: none + + string(6) "foobar" diff --git a/source/reference/method/MongoDBGridFSBucket-uploadFromStream.txt b/source/reference/method/MongoDBGridFSBucket-uploadFromStream.txt new file mode 100644 index 00000000..eabfc2e9 --- /dev/null +++ b/source/reference/method/MongoDBGridFSBucket-uploadFromStream.txt @@ -0,0 +1,114 @@ +=========================================== +MongoDB\\GridFS\\Bucket::uploadFromStream() +=========================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\GridFS\Bucket::uploadFromStream() + + Creates a new GridFS file and copies the contents of a readable stream to it. + + .. code-block:: php + + function uploadFromStream( + string $filename, + resource $source, + array $options = [] + ): mixed + +Parameters +---------- + +``$filename`` : string + The ``filename`` of the file to create. + +``$source`` : resource + Readable stream, from which the new GridFS file's contents will be read. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - _id + - mixed + - Value to use as the file document identifier. Defaults to a new + :php:`MongoDB\BSON\ObjectId ` object. + + * - chunkSizeBytes + - integer + - The chunk size in bytes. Defaults to the bucket's ``chunkSizeBytes`` + option. + + * - disableMD5 + - boolean + - Whether to disable automatic MD5 generation when storing files. + + Defaults to ``false``. + + .. versionadded:: 1.4 + + * - metadata + - array|object + - User data for the ``metadata`` field of the file document. If not + specified, the ``metadata`` field will not be set on the file document. + +Return Values +------------- + +The ``_id`` field of the metadata document associated with the newly created +GridFS file. If the ``_id`` option is not specified, a new +:php:`MongoDB\BSON\ObjectId ` object will be used +by default. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Examples +-------- + +.. code-block:: php + + test->selectGridFSBucket(); + + $stream = fopen('php://temp', 'w+b'); + fwrite($stream, "foobar"); + rewind($stream); + + $id = $bucket->uploadFromStream('filename', $stream); + + var_dump($id); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\BSON\ObjectId)#3009 (1) { + ["oid"]=> + string(24) "5acf81017e21e816e538d883" + } + +See Also +-------- + +- :phpmethod:`MongoDB\GridFS\Bucket::openUploadStream()` diff --git a/source/reference/method/MongoDBGridFSBucket__construct.txt b/source/reference/method/MongoDBGridFSBucket__construct.txt new file mode 100644 index 00000000..b950f2a0 --- /dev/null +++ b/source/reference/method/MongoDBGridFSBucket__construct.txt @@ -0,0 +1,141 @@ +====================================== +MongoDB\\GridFS\\Bucket::__construct() +====================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\GridFS\Bucket::__construct() + + Constructs a new :phpclass:`Bucket ` instance. + + .. code-block:: php + + function __construct( + MongoDB\Driver\Manager $manager, + string $databaseName, + array $options = [] + ) + +Parameters +---------- + +``$manager`` : :php:`MongoDB\Driver\Manager ` + The :php:`Manager ` instance from the extension. The + manager maintains connections between the driver and MongoDB. + +``$databaseName`` : string + The name of the database. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - bucketName + - string + - The bucket name, which will be used as a prefix for the files and + chunks collections. Defaults to ``"fs"``. + + * - chunkSizeBytes + - integer + - The chunk size in bytes. Defaults to ``261120`` (i.e. 255 KiB). + + * - codec + - MongoDB\\Codec\\DocumentCodec + - The default :doc:`codec ` to use for bucket methods + that return a file document (e.g. :phpmethod:`MongoDB\GridFS\Bucket::find()`). + + .. versionadded:: 1.17 + + * - disableMD5 + - boolean + - Whether to disable automatic MD5 generation when storing files. + + Defaults to ``false``. + + .. versionadded:: 1.4 + + * - readConcern + - :php:`MongoDB\Driver\ReadConcern ` + - The default read concern to use for bucket operations. Defaults to the + manager's read concern. + + * - readPreference + - :php:`MongoDB\Driver\ReadPreference ` + - The default read preference to use for bucket operations. Defaults to + the manager's read preference. + + * - typeMap + - array + - Default :php:`type map + ` + to apply to cursors, which determines how BSON documents are converted + to PHP values. The library uses the following type map by default: + + .. code-block:: php + + [ + 'array' => 'MongoDB\Model\BSONArray', + 'document' => 'MongoDB\Model\BSONDocument', + 'root' => 'MongoDB\Model\BSONDocument', + ] + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - The default write concern to use for bucket operations. Defaults to the + manager's write concern. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-invalidargumentexception.rst + +Behavior +-------- + +If you construct a Bucket explicitly, the Bucket inherits any options +from the :php:`MongoDB\Driver\Manager ` object. +If you select the Bucket from a :phpclass:`Database ` object, +the Bucket inherits its options from that object. + +Examples +-------- + +.. code-block:: php + + test->selectGridFSBucket(); + + var_dump($bucket); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\GridFS\Bucket)#3053 (2) { + ["bucketName"]=> + string(4) "test" + ["databaseName"]=> + string(11) "phplib_test" + } + +See Also +-------- + +- :phpmethod:`MongoDB\Database::selectGridFSBucket()` diff --git a/source/reference/method/MongoDBInsertManyResult-getInsertedCount.txt b/source/reference/method/MongoDBInsertManyResult-getInsertedCount.txt new file mode 100644 index 00000000..f114b456 --- /dev/null +++ b/source/reference/method/MongoDBInsertManyResult-getInsertedCount.txt @@ -0,0 +1,40 @@ +============================================= +MongoDB\\InsertManyResult::getInsertedCount() +============================================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\InsertManyResult::getInsertedCount() + + Return the number of documents that were inserted. + + .. code-block:: php + + function getInsertedCount(): integer + + This method should only be called if the write was acknowledged. + +Return Values +------------- + +The number of documents that were inserted. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-badmethodcallexception-write-result.rst + +See Also +-------- + +- :php:`MongoDB\Driver\WriteResult::getInsertedCount() + ` diff --git a/source/reference/method/MongoDBInsertManyResult-getInsertedIds.txt b/source/reference/method/MongoDBInsertManyResult-getInsertedIds.txt new file mode 100644 index 00000000..bf30e28b --- /dev/null +++ b/source/reference/method/MongoDBInsertManyResult-getInsertedIds.txt @@ -0,0 +1,36 @@ +=========================================== +MongoDB\\InsertManyResult::getInsertedIds() +=========================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\InsertManyResult::getInsertedIds() + + Return a map of IDs (i.e. ``_id`` field values) for the inserted documents. + + .. code-block:: php + + function getInsertedIds(): array + + Since IDs are created by the driver, this method may be called irrespective + of whether the write was acknowledged. + +Return Values +------------- + +A map of IDs (i.e. ``_id`` field values) for the inserted documents. + +The index of each ID in the map corresponds to each document's position in the +bulk operation. If a document had an ID prior to inserting (i.e. the driver did +not generate an ID), the index will contain its ``_id`` field value. Any +driver-generated ID will be a :php:`MongoDB\BSON\ObjectId +` instance. diff --git a/source/reference/method/MongoDBInsertManyResult-isAcknowledged.txt b/source/reference/method/MongoDBInsertManyResult-isAcknowledged.txt new file mode 100644 index 00000000..2589edb4 --- /dev/null +++ b/source/reference/method/MongoDBInsertManyResult-isAcknowledged.txt @@ -0,0 +1,34 @@ +=========================================== +MongoDB\\InsertManyResult::isAcknowledged() +=========================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\InsertManyResult::isAcknowledged() + + Return whether the write was acknowledged. + + .. code-block:: php + + function isAcknowledged(): boolean + +Return Values +------------- + +A boolean indicating whether the write was acknowledged. + +See Also +-------- + +- :php:`MongoDB\Driver\WriteResult::isAcknowledged() + ` +- :manual:`Write Concern ` in the MongoDB manual diff --git a/source/reference/method/MongoDBInsertOneResult-getInsertedCount.txt b/source/reference/method/MongoDBInsertOneResult-getInsertedCount.txt new file mode 100644 index 00000000..d6ba1279 --- /dev/null +++ b/source/reference/method/MongoDBInsertOneResult-getInsertedCount.txt @@ -0,0 +1,41 @@ +============================================ +MongoDB\\InsertOneResult::getInsertedCount() +============================================ + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\InsertOneResult::getInsertedCount() + + Return the number of documents that were inserted. + + .. code-block:: php + + function getInsertedCount(): integer + + This method should only be called if the write was acknowledged. + +Return Values +------------- + +The number of documents that were inserted. This should be ``1`` for an +acknowledged insert operation. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-badmethodcallexception-write-result.rst + +See Also +-------- + +- :php:`MongoDB\Driver\WriteResult::getInsertedCount() + ` diff --git a/source/reference/method/MongoDBInsertOneResult-getInsertedId.txt b/source/reference/method/MongoDBInsertOneResult-getInsertedId.txt new file mode 100644 index 00000000..e3cef55d --- /dev/null +++ b/source/reference/method/MongoDBInsertOneResult-getInsertedId.txt @@ -0,0 +1,35 @@ +========================================= +MongoDB\\InsertOneResult::getInsertedId() +========================================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\InsertOneResult::getInsertedId() + + Return the ID (i.e. ``_id`` field value) for the inserted document. + + .. code-block:: php + + function getInsertedId(): mixed + + Since IDs are created by the driver, this method may be called irrespective + of whether the write was acknowledged. + +Return Values +------------- + +The ID (i.e. ``_id`` field value) of the inserted document. + +If the document had an ID prior to inserting (i.e. the driver did not need to +generate an ID), this will contain its ``_id`` field value. Any driver-generated +ID will be a :php:`MongoDB\BSON\ObjectId ` +instance. diff --git a/source/reference/method/MongoDBInsertOneResult-isAcknowledged.txt b/source/reference/method/MongoDBInsertOneResult-isAcknowledged.txt new file mode 100644 index 00000000..3e4505cd --- /dev/null +++ b/source/reference/method/MongoDBInsertOneResult-isAcknowledged.txt @@ -0,0 +1,34 @@ +========================================== +MongoDB\\InsertOneResult::isAcknowledged() +========================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\InsertOneResult::isAcknowledged() + + Return whether the write was acknowledged. + + .. code-block:: php + + function isAcknowledged(): boolean + +Return Values +------------- + +A boolean indicating whether the write was acknowledged. + +See Also +-------- + +- :php:`MongoDB\Driver\WriteResult::isAcknowledged() + ` +- :manual:`Write Concern ` in the MongoDB manual diff --git a/source/reference/method/MongoDBMapReduceResult-getCounts.txt b/source/reference/method/MongoDBMapReduceResult-getCounts.txt new file mode 100644 index 00000000..50cae3ef --- /dev/null +++ b/source/reference/method/MongoDBMapReduceResult-getCounts.txt @@ -0,0 +1,68 @@ +===================================== +MongoDB\\MapReduceResult::getCounts() +===================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\MapReduceResult::getCounts() + + Returns count statistics for the map-reduce operation. + + .. code-block:: php + + function getCounts(): array + +Return Values +------------- + +An array of count statistics for the map-reduce operation. + +Examples +-------- + +This example reports the count statistics for a map-reduce operation. + +.. code-block:: php + + test->zips; + + $map = new MongoDB\BSON\Javascript('function() { emit(this.state, this.pop); }'); + $reduce = new MongoDB\BSON\Javascript('function(key, values) { return Array.sum(values) }'); + $out = ['inline' => 1]; + + $result = $collection->mapReduce($map, $reduce, $out); + + var_dump($result->getCounts()); + +The output would then resemble: + +.. code-block:: none + + array(4) { + ["input"]=> + int(29353) + ["emit"]=> + int(29353) + ["reduce"]=> + int(180) + ["output"]=> + int(51) + } + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::mapReduce()` +- :manual:`mapReduce ` command reference in the + MongoDB manual diff --git a/source/reference/method/MongoDBMapReduceResult-getExecutionTimeMS.txt b/source/reference/method/MongoDBMapReduceResult-getExecutionTimeMS.txt new file mode 100644 index 00000000..fd094fed --- /dev/null +++ b/source/reference/method/MongoDBMapReduceResult-getExecutionTimeMS.txt @@ -0,0 +1,60 @@ +============================================== +MongoDB\\MapReduceResult::getExecutionTimeMS() +============================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\MapReduceResult::getExecutionTimeMS() + + Returns the execution time in milliseconds of the map-reduce operation. + + .. code-block:: php + + function getExecutionTimeMS(): integer + +Return Values +------------- + +An integer denoting the execution time in milliseconds for the map-reduce +operation. + +Examples +-------- + +This example reports the execution time for a map-reduce operation. + +.. code-block:: php + + test->zips; + + $map = new MongoDB\BSON\Javascript('function() { emit(this.state, this.pop); }'); + $reduce = new MongoDB\BSON\Javascript('function(key, values) { return Array.sum(values) }'); + $out = ['inline' => 1]; + + $result = $collection->mapReduce($map, $reduce, $out); + + var_dump($result->getExecutionTimeMS()); + +The output would then resemble: + +.. code-block:: none + + int(244) + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::mapReduce()` +- :manual:`mapReduce ` command reference in the + MongoDB manual diff --git a/source/reference/method/MongoDBMapReduceResult-getIterator.txt b/source/reference/method/MongoDBMapReduceResult-getIterator.txt new file mode 100644 index 00000000..9de94895 --- /dev/null +++ b/source/reference/method/MongoDBMapReduceResult-getIterator.txt @@ -0,0 +1,85 @@ +======================================= +MongoDB\\MapReduceResult::getIterator() +======================================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\MapReduceResult::getIterator() + + Returns a :php:`Traversable `, which may be used to iterate + through the results of the map-reduce operation. + + .. code-block:: php + + function getIterator(): Traversable + +Return Values +------------- + +A :php:`Traversable `, which may be used to iterate through the +results of the map-reduce operation. + +Example +------- + +This example iterates through the results of a map-reduce operation. + +.. code-block:: php + + test->zips; + + $map = new MongoDB\BSON\Javascript('function() { emit(this.state, this.pop); }'); + $reduce = new MongoDB\BSON\Javascript('function(key, values) { return Array.sum(values) }'); + $out = ['inline' => 1]; + + $result = $collection->mapReduce($map, $reduce, $out); + + foreach ($result as $population) { + var_dump($population); + }; + +The output would then resemble: + +.. code-block:: none + + object(stdClass)#2293 (2) { + ["_id"]=> + string(2) "AK" + ["value"]=> + float(544698) + } + object(stdClass)#2300 (2) { + ["_id"]=> + string(2) "AL" + ["value"]=> + float(4040587) + } + object(stdClass)#2293 (2) { + ["_id"]=> + string(2) "AR" + ["value"]=> + float(2350725) + } + object(stdClass)#2300 (2) { + ["_id"]=> + string(2) "AZ" + ["value"]=> + float(3665228) + } + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::mapReduce()` +- :php:`IteratorAggregate::getIterator() ` diff --git a/source/reference/method/MongoDBMapReduceResult-getTiming.txt b/source/reference/method/MongoDBMapReduceResult-getTiming.txt new file mode 100644 index 00000000..98268285 --- /dev/null +++ b/source/reference/method/MongoDBMapReduceResult-getTiming.txt @@ -0,0 +1,76 @@ +===================================== +MongoDB\\MapReduceResult::getTiming() +===================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\MapReduceResult::getTiming() + + Returns timing statistics for the map-reduce operation. + + .. code-block:: php + + function getTiming(): array + + Timing statistics will only be available if the ``verbose`` option was + specified for :phpmethod:`MongoDB\Collection::mapReduce()`. + +Return Values +------------- + +An array of timing statistics for the map-reduce operation. If no timing +statistics are available, the array will be empty. + +Examples +-------- + +This example specifies the ``verbose`` option for +:phpmethod:`MongoDB\Collection::mapReduce()` and reports the timing statistics +for a map-reduce operation. + +.. code-block:: php + + test->zips; + + $map = new MongoDB\BSON\Javascript('function() { emit(this.state, this.pop); }'); + $reduce = new MongoDB\BSON\Javascript('function(key, values) { return Array.sum(values) }'); + $out = ['inline' => 1]; + + $result = $collection->mapReduce($map, $reduce, $out, ['verbose' => true]); + + var_dump($result->getTiming()); + +The output would then resemble: + +.. code-block:: none + + array(5) { + ["mapTime"]=> + int(163) + ["emitLoop"]=> + int(233) + ["reduceTime"]=> + int(9) + ["mode"]=> + string(5) "mixed" + ["total"]=> + int(233) + } + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::mapReduce()` +- :manual:`mapReduce ` command reference in the + MongoDB manual diff --git a/source/reference/method/MongoDBModelCollectionInfo-getCappedMax.txt b/source/reference/method/MongoDBModelCollectionInfo-getCappedMax.txt new file mode 100644 index 00000000..0b86f350 --- /dev/null +++ b/source/reference/method/MongoDBModelCollectionInfo-getCappedMax.txt @@ -0,0 +1,69 @@ +============================================== +MongoDB\\Model\\CollectionInfo::getCappedMax() +============================================== + +.. deprecated:: 1.9 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Model\CollectionInfo::getCappedMax() + + Return the document limit for the capped collection. This correlates with the + ``max`` option for :phpmethod:`MongoDB\Database::createCollection()`. + + .. code-block:: php + + function getCappedMax(): integer|null + +Return Values +------------- + +The document limit for the capped collection. If the collection is not capped, +``null`` will be returned. + +This method is deprecated in favor of using +:phpmethod:`MongoDB\Model\CollectionInfo::getOptions()` and accessing the +``max`` key. + +Examples +-------- + +.. code-block:: php + + 'foo', + 'options' => [ + 'capped' => true, + 'size' => 1048576, + 'max' => 100, + ] + ]); + + var_dump($info->getCappedMax()); + +The output would then resemble: + +.. code-block:: none + + int(100) + +See Also +-------- + +- :phpmethod:`MongoDB\Model\CollectionInfo::getCappedSize()` +- :phpmethod:`MongoDB\Model\CollectionInfo::isCapped()` +- :phpmethod:`MongoDB\Database::createCollection()` +- :manual:`Capped Collections ` in the MongoDB manual +- :manual:`listCollections ` command + reference in the MongoDB manual diff --git a/source/reference/method/MongoDBModelCollectionInfo-getCappedSize.txt b/source/reference/method/MongoDBModelCollectionInfo-getCappedSize.txt new file mode 100644 index 00000000..9b0101aa --- /dev/null +++ b/source/reference/method/MongoDBModelCollectionInfo-getCappedSize.txt @@ -0,0 +1,69 @@ +=============================================== +MongoDB\\Model\\CollectionInfo::getCappedSize() +=============================================== + +.. deprecated:: 1.9 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Model\CollectionInfo::getCappedSize() + + Return the size limit for the capped collection in bytes. This correlates + with the ``size`` option for + :phpmethod:`MongoDB\Database::createCollection()`. + + .. code-block:: php + + function getCappedSize(): integer|null + +Return Values +------------- + +The size limit for the capped collection in bytes. If the collection is not +capped, ``null`` will be returned. + +This method is deprecated in favor of using +:phpmethod:`MongoDB\Model\CollectionInfo::getOptions()` and accessing the +``size`` key. + +Examples +-------- + +.. code-block:: php + + 'foo', + 'options' => [ + 'capped' => true, + 'size' => 1048576, + ] + ]); + + var_dump($info->getCappedSize()); + +The output would then resemble: + +.. code-block:: none + + int(1048576) + +See Also +-------- + +- :phpmethod:`MongoDB\Model\CollectionInfo::getCappedMax()` +- :phpmethod:`MongoDB\Model\CollectionInfo::isCapped()` +- :phpmethod:`MongoDB\Database::createCollection()` +- :manual:`Capped Collections ` in the MongoDB manual +- :manual:`listCollections ` command + reference in the MongoDB manual diff --git a/source/reference/method/MongoDBModelCollectionInfo-getIdIndex.txt b/source/reference/method/MongoDBModelCollectionInfo-getIdIndex.txt new file mode 100644 index 00000000..73f47668 --- /dev/null +++ b/source/reference/method/MongoDBModelCollectionInfo-getIdIndex.txt @@ -0,0 +1,75 @@ +============================================ +MongoDB\\Model\\CollectionInfo::getIdIndex() +============================================ + +.. versionadded:: 1.9 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Model\CollectionInfo::getIdIndex() + + Returns information about the ``_id`` field index. + + .. code-block:: php + + function getIdIndex(): array + +Return Values +------------- + +An array containing information on the ``_id`` index. This corresponds to the +``idIndex`` field returned in the ``listCollections`` command reply. + +Examples +-------- + +.. code-block:: php + + 'view', + 'name' => 'foo', + 'idIndex' => [ + 'v' => 2, + 'key' => ['_id' => 1], + 'name' => '_id', + 'ns' => 'test.foo', + ], + ]); + + var_dump($info->getIdIndex()); + +The output would then resemble: + +.. code-block:: none + + array(4) { + ["v"]=> + int(2) + ["key"]=> + array(1) { + ["_id"]=> + int(1) + } + ["name"]=> + string(3) "_id" + ["ns"]=> + string(8) "test.foo" + } + +See Also +-------- + +- :phpmethod:`MongoDB\Database::createCollection()` +- :manual:`listCollections ` command + reference in the MongoDB manual diff --git a/source/reference/method/MongoDBModelCollectionInfo-getInfo.txt b/source/reference/method/MongoDBModelCollectionInfo-getInfo.txt new file mode 100644 index 00000000..efdc1182 --- /dev/null +++ b/source/reference/method/MongoDBModelCollectionInfo-getInfo.txt @@ -0,0 +1,61 @@ +========================================= +MongoDB\\Model\\CollectionInfo::getInfo() +========================================= + +.. versionadded:: 1.9 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Model\CollectionInfo::getInfo() + + Returns additional information about the collection. + + .. code-block:: php + + function getInfo(): array + +Return Values +------------- + +An array containing extra information about the collection. This corresponds to +the ``info`` field returned in the ``listCollections`` command reply. + +Examples +-------- + +.. code-block:: php + + 'view', + 'name' => 'foo', + 'info' => ['readOnly' => true] + ]); + + var_dump($info->getInfo()); + +The output would then resemble: + +.. code-block:: none + + array(1) { + ["readOnly"]=> + bool(true) + } + +See Also +-------- + +- :phpmethod:`MongoDB\Database::createCollection()` +- :manual:`listCollections ` command + reference in the MongoDB manual diff --git a/source/reference/method/MongoDBModelCollectionInfo-getName.txt b/source/reference/method/MongoDBModelCollectionInfo-getName.txt new file mode 100644 index 00000000..83a74b2b --- /dev/null +++ b/source/reference/method/MongoDBModelCollectionInfo-getName.txt @@ -0,0 +1,52 @@ +========================================= +MongoDB\\Model\\CollectionInfo::getName() +========================================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Model\CollectionInfo::getName() + + Return the collection name. + + .. code-block:: php + + function getName(): string + +Return Values +------------- + +The collection name. This corresponds to the ``name`` field returned in the +``listCollections`` command reply. + +Examples +-------- + +.. code-block:: php + + 'foo']); + + echo $info->getName(); + +The output would then resemble: + +.. code-block:: none + + foo + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::getCollectionName()` +- :manual:`listCollections ` command + reference in the MongoDB manual diff --git a/source/reference/method/MongoDBModelCollectionInfo-getOptions.txt b/source/reference/method/MongoDBModelCollectionInfo-getOptions.txt new file mode 100644 index 00000000..d438b44b --- /dev/null +++ b/source/reference/method/MongoDBModelCollectionInfo-getOptions.txt @@ -0,0 +1,65 @@ +============================================ +MongoDB\\Model\\CollectionInfo::getOptions() +============================================ + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Model\CollectionInfo::getOptions() + + Return the collection options. This correlates with the options for + :phpmethod:`MongoDB\Database::createCollection()`, but may include + additional fields set by the server. + + .. code-block:: php + + function getOptions(): array + +Return Values +------------- + +The collection options. This corresponds to the ``options`` field returned in +the ``listCollections`` command reply. + +Examples +-------- + +.. code-block:: php + + 'foo', + 'options' => [ + 'capped' => true, + 'size' => 1048576, + ] + ]); + + var_dump($info->getOptions()); + +The output would then resemble: + +.. code-block:: none + + array(2) { + ["capped"]=> + bool(true) + ["size"]=> + int(1048576) + } + +See Also +-------- + +- :phpmethod:`MongoDB\Database::createCollection()` +- :manual:`listCollections ` command + reference in the MongoDB manual diff --git a/source/reference/method/MongoDBModelCollectionInfo-getType.txt b/source/reference/method/MongoDBModelCollectionInfo-getType.txt new file mode 100644 index 00000000..39a6c442 --- /dev/null +++ b/source/reference/method/MongoDBModelCollectionInfo-getType.txt @@ -0,0 +1,54 @@ +========================================= +MongoDB\\Model\\CollectionInfo::getType() +========================================= + +.. versionadded:: 1.9 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Model\CollectionInfo::getType() + + Return the collection type. + + .. code-block:: php + + function getType(): string + +Return Values +------------- + +The collection type. This corresponds to the ``type`` field returned in the +``listCollections`` command reply. + +Examples +-------- + +.. code-block:: php + + 'collection', 'name' => 'foo']); + + echo $info->getType(); + +The output would then resemble: + +.. code-block:: none + + collection + +See Also +-------- + +- :phpmethod:`MongoDB\Database::createCollection()` +- :manual:`listCollections ` command + reference in the MongoDB manual diff --git a/source/reference/method/MongoDBModelCollectionInfo-isCapped.txt b/source/reference/method/MongoDBModelCollectionInfo-isCapped.txt new file mode 100644 index 00000000..aa70df80 --- /dev/null +++ b/source/reference/method/MongoDBModelCollectionInfo-isCapped.txt @@ -0,0 +1,66 @@ +========================================== +MongoDB\\Model\\CollectionInfo::isCapped() +========================================== + +.. deprecated:: 1.9 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Model\CollectionInfo::isCapped() + + Return whether the collection is a :manual:`capped collection + `. + + .. code-block:: php + + function isCapped(): boolean + +Return Values +------------- + +A boolean indicating whether the collection is a capped collection. + +This method is deprecated in favor of using +:phpmethod:`MongoDB\Model\CollectionInfo::getOptions()` and accessing the +``capped`` key. + +Examples +-------- + +.. code-block:: php + + 'foo', + 'options' => [ + 'capped' => true, + 'size' => 1048576, + ] + ]); + + var_dump($info->isCapped()); + +The output would then resemble: + +.. code-block:: none + + bool(true) + +See Also +-------- + +- :phpmethod:`MongoDB\Model\CollectionInfo::getCappedMax()` +- :phpmethod:`MongoDB\Model\CollectionInfo::getCappedSize()` +- :manual:`Capped Collections ` in the MongoDB manual +- :manual:`listCollections ` command + reference in the MongoDB manual diff --git a/source/reference/method/MongoDBModelDatabaseInfo-getName.txt b/source/reference/method/MongoDBModelDatabaseInfo-getName.txt new file mode 100644 index 00000000..4ef37321 --- /dev/null +++ b/source/reference/method/MongoDBModelDatabaseInfo-getName.txt @@ -0,0 +1,51 @@ +======================================= +MongoDB\\Model\\DatabaseInfo::getName() +======================================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Model\DatabaseInfo::getName() + + Return the database name. + + .. code-block:: php + + function getName(): string + +Return Values +------------- + +The database name. + +Examples +-------- + +.. code-block:: php + + 'foo']); + + echo $info->getName(); + +The output would then resemble: + +.. code-block:: none + + foo + +See Also +-------- + +- :phpmethod:`MongoDB\Database::getDatabaseName()` +- :manual:`listDatabases ` command reference + in the MongoDB manual diff --git a/source/reference/method/MongoDBModelDatabaseInfo-getSizeOnDisk.txt b/source/reference/method/MongoDBModelDatabaseInfo-getSizeOnDisk.txt new file mode 100644 index 00000000..3af6ef48 --- /dev/null +++ b/source/reference/method/MongoDBModelDatabaseInfo-getSizeOnDisk.txt @@ -0,0 +1,50 @@ +============================================= +MongoDB\\Model\\DatabaseInfo::getSizeOnDisk() +============================================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Model\DatabaseInfo::getSizeOnDisk() + + Return the total size of the database file on disk in bytes. + + .. code-block:: php + + function getSizeOnDisk(): integer + +Return Values +------------- + +The total size of the database file on disk in bytes. + +Examples +-------- + +.. code-block:: php + + 1048576]); + + var_dump($info->getSizeOnDisk()); + +The output would then resemble: + +.. code-block:: none + + int(1048576) + +See Also +-------- + +- :manual:`listDatabases ` command reference + in the MongoDB manual diff --git a/source/reference/method/MongoDBModelDatabaseInfo-isEmpty.txt b/source/reference/method/MongoDBModelDatabaseInfo-isEmpty.txt new file mode 100644 index 00000000..72849b8e --- /dev/null +++ b/source/reference/method/MongoDBModelDatabaseInfo-isEmpty.txt @@ -0,0 +1,50 @@ +======================================= +MongoDB\\Model\\DatabaseInfo::isEmpty() +======================================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Model\DatabaseInfo::isEmpty() + + Return whether the database has any data. + + .. code-block:: php + + function isEmpty(): boolean + +Return Values +------------- + +A boolean indicating whether the database has any data. + +Examples +-------- + +.. code-block:: php + + true]); + + var_dump($info->isEmpty()); + +The output would then resemble: + +.. code-block:: none + + bool(true) + +See Also +-------- + +- :manual:`listDatabases ` command reference + in the MongoDB manual diff --git a/source/reference/method/MongoDBModelIndexInfo-getKey.txt b/source/reference/method/MongoDBModelIndexInfo-getKey.txt new file mode 100644 index 00000000..0925428f --- /dev/null +++ b/source/reference/method/MongoDBModelIndexInfo-getKey.txt @@ -0,0 +1,58 @@ +=================================== +MongoDB\\Model\\IndexInfo::getKey() +=================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Model\IndexInfo::getKey() + + Return the index specification (i.e. indexed field(s) and order). This + correlates with the ``$key`` parameter for + :phpmethod:`MongoDB\Collection::createIndex()`. + + .. code-block:: php + + function getKey(): array + +Return Values +------------- + +The index specification as an associative array. + +Examples +-------- + +.. code-block:: php + + ['x' => 1], + ]); + + var_dump($info->getKey()); + +The output would then resemble: + +.. code-block:: none + + array(1) { + ["x"]=> + int(1) + } + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::createIndex()` +- :manual:`listIndexes ` command reference in + the MongoDB manual diff --git a/source/reference/method/MongoDBModelIndexInfo-getName.txt b/source/reference/method/MongoDBModelIndexInfo-getName.txt new file mode 100644 index 00000000..4404964d --- /dev/null +++ b/source/reference/method/MongoDBModelIndexInfo-getName.txt @@ -0,0 +1,55 @@ +==================================== +MongoDB\\Model\\IndexInfo::getName() +==================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Model\IndexInfo::getName() + + Return the index name. This correlates with the return value of + :phpmethod:`MongoDB\Collection::createIndex()`. An index name may be derived + from the ``$key`` parameter or explicitly specified via the ``name`` option. + + .. code-block:: php + + function getName(): string + +Return Values +------------- + +The index name. + +Examples +-------- + +.. code-block:: php + + 'x_1', + ]); + + echo $info->getName(); + +The output would then resemble: + +.. code-block:: none + + x_1 + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::createIndex()` +- :manual:`listIndexes ` command reference in + the MongoDB manual diff --git a/source/reference/method/MongoDBModelIndexInfo-getNamespace.txt b/source/reference/method/MongoDBModelIndexInfo-getNamespace.txt new file mode 100644 index 00000000..099a1830 --- /dev/null +++ b/source/reference/method/MongoDBModelIndexInfo-getNamespace.txt @@ -0,0 +1,55 @@ +========================================= +MongoDB\\Model\\IndexInfo::getNamespace() +========================================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Model\IndexInfo::getNamespace() + + Return the index namespace, which is the namespace of the collection + containing the index. + + .. code-block:: php + + function getNamespace(): string + +Return Values +------------- + +The index namespace. + +Examples +-------- + +.. code-block:: php + + 'foo.bar', + ]); + + echo $info->getNamespace(); + +The output would then resemble: + +.. code-block:: none + + foo.bar + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::createIndex()` +- :phpmethod:`MongoDB\Collection::getNamespace()` +- :manual:`listIndexes ` command reference in + the MongoDB manual diff --git a/source/reference/method/MongoDBModelIndexInfo-getVersion.txt b/source/reference/method/MongoDBModelIndexInfo-getVersion.txt new file mode 100644 index 00000000..cd0d1bb4 --- /dev/null +++ b/source/reference/method/MongoDBModelIndexInfo-getVersion.txt @@ -0,0 +1,53 @@ +======================================= +MongoDB\\Model\\IndexInfo::getVersion() +======================================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Model\IndexInfo::getVersion() + + Return the index version. + + .. code-block:: php + + function getVersion(): integer + +Return Values +------------- + +The index version. + +Examples +-------- + +.. code-block:: php + + 1, + ]); + + var_dump($info->getVersion()); + +The output would then resemble: + +.. code-block:: none + + int(1) + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::createIndex()` +- :manual:`listIndexes ` command reference in + the MongoDB manual diff --git a/source/reference/method/MongoDBModelIndexInfo-is2dSphere.txt b/source/reference/method/MongoDBModelIndexInfo-is2dSphere.txt new file mode 100644 index 00000000..27fd3f9a --- /dev/null +++ b/source/reference/method/MongoDBModelIndexInfo-is2dSphere.txt @@ -0,0 +1,61 @@ +======================================= +MongoDB\\Model\\IndexInfo::is2dSphere() +======================================= + +.. versionadded:: 1.4 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Model\IndexInfo::is2dSphere() + + Return whether the index is a :manual:`2dsphere ` + index. + + .. code-block:: php + + function is2dSphere(): boolean + +Return Values +------------- + +A boolean indicating whether the index is a 2dsphere index. + +Examples +-------- + +.. code-block:: php + + selectCollection('test', 'places'); + + $collection->createIndex(['pos' => '2dsphere']); + + foreach ($collection->listIndexes() as $index) { + if ($index->is2dSphere()) { + printf("%s has 2dsphereIndexVersion: %d\n", $index->getName(), $index['2dsphereIndexVersion']); + } + } + +The output would then resemble: + +.. code-block:: none + + pos_2dsphere has 2dsphereIndexVersion: 3 + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::createIndex()` +- :phpmethod:`MongoDB\Collection::listIndexes()` +- :manual:`2dsphere Indexes ` reference in the MongoDB + manual diff --git a/source/reference/method/MongoDBModelIndexInfo-isGeoHaystack.txt b/source/reference/method/MongoDBModelIndexInfo-isGeoHaystack.txt new file mode 100644 index 00000000..87b7a53d --- /dev/null +++ b/source/reference/method/MongoDBModelIndexInfo-isGeoHaystack.txt @@ -0,0 +1,64 @@ +========================================== +MongoDB\\Model\\IndexInfo::isGeoHaystack() +========================================== + +.. versionadded:: 1.4 + +.. deprecated:: 1.16 + MongoDB 5.0 and later no longer supports geoHaystack indexes. + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Model\IndexInfo::isGeoHaystack() + + Return whether the index is a :manual:`geoHaystack ` + index. + + .. code-block:: php + + function isGeoHaystack(): boolean + +Return Values +------------- + +A boolean indicating whether the index is a geoHaystack index. + +Examples +-------- + +.. code-block:: php + + selectCollection('test', 'places'); + + $collection->createIndex(['pos' => 'geoHaystack', 'x' => 1], ['bucketSize' => 5]); + + foreach ($collection->listIndexes() as $index) { + if ($index->isGeoHaystack()) { + printf("%s has bucketSize: %d\n", $index->getName(), $index['bucketSize']); + } + } + +The output would then resemble: + +.. code-block:: none + + pos_geoHaystack_x_1 has bucketSize: 5 + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::createIndex()` +- :phpmethod:`MongoDB\Collection::listIndexes()` +- :manual:`geoHaystack Indexes ` reference in the MongoDB + manual diff --git a/source/reference/method/MongoDBModelIndexInfo-isSparse.txt b/source/reference/method/MongoDBModelIndexInfo-isSparse.txt new file mode 100644 index 00000000..22c307ab --- /dev/null +++ b/source/reference/method/MongoDBModelIndexInfo-isSparse.txt @@ -0,0 +1,56 @@ +===================================== +MongoDB\\Model\\IndexInfo::isSparse() +===================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Model\IndexInfo::isSparse() + + Return whether the index is a :manual:`sparse index `. + This correlates with the ``sparse`` option for + :phpmethod:`MongoDB\Collection::createIndex()`. + + .. code-block:: php + + function isSparse(): boolean + +Return Values +------------- + +A boolean indicating whether the index is a sparse index. + +Examples +-------- + +.. code-block:: php + + true, + ]); + + var_dump($info->isSparse()); + +The output would then resemble: + +.. code-block:: none + + bool(true) + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::createIndex()` +- :manual:`listIndexes ` command reference in + the MongoDB manual +- :manual:`Sparse Indexes ` in the MongoDB manual diff --git a/source/reference/method/MongoDBModelIndexInfo-isText.txt b/source/reference/method/MongoDBModelIndexInfo-isText.txt new file mode 100644 index 00000000..b600ebdd --- /dev/null +++ b/source/reference/method/MongoDBModelIndexInfo-isText.txt @@ -0,0 +1,60 @@ +=================================== +MongoDB\\Model\\IndexInfo::isText() +=================================== + +.. versionadded:: 1.4 + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Model\IndexInfo::isText() + + Return whether the index is a :manual:`text ` index. + + .. code-block:: php + + function isText(): boolean + +Return Values +------------- + +A boolean indicating whether the index is a text index. + +Examples +-------- + +.. code-block:: php + + selectCollection('test', 'restaurants'); + + $collection->createIndex(['name' => 'text']); + + foreach ($collection->listIndexes() as $index) { + if ($index->isText()) { + printf("%s has default language: %d\n", $index->getName(), $index['default_language']); + } + } + +The output would then resemble: + +.. code-block:: none + + name_text has default language: english + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::createIndex()` +- :phpmethod:`MongoDB\Collection::listIndexes()` +- :manual:`Text Indexes ` reference in the MongoDB + manual diff --git a/source/reference/method/MongoDBModelIndexInfo-isTtl.txt b/source/reference/method/MongoDBModelIndexInfo-isTtl.txt new file mode 100644 index 00000000..ef417942 --- /dev/null +++ b/source/reference/method/MongoDBModelIndexInfo-isTtl.txt @@ -0,0 +1,56 @@ +================================== +MongoDB\\Model\\IndexInfo::isTtl() +================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Model\IndexInfo::isTtl() + + Return whether the index is a :manual:`TTL index `. This + correlates with the ``expireAfterSeconds`` option for + :phpmethod:`MongoDB\Collection::createIndex()`. + + .. code-block:: php + + function isTtl(): boolean + +Return Values +------------- + +A boolean indicating whether the index is a TTL index. + +Examples +-------- + +.. code-block:: php + + 100, + ]); + + var_dump($info->isTtl()); + +The output would then resemble: + +.. code-block:: none + + bool(true) + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::createIndex()` +- :manual:`listIndexes ` command reference in + the MongoDB manual +- :manual:`TTL Indexes ` in the MongoDB manual diff --git a/source/reference/method/MongoDBModelIndexInfo-isUnique.txt b/source/reference/method/MongoDBModelIndexInfo-isUnique.txt new file mode 100644 index 00000000..12d8b45c --- /dev/null +++ b/source/reference/method/MongoDBModelIndexInfo-isUnique.txt @@ -0,0 +1,56 @@ +===================================== +MongoDB\\Model\\IndexInfo::isUnique() +===================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Model\IndexInfo::isUnique() + + Return whether the index is a :manual:`unique index `. + This correlates with the ``unique`` option for + :phpmethod:`MongoDB\Collection::createIndex()`. + + .. code-block:: php + + function isUnique(): boolean + +Return Values +------------- + +A boolean indicating whether the index is a unique index. + +Examples +-------- + +.. code-block:: php + + true, + ]); + + var_dump($info->isUnique()); + +The output would then resemble: + +.. code-block:: none + + bool(true) + +See Also +-------- + +- :phpmethod:`MongoDB\Collection::createIndex()` +- :manual:`listIndexes ` command reference in + the MongoDB manual +- :manual:`Unique Indexes ` in the MongoDB manual diff --git a/source/reference/method/MongoDBUpdateResult-getMatchedCount.txt b/source/reference/method/MongoDBUpdateResult-getMatchedCount.txt new file mode 100644 index 00000000..f668fe12 --- /dev/null +++ b/source/reference/method/MongoDBUpdateResult-getMatchedCount.txt @@ -0,0 +1,49 @@ +======================================== +MongoDB\\UpdateResult::getMatchedCount() +======================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\UpdateResult::getMatchedCount() + + Return the number of documents that were matched. + + .. code-block:: php + + function getMatchedCount(): integer + + This method should only be called if the write was acknowledged. + + .. note:: + + If an update/replace operation results in no change to the document + (e.g. setting the value of a field to its current value), the matched + count may be greater than the value returned by + :phpmethod:`getModifiedCount() + `. + +Return Values +------------- + +The number of documents that were matched. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-badmethodcallexception-write-result.rst + +See Also +-------- + +- :phpmethod:`MongoDB\UpdateResult::getModifiedCount()` +- :php:`MongoDB\Driver\WriteResult::getMatchedCount() + ` diff --git a/source/reference/method/MongoDBUpdateResult-getModifiedCount.txt b/source/reference/method/MongoDBUpdateResult-getModifiedCount.txt new file mode 100644 index 00000000..5c8bfe73 --- /dev/null +++ b/source/reference/method/MongoDBUpdateResult-getModifiedCount.txt @@ -0,0 +1,48 @@ +========================================= +MongoDB\\UpdateResult::getModifiedCount() +========================================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\UpdateResult::getModifiedCount() + + Return the number of documents that were modified. + + .. code-block:: php + + function getModifiedCount(): integer|null + + This method should only be called if the write was acknowledged. + + .. note:: + + If an update/replace operation results in no change to the document + (e.g. setting the value of a field to its current value), the modified + count may be less than the value returned by :phpmethod:`getMatchedCount() + `. + +Return Values +------------- + +The number of documents that were modified. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-badmethodcallexception-write-result.rst + +See Also +-------- + +- :phpmethod:`MongoDB\UpdateResult::getMatchedCount()` +- :php:`MongoDB\Driver\WriteResult::getModifiedCount() + ` diff --git a/source/reference/method/MongoDBUpdateResult-getUpsertedCount.txt b/source/reference/method/MongoDBUpdateResult-getUpsertedCount.txt new file mode 100644 index 00000000..7074696e --- /dev/null +++ b/source/reference/method/MongoDBUpdateResult-getUpsertedCount.txt @@ -0,0 +1,42 @@ +========================================= +MongoDB\\UpdateResult::getUpsertedCount() +========================================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\UpdateResult::getUpsertedCount() + + Return the number of documents that were upserted. + + .. code-block:: php + + function getUpsertedCount(): integer + + This method should only be called if the write was acknowledged. + +Return Values +------------- + +The total number of documents that were upserted. This should be either ``0`` or +``1`` for an acknowledged update or replace operation, depending on whether an +upsert occurred. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-badmethodcallexception-write-result.rst + +See Also +-------- + +- :php:`MongoDB\Driver\WriteResult::getUpsertedCount() + ` diff --git a/source/reference/method/MongoDBUpdateResult-getUpsertedId.txt b/source/reference/method/MongoDBUpdateResult-getUpsertedId.txt new file mode 100644 index 00000000..d9200778 --- /dev/null +++ b/source/reference/method/MongoDBUpdateResult-getUpsertedId.txt @@ -0,0 +1,44 @@ +====================================== +MongoDB\\UpdateResult::getUpsertedId() +====================================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\UpdateResult::getUpsertedId() + + Return the ID (i.e. ``_id`` field value) of the upserted document. + + .. code-block:: php + + function getUpsertedId(): mixed|null + +Return Values +------------- + +The ID (i.e. ``_id`` field value) of the upserted document. If no document was +upserted, ``null`` will be returned. + +If the document had an ID prior to upserting (i.e. the server did not need to +generate an ID), this will contain its ``_id`` field value. Any server-generated +ID will be a :php:`MongoDB\BSON\ObjectId ` +instance. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-badmethodcallexception-write-result.rst + +See Also +-------- + +- :php:`MongoDB\Driver\WriteResult::getUpsertedIds() + ` diff --git a/source/reference/method/MongoDBUpdateResult-isAcknowledged.txt b/source/reference/method/MongoDBUpdateResult-isAcknowledged.txt new file mode 100644 index 00000000..2e7c7b05 --- /dev/null +++ b/source/reference/method/MongoDBUpdateResult-isAcknowledged.txt @@ -0,0 +1,34 @@ +======================================= +MongoDB\\UpdateResult::isAcknowledged() +======================================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\UpdateResult::isAcknowledged() + + Return whether the write was acknowledged. + + .. code-block:: php + + function isAcknowledged(): boolean + +Return Values +------------- + +A boolean indicating whether the write was acknowledged. + +See Also +-------- + +- :php:`MongoDB\Driver\WriteResult::isAcknowledged() + ` +- :manual:`Write Concern ` in the MongoDB manual diff --git a/source/reference/result-classes.txt b/source/reference/result-classes.txt new file mode 100644 index 00000000..b59f480c --- /dev/null +++ b/source/reference/result-classes.txt @@ -0,0 +1,22 @@ +============== +Result Classes +============== + +.. default-domain:: mongodb + +.. toctree:: + :titlesonly: + + BulkWriteResult Class + DeleteResult Class + InsertManyResult Class + InsertOneResult Class + UpdateResult Class + ChangeStream Class + MapReduceResult Class + CollectionInfo Class + CollectionInfoIterator Class + DatabaseInfo Class + DatabaseInfoIterator Class + IndexInfo Class + IndexInfoIterator Class \ No newline at end of file diff --git a/source/tutorial.txt b/source/tutorial.txt new file mode 100644 index 00000000..31595bdc --- /dev/null +++ b/source/tutorial.txt @@ -0,0 +1,22 @@ +Tutorials +========= + +.. default-domain:: mongodb + +.. toctree:: + + /tutorial/connecting + /tutorial/server-selection + /tutorial/crud + /tutorial/codecs + /tutorial/collation + /tutorial/commands + /tutorial/custom-types + /tutorial/decimal128 + /tutorial/encryption + /tutorial/gridfs + /tutorial/indexes + /tutorial/tailable-cursor + /tutorial/example-data + /tutorial/modeling-bson-data + /tutorial/stable-api diff --git a/source/tutorial/codecs.txt b/source/tutorial/codecs.txt new file mode 100644 index 00000000..a4bb5dd6 --- /dev/null +++ b/source/tutorial/codecs.txt @@ -0,0 +1,117 @@ +====== +Codecs +====== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. versionadded:: 1.17 + +Overview +-------- + +Codecs are used to decode BSON documents into PHP objects, and encode PHP objects into BSON documents. In contrast to +other methods (e.g. type maps), codecs allow for greater customization and handling of different data types. They +separate logic for BSON encoding and decoding from the domain classes, which also enables BSON to be decoded into plain +old PHP objects. + +Handling Documents +------------------ + +The main logic is contained in a document codec. This class implements the ``MongoDB\Codec\DocumentCodec`` interface and +defines what data types can be encoded/decoded and how. The following example defines a ``Person`` class and a codec to +transform it: + +.. literalinclude:: /examples/codecs/handling-documents/Person.php + :language: php + +.. literalinclude:: /examples/codecs/handling-documents/PersonCodec.php + :language: php + +To then use this codec with a collection, specify the ``codec`` option when selecting the collection: + +.. literalinclude:: /examples/codecs/handling-documents/using-codec.php + :language: php + +The example above selects a collection and instructs it to use the ``PersonCodec`` for encoding and decoding documents. +When inserting data, the ``PersonCodec`` is used to encode the document. When retrieving data, the same ``PersonCodec`` +is used to decode BSON data into a ``Person`` instance. Note that while the ``PersonCodec`` could technically decode any +BSON document that contains a name field, we wouldn't want to use it for any other documents. Document codecs are meant +to be used with a :phpclass:`MongoDB\Collection`, or when decoding embedded documents. + +When using a collection with a codec, the codec will only accept and return data of that type for certain operations. +Insert and replace operations (e.g. ``insertOne``, ```findOneAndReplace``, and some ``bulkWrite`` operations) will +attempt to encode the given data using the provided codec. Trying to insert or replace a document that cannot be encoded +will result in an exception. Read operations (e.g. ``aggregate``, ``find``, and ``findOneAndUpdate``) will attempt to +decode returned documents using the provided codec. If the codec does not support the data returned, an exception will +be thrown. + +You can disable codec usage for a specific operation or use a different codec (e.g. to decode the result of an +aggregation pipeline) by specifying ``null`` for the ``codec`` option for any operation. Alternatively, specifying a +type map using the ``typeMap`` operation will also override the collection-level codec: + +.. literalinclude:: /examples/codecs/handling-documents/disabling-codec.php + :language: php + +.. _php-codec-handling-data-types: + +Handling Fields and Data Types +------------------------------ + +The previous example showed how to define a codec for a specific class. However, you may want to create a codec that +handles a particular data type in any document. This can be achieved by implementing the ``MongoDB\Codec\Codec`` +interface. + +The following example defines a codec that stores ``DateTimeInterface`` instances as an embedded document containing a +BSON date and accompanying timezone string. Those same embedded documents can then be translated back into a +``DateTimeImmutable`` during BSON decoding. + +.. literalinclude:: /examples/codecs/handling-data-types/DateTimeCodec.php + :language: php + +.. note:: + When writing a codec, you should be as lenient as possible when it comes to handling data. In this case, the codec + handles any ``DateTimeInterface`` when encoding to BSON, as a ``UTCDateTime`` instance can be created from any such + object. When decoding data from BSON, it will always decode to a ``DateTimeImmutable`` instance. + +This codec can now be leveraged by other codecs that handle date fields. + +First, we add a ``createdAt`` field to the ``Person`` class: + +.. literalinclude:: /examples/codecs/handling-data-types/Person.php + :language: php + +Last but not least, we modify the codec to handle the new field: + +.. literalinclude:: /examples/codecs/handling-data-types/PersonCodec.php + :language: php + +Handling Embedded Documents +--------------------------- + +A previous example showed how to handle a single document. However, sometimes you want to handle fields that contain +embedded documents. We will demonstrate this using an ``Address`` document, which we will embed within a ``Person`` +document. To ensure consistency, we're going to make this a read-only class: + +.. literalinclude:: /examples/codecs/handling-embedded-documents/Address.php + :language: php + +We can now create a document codec for this class: + +.. literalinclude:: /examples/codecs/handling-embedded-documents/AddressCodec.php + :language: php + +The ``Person`` class gets a new ``address`` field, but we'll leave this optional: + +.. literalinclude:: /examples/codecs/handling-embedded-documents/Person.php + :language: php + +The ``PersonCodec`` can now handle the optional ``address`` field when transforming data: + +.. literalinclude:: /examples/codecs/handling-embedded-documents/PersonCodec.php + :language: php diff --git a/source/tutorial/collation.txt b/source/tutorial/collation.txt new file mode 100644 index 00000000..6ba335e7 --- /dev/null +++ b/source/tutorial/collation.txt @@ -0,0 +1,373 @@ +========= +Collation +========= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. versionadded:: 1.1 + +Overview +-------- + +MongoDB 3.4 introduced support for :manual:`collations +`, which provide a set of rules to comply with the +conventions of a particular language when comparing strings. + +For example, in Canadian French, the last accent in a given word determines the +sorting order. Consider the following French words: + +.. code-block:: none + + cote < coté < côte < côté + +The sort order using the Canadian French collation would result in the +following: + +.. code-block:: none + + cote < côte < coté < côté + +If collation is unspecified, MongoDB uses simple binary comparison for strings. +As such, the sort order of the words would be: + +.. code-block:: none + + cote < coté < côte < côté + +Usage +----- + +You can specify a default collation for collections and indexes when they are +created, or specify a collation for CRUD operations and aggregations. For +operations that support collation, MongoDB uses the collection's default +collation unless the operation specifies a different collation. + +Collation Parameters +~~~~~~~~~~~~~~~~~~~~ + +.. code-block:: php + + 'collation' => [ + 'locale' => , + 'caseLevel' => , + 'caseFirst' => , + 'strength' => , + 'numericOrdering' => , + 'alternate' => , + 'maxVariable' => , + 'normalization' => , + 'backwards' => , + ] + +The only required parameter is ``locale``, which the server parses as an `ICU +format locale ID `_. For example, set +``locale`` to ``en_US`` to represent US English or ``fr_CA`` to represent +Canadian French. + +For a complete description of the available parameters, see :manual:`Collation +Document ` in the MongoDB manual. + +Assign a Default Collation to a Collection +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following example creates a new collection called ``contacts`` on the +``test`` database and assigns a default collation with the ``fr_CA`` locale. +Specifying a collation when you create the collection ensures that all +operations involving a query that are run against the ``contacts`` collection +use the ``fr_CA`` collation, unless the query specifies another collation. Any +indexes on the new collection also inherit the default collation, unless the +creation command specifies another collation. + +.. code-block:: php + + test; + + $database->createCollection('contacts', [ + 'collation' => ['locale' => 'fr_CA'], + ]); + +Assign a Collation to an Index +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To specify a collation for an index, use the ``collation`` option when you +create the index. + +The following example creates an index on the ``name`` field of the +``address_book`` collection, with the ``unique`` parameter enabled and a default +collation with ``locale`` set to ``en_US``. + +.. code-block:: php + + test->address_book; + + $collection->createIndex( + ['first_name' => 1], + [ + 'collation' => ['locale' => 'en_US'], + 'unique' => true, + ] + ); + +To use this index, make sure your queries also specify the same collation. The +following query uses the above index: + +.. code-block:: php + + test->address_book; + + $cursor = $collection->find( + ['first_name' => 'Adam'], + [ + 'collation' => ['locale' => 'en_US'], + ] + ); + +The following queries do **NOT** use the index. The first query uses no +collation, and the second uses a collation with a different ``strength`` value +than the collation on the index. + +.. code-block:: php + + test->address_book; + + $cursor1 = $collection->find(['first_name' => 'Adam']); + + $cursor2 = $collection->find( + ['first_name' => 'Adam'], + [ + 'collation' => [ + 'locale' => 'en_US', + 'strength' => 2, + ], + ] + ); + +Operations that Support Collation +--------------------------------- + +All reading, updating, and deleting methods support collation. Some examples are +listed below. + +``find()`` with ``sort`` +~~~~~~~~~~~~~~~~~~~~~~~~ + +Individual queries can specify a collation to use when matching and sorting +results. The following query and sort operation uses a German collation with the +``locale`` parameter set to ``de``. + +.. code-block:: php + + test->contacts; + + $cursor = $collection->find( + ['city' => 'New York'], + [ + 'collation' => ['locale' => 'de'], + 'sort' => ['name' => 1], + ] + ); + +``findOneAndUpdate()`` +~~~~~~~~~~~~~~~~~~~~~~ + +A collection called ``names`` contains the following documents: + +.. code-block:: javascript + + { "_id" : 1, "first_name" : "Hans" } + { "_id" : 2, "first_name" : "Gunter" } + { "_id" : 3, "first_name" : "Günter" } + { "_id" : 4, "first_name" : "Jürgen" } + +The following :phpmethod:`findOneAndUpdate() +` operation on the collection does not +specify a collation. + +.. code-block:: php + + test->names; + + $document = $collection->findOneAndUpdate( + ['first_name' => ['$lt' => 'Gunter']], + ['$set' => ['verified' => true]] + ); + +Because ``Gunter`` is lexically first in the collection, the above operation +returns no results and updates no documents. + +Consider the same :phpmethod:`findOneAndUpdate() +` operation but with a collation +specified, which uses the locale ``de@collation=phonebook``. + +.. note:: + + Some locales have a ``collation=phonebook`` option available for use with + languages which sort proper nouns differently from other words. According to + the ``de@collation=phonebook`` collation, characters with umlauts come before + the same characters without umlauts. + +.. code-block:: php + + test->names; + + $document = $collection->findOneAndUpdate( + ['first_name' => ['$lt' => 'Gunter']], + ['$set' => ['verified' => true]], + [ + 'collation' => ['locale' => 'de@collation=phonebook'], + 'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER, + ] + ); + +The operation returns the following updated document: + +.. code-block:: javascript + + { "_id" => 3, "first_name" => "Günter", "verified" => true } + +``findOneAndDelete()`` +~~~~~~~~~~~~~~~~~~~~~~ + +Set the ``numericOrdering`` collation parameter to ``true`` to compare numeric +strings by their numeric values. + +The collection ``numbers`` contains the following documents: + +.. code-block:: javascript + + { "_id" : 1, "a" : "16" } + { "_id" : 2, "a" : "84" } + { "_id" : 3, "a" : "179" } + +The following example matches the first document in which field ``a`` has a +numeric value greater than 100 and deletes it. + +.. code-block:: php + + test->numbers; + + $document = $collection->findOneAndDelete( + ['a' => ['$gt' =-> '100']], + [ + 'collation' => [ + 'locale' => 'en', + 'numericOrdering' => true, + ], + ] + ); + +After the above operation, the following documents remain in the collection: + +.. code-block:: javascript + + { "_id" : 1, "a" : "16" } + { "_id" : 2, "a" : "84" } + +If you perform the same operation without collation, the server deletes the +first document it finds in which the lexical value of ``a`` is greater than +``"100"``. + +.. code-block:: php + + test->numbers; + + $document = $collection->findOneAndDelete(['a' => ['$gt' =-> '100']]); + +After the above operation is executed, the document in which ``a`` was equal to +``"16"`` has been deleted, and the following documents remain in the collection: + +.. code-block:: javascript + + { "_id" : 2, "a" : "84" } + { "_id" : 3, "a" : "179" } + +``deleteMany()`` +~~~~~~~~~~~~~~~~ + +You can use collations with all the various CRUD operations which exist in the +|php-library|. + +The collection ``recipes`` contains the following documents: + +.. code-block:: javascript + + { "_id" : 1, "dish" : "veggie empanadas", "cuisine" : "Spanish" } + { "_id" : 2, "dish" : "beef bourgignon", "cuisine" : "French" } + { "_id" : 3, "dish" : "chicken molé", "cuisine" : "Mexican" } + { "_id" : 4, "dish" : "chicken paillard", "cuisine" : "french" } + { "_id" : 5, "dish" : "pozole verde", "cuisine" : "Mexican" } + +Setting the ``strength`` parameter of the collation document to ``1`` or ``2`` +causes the server to disregard case in the query filter. The following example +uses a case-insensitive query filter to delete all records in which the +``cuisine`` field matches ``French``. + +.. code-block:: php + + test->recipes; + + $collection->deleteMany( + ['cuisine' => 'French'], + [ + 'collation' => [ + 'locale' => 'en_US', + 'strength' => 1, + ], + ] + ); + +After the above operation runs, the documents with ``_id`` values of ``2`` and +``4`` are deleted from the collection. + +Aggregation +~~~~~~~~~~~ + +To use collation with an :phpmethod:`aggregate() +` operation, specify a collation in the +aggregation options. + +The following aggregation example uses a collection called ``names`` and groups +the ``first_name`` field together, counts the total number of results in each +group, and sorts the results by German phonebook order. + +.. code-block:: php + + test->names; + + $cursor = $collection->aggregate( + [ + ['$group' => ['_id' => '$first_name', 'name_count' => ['$sum' => 1]]], + ['$sort' => ['_id' => 1]], + ], + [ + 'collation' => ['locale' => 'de@collation=phonebook'], + ] + ); diff --git a/source/tutorial/commands.txt b/source/tutorial/commands.txt new file mode 100644 index 00000000..1debe37b --- /dev/null +++ b/source/tutorial/commands.txt @@ -0,0 +1,150 @@ +========================= +Execute Database Commands +========================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +Overview +-------- + +The |php-library| provides helper methods across the :phpclass:`Client +`, :phpclass:`Database `, and +:phpclass:`Collection ` classes for common +:manual:`database commands `. In addition, the +:phpmethod:`MongoDB\Database::command()` method may be used to run database +commands that do not have a helper method. + +The :phpmethod:`MongoDB\Database::command()` method always returns a +:php:`MongoDB\Driver\Cursor ` object, since it must +support execution of commands that return single result documents *and* multiple +results via a command cursor. + +Commands That Return a Single Result Document +--------------------------------------------- + +Most database commands return a single result document, which can be obtained by +converting the returned cursor to an array and accessing its first element. The +following example executes a :manual:`ping ` command +and prints its result document: + +.. code-block:: php + + test; + + $cursor = $database->command(['ping' => 1]); + + var_dump($cursor->toArray()[0]); + +The output would resemble: + +.. code-block:: none + + object(MongoDB\Model\BSONDocument)#11 (1) { + ["storage":"ArrayObject":private]=> + array(1) { + ["ok"]=> + float(1) + } + } + +Commands That Yield Multiple Results +------------------------------------ + +Some database commands return a cursor with multiple results. The following +example executes :manual:`listCollections `, +which returns a cursor containing a result document for each collection in the +``test`` database, and iterates through the results using a ``foreach`` loop. +Note that this example is illustrative; applications would generally use +:phpmethod:`MongoDB\Database::listCollections()` in practice. + +.. code-block:: php + + test; + + $cursor = $database->command(['listCollections' => 1]); + + foreach ($cursor as $collection) { + echo $collection['name'], "\n"; + } + +The output might resemble the following: + +.. code-block:: none + + persons + posts + zips + +.. note:: + + At the *protocol* level, commands that yield multiple results via a cursor + will return a single result document with the essential ingredients for + constructing the cursor (i.e. the cursor's ID, namespace, and an optional + first batch of results). If the :php:`MongoDB\Driver\Manager::executeCommand() + ` method in the extension detects + such a response, it will construct an iterable command cursor and return it + instead of the raw result document. If necessary, raw result documents can + still be observed using `command monitoring + `_. + +Specifying a Custom Read Preference +----------------------------------- + +Write commands, such as :manual:`createUser `, +can only be executed on a writable server (e.g. :term:`primary` replica set +member). Command helper methods in the |php-library|, such as +:phpmethod:`MongoDB\Database::drop()`, know to apply their own :term:`read +preference` if necessary. However, the :phpmethod:`MongoDB\Database::command()` +method is a generic method and defaults to the read preference of the Database +object on which it is invoked. When necessary, the ``readPreference`` option may +be used to override the default read preference. + +The following example connects to a cluster and specifies ``secondaryPreferred`` +as the Client's default read preference. It then specifies a ``primary`` read +preference when executing the ``createUser`` command on the ``test`` database: + +.. code-block:: php + + 'secondaryPreferred'] + ); + + $client->test; + + $cursor = $db->command( + [ + 'createUser' => 'username', + 'pwd' => 'password', + 'roles' => ['readWrite'], + ], + [ + 'readPreference' => new MongoDB\Driver\ReadPreference('primary'), + ] + ); + + var_dump($cursor->toArray()[0]); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Model\BSONDocument)#8 (1) { + ["storage":"ArrayObject":private]=> + array(1) { + ["ok"]=> + float(1) + } + } diff --git a/source/tutorial/connecting.txt b/source/tutorial/connecting.txt new file mode 100644 index 00000000..cffd19ef --- /dev/null +++ b/source/tutorial/connecting.txt @@ -0,0 +1,25 @@ +===================== +Connecting to MongoDB +===================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +Creating a Client instance +-------------------------------------------------------- + +.. include:: /reference/method/MongoDBClient__construct.txt + :start-after: start-connecting-include + :end-before: end-connecting-include + +Specifying connection options +----------------------------- + +Connection options can be passed via the ``$uri`` parameter, or through the +``$options`` and ``$driverOptions`` parameters. The available options are +documented in the :phpmethod:`MongoDB\Client::__construct()` reference. diff --git a/source/tutorial/crud.txt b/source/tutorial/crud.txt new file mode 100644 index 00000000..a69ec662 --- /dev/null +++ b/source/tutorial/crud.txt @@ -0,0 +1,794 @@ +=============== +CRUD Operations +=============== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + + +CRUD operations *create*, *read*, *update*, and *delete* documents. The +|php-library|'s :phpclass:`MongoDB\Collection` class implements MongoDB's +cross-driver `CRUD specification +`_, +providing access to methods for inserting, finding, updating, and deleting +documents in MongoDB. + +This document provides a general introduction to inserting, querying, updating, +and deleting documents using the |php-library|. The MongoDB Manual's +:manual:`CRUD Section ` provides a more thorough introduction to CRUD +operations with MongoDB. + +Insert Documents +---------------- + +Insert One Document +~~~~~~~~~~~~~~~~~~~ + +The :phpmethod:`MongoDB\Collection::insertOne()` method inserts a single +document into MongoDB and returns an instance of +:phpclass:`MongoDB\InsertOneResult`, which you can use to access the ID of the +inserted document. + +.. this uses the insertOne example from the method reference: + +.. include:: /reference/method/MongoDBCollection-insertOne.txt + :start-after: start-crud-include + :end-before: end-crud-include + +The output includes the ID of the inserted document. + +If you include an ``_id`` value when inserting a document, MongoDB checks to +ensure that the ``_id`` value is unique for the collection. If the ``_id`` value +is not unique, the insert operation fails due to a duplicate key error. + +The following example inserts a document while specifying the value for the +``_id``: + +.. code-block:: php + + test->users; + + $insertOneResult = $collection->insertOne(['_id' => 1, 'name' => 'Alice']); + + printf("Inserted %d document(s)\n", $insertOneResult->getInsertedCount()); + + var_dump($insertOneResult->getInsertedId()); + +The output would then resemble: + +.. code-block:: none + + Inserted 1 document(s) + int(1) + +.. seealso:: + + :phpmethod:`MongoDB\Collection::insertOne()` + +Insert Many Documents +~~~~~~~~~~~~~~~~~~~~~ + +The :phpmethod:`MongoDB\Collection::insertMany()` method allows you to insert +multiple documents in one write operation and returns an instance of +:phpclass:`MongoDB\InsertManyResult`, which you can use to access the IDs of +the inserted documents. + +.. this uses the insertMany example from the method reference: + +.. include:: /reference/method/MongoDBCollection-insertMany.txt + :start-after: start-crud-include + :end-before: end-crud-include + +.. seealso:: + + :phpmethod:`MongoDB\Collection::insertMany()` + +Query Documents +--------------- + +The |php-library| provides the :phpmethod:`MongoDB\Collection::findOne()` and +:phpmethod:`MongoDB\Collection::find()` methods for querying documents and the +:phpmethod:`MongoDB\Collection::aggregate()` method for performing +:manual:`aggregation operations `. + +.. include:: /includes/extracts/note-bson-comparison.rst + +Find One Document +~~~~~~~~~~~~~~~~~ + +:phpmethod:`MongoDB\Collection::findOne()` returns the :term:`first document +` that matches the query or ``null`` if no document matches the +query. + +The following example searches for the document with ``_id`` of ``"94301"``: + +.. code-block:: php + + test->zips; + + $document = $collection->findOne(['_id' => '94301']); + + var_dump($document); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Model\BSONDocument)#13 (1) { + ["storage":"ArrayObject":private]=> + array(5) { + ["_id"]=> + string(5) "94301" + ["city"]=> + string(9) "PALO ALTO" + ["loc"]=> + object(MongoDB\Model\BSONArray)#12 (1) { + ["storage":"ArrayObject":private]=> + array(2) { + [0]=> + float(-122.149685) + [1]=> + float(37.444324) + } + } + ["pop"]=> + int(15965) + ["state"]=> + string(2) "CA" + } + } + +.. note:: + + The criteria in this example matched an ``_id`` with a string value of + ``"94301"``. The same criteria would not have matched a document with an + integer value of ``94301`` due to MongoDB's :manual:`comparison rules for + BSON types `. Similarly, users should + use a :php:`MongoDB\BSON\ObjectId ` object + when matching an ``_id`` with an :manual:`ObjectId ` + value, as strings and ObjectIds are not directly comparable. + +.. seealso:: + + :phpmethod:`MongoDB\Collection::findOne()` + +.. _php-find-many-documents: + +Find Many Documents +~~~~~~~~~~~~~~~~~~~ + +:phpmethod:`MongoDB\Collection::find()` returns a +:php:`MongoDB\Driver\Cursor ` object, which you can +iterate upon to access all matched documents. + +The following example lists the documents in the ``zips`` collection with the +specified city and state values: + +.. code-block:: php + + test->zips; + + $cursor = $collection->find(['city' => 'JERSEY CITY', 'state' => 'NJ']); + + foreach ($cursor as $document) { + echo $document['_id'], "\n"; + } + +The output would resemble: + +.. code-block:: none + + 07302 + 07304 + 07305 + 07306 + 07307 + 07310 + +.. seealso:: + + :phpmethod:`MongoDB\Collection::find()` + +.. _php-query-projection: + +Query Projection +~~~~~~~~~~~~~~~~ + +By default, queries in MongoDB return all fields in matching documents. To limit +the amount of data that MongoDB sends to applications, you can include a +:manual:`projection document ` in +the query operation. + +.. note:: + + MongoDB includes the ``_id`` field by default unless you explicitly exclude + it in a projection document. + +The following example finds restaurants based on the ``cuisine`` and ``borough`` +fields and uses a :manual:`projection +` to limit the fields that are +returned. It also limits the results to 5 documents. + +.. code-block:: php + + test->restaurants; + + $cursor = $collection->find( + [ + 'cuisine' => 'Italian', + 'borough' => 'Manhattan', + ], + [ + 'projection' => [ + 'name' => 1, + 'borough' => 1, + 'cuisine' => 1, + ], + 'limit' => 4, + ] + ); + + foreach($cursor as $restaurant) { + var_dump($restaurant); + }; + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Model\BSONDocument)#10 (1) { + ["storage":"ArrayObject":private]=> + array(4) { + ["_id"]=> + object(MongoDB\BSON\ObjectId)#8 (1) { + ["oid"]=> + string(24) "576023c6b02fa9281da3f983" + } + ["borough"]=> + string(9) "Manhattan" + ["cuisine"]=> + string(7) "Italian" + ["name"]=> + string(23) "Isle Of Capri Resturant" + } + } + object(MongoDB\Model\BSONDocument)#13 (1) { + ["storage":"ArrayObject":private]=> + array(4) { + ["_id"]=> + object(MongoDB\BSON\ObjectId)#12 (1) { + ["oid"]=> + string(24) "576023c6b02fa9281da3f98d" + } + ["borough"]=> + string(9) "Manhattan" + ["cuisine"]=> + string(7) "Italian" + ["name"]=> + string(18) "Marchis Restaurant" + } + } + object(MongoDB\Model\BSONDocument)#8 (1) { + ["storage":"ArrayObject":private]=> + array(4) { + ["_id"]=> + object(MongoDB\BSON\ObjectId)#10 (1) { + ["oid"]=> + string(24) "576023c6b02fa9281da3f99b" + } + ["borough"]=> + string(9) "Manhattan" + ["cuisine"]=> + string(7) "Italian" + ["name"]=> + string(19) "Forlinis Restaurant" + } + } + object(MongoDB\Model\BSONDocument)#12 (1) { + ["storage":"ArrayObject":private]=> + array(4) { + ["_id"]=> + object(MongoDB\BSON\ObjectId)#13 (1) { + ["oid"]=> + string(24) "576023c6b02fa9281da3f9a8" + } + ["borough"]=> + string(9) "Manhattan" + ["cuisine"]=> + string(7) "Italian" + ["name"]=> + string(22) "Angelo Of Mulberry St." + } + } + +Limit, Sort, and Skip Options +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In addition to :ref:`projection criteria `, you can +specify options to limit, sort, and skip documents during queries. + +The following example uses the ``limit`` and ``sort`` options to query for the +five most populous zip codes in the United States: + +.. code-block:: php + + test->zips; + + $cursor = $collection->find( + [], + [ + 'limit' => 5, + 'sort' => ['pop' => -1], + ] + ); + + foreach ($cursor as $document) { + printf("%s: %s, %s\n", $document['_id'], $document['city'], $document['state']); + } + +The output would then resemble: + +.. code-block:: none + + 60623: CHICAGO, IL + 11226: BROOKLYN, NY + 10021: NEW YORK, NY + 10025: NEW YORK, NY + 90201: BELL GARDENS, CA + +Regular Expressions +~~~~~~~~~~~~~~~~~~~ + +Filter criteria may include regular expressions, either by using the +:php:`MongoDB\BSON\Regex ` class directory or the +:query:`$regex` operator. + +The following example lists documents in the ``zips`` collection where the city +name starts with "garden" and the state is Texas: + +.. code-block:: php + + test->zips; + + $cursor = $collection->find([ + 'city' => new MongoDB\BSON\Regex('^garden', 'i'), + 'state' => 'TX', + ]); + + foreach ($cursor as $document) { + printf("%s: %s, %s\n", $document['_id'], $document['city'], $document['state']); + } + +The output would then resemble: + +.. code-block:: none + + 78266: GARDEN RIDGE, TX + 79739: GARDEN CITY, TX + 79758: GARDENDALE, TX + +An equivalent filter could be constructed using the :query:`$regex` operator: + +.. code-block:: php + + ['$regex' => '^garden', '$options' => 'i'], + 'state' => 'TX', + ] + +.. seealso:: + + :manual:`$regex ` in the MongoDB manual + +Although MongoDB's regular expression syntax is not exactly the same as PHP's +:php:`PCRE ` syntax, :php:`preg_quote() ` +may be used to escape special characters that should be matched as-is. The +following example finds restaurants whose name starts with "(Library)": + +.. code-block:: php + + test->restaurants; + + $cursor = $collection->find([ + 'name' => new MongoDB\BSON\Regex('^' . preg_quote('(Library)')), + ]); + +.. _php-aggregation: + +Complex Queries with Aggregation +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +MongoDB's :manual:`Aggregation Framework ` allows +you to issue complex queries that filter, transform, and group collection data. +The |php-library|\'s :phpmethod:`MongoDB\Collection::aggregate()` method +returns a :php:`Traversable ` object, which you can iterate upon to +access the results of the aggregation operation. Refer to the +:phpmethod:`MongoDB\Collection::aggregate()` method's :ref:`behavior +reference ` for more about the method's output. + +The following example lists the 5 US states with the most zip codes associated +with them: + +.. code-block:: php + + test->zips; + + $cursor = $collection->aggregate([ + ['$group' => ['_id' => '$state', 'count' => ['$sum' => 1]]], + ['$sort' => ['count' => -1]], + ['$limit' => 5], + ]); + + foreach ($cursor as $state) { + printf("%s has %d zip codes\n", $state['_id'], $state['count']); + } + +The output would then resemble: + +.. code-block:: none + + TX has 1671 zip codes + NY has 1595 zip codes + CA has 1516 zip codes + PA has 1458 zip codes + IL has 1237 zip codes + +.. seealso:: + + :phpmethod:`MongoDB\Collection::aggregate()` + +Update Documents +---------------- + +Update One Document +~~~~~~~~~~~~~~~~~~~ + +Use the :phpmethod:`MongoDB\Collection::updateOne()` method to update a single +document matching a filter. :phpmethod:`MongoDB\Collection::updateOne()` +returns a :phpclass:`MongoDB\UpdateResult` object, which you can use to access +statistics about the update operation. + +Update methods have two required parameters: the query filter that identifies +the document or documents to update, and an update document that specifies what +updates to perform. The :phpmethod:`MongoDB\Collection::updateOne()` reference +describes each parameter in detail. + +The following example inserts two documents into an empty ``users`` collection +in the ``test`` database using the :phpmethod:`MongoDB\Collection::insertOne()` +method, and then updates the documents where the value for the ``state`` field +is ``"ny"`` to include a ``country`` field set to ``"us"``: + +.. code-block:: php + + test->users; + $collection->drop(); + + $collection->insertOne(['name' => 'Bob', 'state' => 'ny']); + $collection->insertOne(['name' => 'Alice', 'state' => 'ny']); + $updateResult = $collection->updateOne( + ['state' => 'ny'], + ['$set' => ['country' => 'us']] + ); + + printf("Matched %d document(s)\n", $updateResult->getMatchedCount()); + printf("Modified %d document(s)\n", $updateResult->getModifiedCount()); + +Since the update operation uses the +:phpmethod:`MongoDB\Collection::updateOne()` method, which updates the first +document to match the filter criteria, the results would then resemble: + +.. code-block:: none + + Matched 1 document(s) + Modified 1 document(s) + +It is possible for a document to match the filter but *not be modified* by an +update, as is the case where the update sets a field's value to its existing +value, as in this example: + +.. code-block:: php + + test->users; + $collection->drop(); + + $collection->insertOne(['name' => 'Bob', 'state' => 'ny']); + $updateResult = $collection->updateOne( + ['name' => 'Bob'], + ['$set' => ['state' => 'ny']] + ); + + printf("Matched %d document(s)\n", $updateResult->getMatchedCount()); + printf("Modified %d document(s)\n", $updateResult->getModifiedCount()); + +The number of matched documents and the number of *modified* documents would +therefore not be equal, and the output from the operation would resemble: + +.. code-block:: none + + Matched 1 document(s) + Modified 0 document(s) + +.. seealso:: + + - :phpmethod:`MongoDB\Collection::updateOne()` + - :phpmethod:`MongoDB\Collection::findOneAndUpdate()` + +Update Many Documents +~~~~~~~~~~~~~~~~~~~~~ + +:phpmethod:`MongoDB\Collection::updateMany()` updates one or more documents +matching the filter criteria and returns a :phpclass:`MongoDB\UpdateResult` +object, which you can use to access statistics about the update operation. + +Update methods have two required parameters: the query filter that identifies +the document or documents to update, and an update document that specifies what +updates to perform. The :phpmethod:`MongoDB\Collection::updateMany()` reference +describes each parameter in detail. + +The following example inserts three documents into an empty ``users`` collection +in the ``test`` database and then uses the :update:`$set` operator to update the +documents matching the filter criteria to include the ``country`` field with +value ``"us"``: + +.. code-block:: php + + test->users; + $collection->drop(); + + $collection->insertOne(['name' => 'Bob', 'state' => 'ny', 'country' => 'us']); + $collection->insertOne(['name' => 'Alice', 'state' => 'ny']); + $collection->insertOne(['name' => 'Sam', 'state' => 'ny']); + $updateResult = $collection->updateMany( + ['state' => 'ny'], + ['$set' => ['country' => 'us']] + ); + + printf("Matched %d document(s)\n", $updateResult->getMatchedCount()); + printf("Modified %d document(s)\n", $updateResult->getModifiedCount()); + +If an update operation results in no change to a document, such as setting the +value of the field to its current value, the number of modified documents can be +less than the number of *matched* documents. Since the update document with +``name`` of ``"Bob"`` results in no changes to the document, the output of the +operation therefore resembles: + +.. code-block:: none + + Matched 3 document(s) + Modified 2 document(s) + +.. seealso:: + + :phpmethod:`MongoDB\Collection::updateMany()` + +Replace Documents +~~~~~~~~~~~~~~~~~ + +Replacement operations are similar to update operations, but instead of updating +a document to include new fields or new field values, a replacement operation +replaces the entire document with a new document, but retains the original +document's ``_id`` value. + +The :phpmethod:`MongoDB\Collection::replaceOne()` method replaces a single +document that matches the filter criteria and returns an instance of +:phpclass:`MongoDB\UpdateResult`, which you can use to access statistics about +the replacement operation. + +:phpmethod:`MongoDB\Collection::replaceOne()` has two required parameters: the +query filter that identifies the document or documents to replace, and a +replacement document that will replace the original document in MongoDB. The +:phpmethod:`MongoDB\Collection::replaceOne()` reference describes each +parameter in detail. + +.. important:: + + Replacement operations replace all of the fields in a document except the + ``_id`` value. To avoid accidentally overwriting or deleting desired fields, + use the :phpmethod:`MongoDB\Collection::updateOne()` or + :phpmethod:`MongoDB\Collection::updateMany()` methods to update individual + fields in a document rather than replacing the entire document. + +The following example inserts one document into an empty ``users`` collection in +the ``test`` database, and then replaces that document with a new one: + +.. code-block:: php + + test->users; + $collection->drop(); + + $collection->insertOne(['name' => 'Bob', 'state' => 'ny']); + $updateResult = $collection->replaceOne( + ['name' => 'Bob'], + ['name' => 'Robert', 'state' => 'ca'] + ); + + printf("Matched %d document(s)\n", $updateResult->getMatchedCount()); + printf("Modified %d document(s)\n", $updateResult->getModifiedCount()); + +The output would then resemble: + +.. code-block:: none + + Matched 1 document(s) + Modified 1 document(s) + +.. seealso:: + + - :phpmethod:`MongoDB\Collection::replaceOne()` + - :phpmethod:`MongoDB\Collection::findOneAndReplace()` + +Upsert +~~~~~~ + +Update and replace operations support an :manual:`upsert +` option. When ``upsert`` is ``true`` +*and* no documents match the specified filter, the operation creates a new +document and inserts it. If there *are* matching documents, then the operation +modifies or replaces the matching document or documents. + +When a document is upserted, the ID is accessible via +:phpmethod:`MongoDB\UpdateResult::getUpsertedId()`. + +The following example uses :phpmethod:`MongoDB\Collection::updateOne()` with +the ``upsert`` option set to ``true`` and an empty ``users`` collection in the +``test`` database, therefore inserting the document into the database: + +.. code-block:: php + + test->users; + $collection->drop(); + + $updateResult = $collection->updateOne( + ['name' => 'Bob'], + ['$set' => ['state' => 'ny']], + ['upsert' => true] + ); + + printf("Matched %d document(s)\n", $updateResult->getMatchedCount()); + printf("Modified %d document(s)\n", $updateResult->getModifiedCount()); + printf("Upserted %d document(s)\n", $updateResult->getUpsertedCount()); + + $upsertedDocument = $collection->findOne([ + '_id' => $updateResult->getUpsertedId(), + ]); + + var_dump($upsertedDocument); + +The output would then resemble: + +.. code-block:: none + + Matched 0 document(s) + Modified 0 document(s) + Upserted 1 document(s) + object(MongoDB\Model\BSONDocument)#16 (1) { + ["storage":"ArrayObject":private]=> + array(3) { + ["_id"]=> + object(MongoDB\BSON\ObjectId)#15 (1) { + ["oid"]=> + string(24) "57509c4406d7241dad86e7c3" + } + ["name"]=> + string(3) "Bob" + ["state"]=> + string(2) "ny" + } + } + +Delete Documents +---------------- + +Delete One Document +~~~~~~~~~~~~~~~~~~~ + +The :phpmethod:`MongoDB\Collection::deleteOne()` method deletes a single +document that matches the filter criteria and returns a +:phpclass:`MongoDB\DeleteResult`, which you can use to access statistics about +the delete operation. + +If multiple documents match the filter criteria, +:phpmethod:`MongoDB\Collection::deleteOne()` deletes the :term:`first +` matching document. + +:phpmethod:`MongoDB\Collection::deleteOne()` has one required parameter: a +query filter that specifies the document to delete. Refer to the +:phpmethod:`MongoDB\Collection::deleteOne()` reference for full method +documentation. + +The following operation deletes the first document where the ``state`` field's +value is ``"ny"``: + +.. code-block:: php + + test->users; + $collection->drop(); + + $collection->insertOne(['name' => 'Bob', 'state' => 'ny']); + $collection->insertOne(['name' => 'Alice', 'state' => 'ny']); + $deleteResult = $collection->deleteOne(['state' => 'ny']); + + printf("Deleted %d document(s)\n", $deleteResult->getDeletedCount()); + +The output would then resemble: + +.. code-block:: none + + Deleted 1 document(s) + +.. seealso:: + + :phpmethod:`MongoDB\Collection::deleteOne()` + +Delete Many Documents +~~~~~~~~~~~~~~~~~~~~~ + +:phpmethod:`MongoDB\Collection::deleteMany()` deletes all of the documents that +match the filter criteria and returns a :phpclass:`MongoDB\DeleteResult`, which +you can use to access statistics about the delete operation. + +:phpmethod:`MongoDB\Collection::deleteMany()` has one required parameter: a +query filter that specifies the document to delete. Refer to the +:phpmethod:`MongoDB\Collection::deleteMany()` reference for full method +documentation. + +The following operation deletes all of the documents where the ``state`` field's +value is ``"ny"``: + +.. code-block:: php + + test->users; + $collection->drop(); + + $collection->insertOne(['name' => 'Bob', 'state' => 'ny']); + $collection->insertOne(['name' => 'Alice', 'state' => 'ny']); + $deleteResult = $collection->deleteMany(['state' => 'ny']); + + printf("Deleted %d document(s)\n", $deleteResult->getDeletedCount()); + +The output would then resemble: + +.. code-block:: none + + Deleted 2 document(s) + +.. seealso:: + + :phpmethod:`MongoDB\Collection::deleteMany()` diff --git a/source/tutorial/custom-types.txt b/source/tutorial/custom-types.txt new file mode 100644 index 00000000..f3736675 --- /dev/null +++ b/source/tutorial/custom-types.txt @@ -0,0 +1,195 @@ +================= +Custom Data-Types +================= + +.. default-domain:: mongodb + +.. note:: + + This tutorial explains implementing custom data types using the :php:`MongoDB\BSON\Persistable ` + interface found in the MongoDB extension. Consider using a codec instead to decouple the MongoDB persistence logic + from your business logic. See the :ref:`codec tutorial ` for an example. + +The MongoDB PHP extension and library support custom classes while +serializing and deserializing. An example of where this might be useful is +if you want to store date/time information retaining the time zone +information that PHP's :php:`DateTimeImmutable ` +class stores with a point in time. + +The extension serializes PHP variables, including objects, into BSON when it +communicates to the server, and deserializes BSON back into PHP variables when +it receives data from the server. + +It is possible to influence the behavior by implementing the +:php:`MongoDB\BSON\Persistable ` interface. +If a class implements this interface, then upon serialization the +:php:`bsonSerialize ` method is +called. This method is responsible for returning an array or stdClass object +to convert to BSON and store in the database. That data will later be used to +reconstruct the object upon reading from the database. + +As an example we present the ``LocalDateTime`` class. This class wraps around +the :php:`MongoDB\BSON\UTCDateTime ` data +type and a time zone. + +.. code-block:: php + + utc = new \MongoDB\BSON\UTCDateTime($milliseconds); + if ($timezone === null) { + $timezone = new \DateTimeZone(date_default_timezone_get()); + } + $this->tz = $timezone; + } + ?> + +As it implements the :php:`MongoDB\BSON\Persistable +` interface, the +class is required to implement the :php:`bsonSerialize +` and :php:`bsonUnserialize +` methods. In the +:php:`bsonSerialize ` method, we +return an array with the two values that we need to persist: the point in time +in milliseconds since the Epoch, represented by a +:php:`MongoDB\BSON\UTCDateTime ` object, and +a string containing the Olson time zone identifier: + +.. code-block:: php + + $this->utc, + 'tz' => $this->tz->getName(), + ]; + } + ?> + +The extension will additionally add a ``__pclass`` field to the document, and +store that in the database, too. This field contains the PHP class name so that +upon deserialization the extension knows which class to use for recreating the +stored object. + +When the document is read from the database, the extension detects whether a +``__pclass`` field is present and then executes +:php:`MongoDB\BSON\Persistable::bsonUnserialize +` method which is +responsible for restoring the object's original state. + +In the code below, we make sure that the data in the ``utc`` and ``tz`` fields +are of the right time, and then assign their values to the two private +properties. + +.. code-block:: php + + utc = $data['utc']; + $this->tz = new \DateTimeZone($data['tz']); + } + ?> + +You may have noticed that the class also implements the +:php:`MongoDB\BSON\UTCDateTimeInterface +` interface. This interface defines +the two non-constructor methods of the :php:`MongoDB\BSON\UTCDateTime +` class. + +It is recommended that wrappers around existing BSON classes implement their +respective interface (i.e. :php:`MongoDB\BSON\UTCDateTimeInterface +`) so that the wrapper objects can be +used in the same context as their original unwrapped version. It is also +recommended that you always type-hint against the interface (i.e. +:php:`MongoDB\BSON\UTCDateTimeInterface +`) and never against the concrete +class (i.e. :php:`MongoDB\BSON\UTCDateTime +`), as this would prevent wrapped objects from +being accepted into methods. + +In our new ``toDateTime`` method we return a :php:`DateTime ` +object with the local time zone set, instead of the UTC time zone that +:php:`MongoDB\BSON\UTCDateTime ` normally uses +in its return value. + +.. code-block:: php + + utc->toDateTime()->setTimezone($this->tz); + } + + public function __toString() + { + return (string) $this->utc; + } + } + ?> + +With the class defined, we can now use it in our documents. The snippet below +demonstrates the round tripping from the ``LocalDateTime`` object to BSON, and +back to ``LocalDateTime``. + +.. code-block:: php + + new LocalDateTime]); + $document = MongoDB\BSON\toPHP($bson); + + var_dump($document); + var_dump($document->date->toDateTime()); + ?> + +Which outputs: + +.. code-block:: none + + object(stdClass)#1 (1) { + ["date"]=> + object(LocalDateTime)#2 (2) { + ["utc":"LocalDateTime":private]=> + object(MongoDB\BSON\UTCDateTime)#3 (1) { + ["milliseconds"]=> + string(13) "1533042443716" + } + ["tz":"LocalDateTime":private]=> + object(DateTimeZone)#4 (2) { + ["timezone_type"]=> + int(3) + ["timezone"]=> + string(13) "Europe/London" + } + } + } + object(DateTime)#5 (3) { + ["date"]=> + string(26) "2018-07-31 14:07:23.716000" + ["timezone_type"]=> + int(3) + ["timezone"]=> + string(13) "Europe/London" + } + +Storing the Olson time zone identifier in a separate field also works well +with MongoDB's :manual:`Aggregation Framework `, which allows +date manipulation, :manual:`formatting +`, and querying depending on a +specific time zone. diff --git a/source/tutorial/decimal128.txt b/source/tutorial/decimal128.txt new file mode 100644 index 00000000..2397ccd8 --- /dev/null +++ b/source/tutorial/decimal128.txt @@ -0,0 +1,129 @@ +========== +Decimal128 +========== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +Overview +-------- + +MongoDB 3.4 introduced support for a Decimal128 BSON type, +which is a 128-bit decimal-based +floating-point value capable of emulating decimal rounding with exact precision. +This functionality is intended for applications that handle :manual:`monetary +data `, such as financial and tax computations. + +The :php:`MongoDB\BSON\Decimal128 ` class may be used +to work with this type in PHP. + +Working with Decimal128 Values +------------------------------ + +Inserting a Decimal128 +~~~~~~~~~~~~~~~~~~~~~~ + +The following example inserts a value of type ``Decimal128`` into the ``price`` +field of a collection named ``inventory``: + +.. code-block:: php + + test->inventory; + + $collection->insertOne([ + '_id' => 1, + 'item' => '26-inch monitor', + 'price' => new MongoDB\BSON\Decimal128('428.79'), + ]); + + $item = $collection->findOne(['_id' => 1]); + + var_dump($item); + +The output would then resemble: + +.. code-block:: none + + object(MongoDB\Model\BSONDocument)#9 (1) { + ["storage":"ArrayObject":private]=> + array(3) { + ["_id"]=> + int(1) + ["item"]=> + string(15) "26-inch monitor" + ["price"]=> + object(MongoDB\BSON\Decimal128)#13 (1) { + ["dec"]=> + string(6) "428.79" + } + } + } + +Mathematical Operations with BCMath +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The :php:`extension ` does not provide any functionality for working +with ``Decimal128`` values; however, the string representation of a +:php:`MongoDB\BSON\Decimal128 ` object may be used +with PHP's :php:`BCMath ` extension. + +The following example adds two ``Decimal128`` values and creates a new +``Decimal128`` value with the result from :php:`bcadd() `: + +.. code-block:: php + + + string(1) "6" + } + +This does not match the expected result of "6.912". Each operation in the BCMath +API uses a scale to determine the number of decimal digits in the result. The +default scale is zero, which is why the above example produces a result with no +decimal precision. + +In the following example, we use a scale of three for :php:`bcadd() ` to +obtain the expected result: + +.. code-block:: php + + + string(5) "6.912" + } + +In lieu of specifying a scale for each operation, a default scale may be set via +:php:`bcscale() ` or the :php:`bcmath.scale INI setting +`. The ``Decimal128`` type +supports up to 34 decimal digits (i.e. significant digits). diff --git a/source/tutorial/encryption.txt b/source/tutorial/encryption.txt new file mode 100644 index 00000000..adf4cc41 --- /dev/null +++ b/source/tutorial/encryption.txt @@ -0,0 +1,274 @@ +================= +In-Use Encryption +================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 3 + :class: singlecol + + +Dependencies +------------ + +To get started using in-use encryption in your project, the +:php:`extension ` will need to be compiled with +`libmongocrypt `_ (enabled by +default). + +Additionally, either ``crypt_shared`` or ``mongocryptd`` are required in order to +use *automatic* client-side encryption. Neither is required for *explicit* +encryption. + + +``crypt_shared`` +~~~~~~~~~~~~~~~~ + +The :manual:`Automatic Encryption Shared Library ` +(``crypt_shared``) provides the same functionality as ``mongocryptd``, but does not +require you to spawn another process to perform automatic encryption. + +By default, the extension attempts to load ``crypt_shared`` from the system +path(s) and uses it automatically if found. To load ``crypt_shared`` from +another location, use the ``cryptSharedLibPath`` auto encryption +:php:`driver option ` +when constructing a client. If the extension cannot load ``crypt_shared`` it +will attempt to fallback to using ``mongocryptd`` by default. The +``cryptSharedLibRequired`` option may be used to always require ``crypt_shared`` +and fail if it cannot be loaded. + +For detailed installation instructions see the MongoDB documentation for the +:manual:`Automatic Encryption Shared Library `. + + +``mongocryptd`` +~~~~~~~~~~~~~~~ + +The ``mongocryptd`` binary is an alternative requirement for automatic client-side +encryption and is included as a component in the +:manual:`MongoDB Enterprise Server package `. +For detailed installation instructions see the +:manual:`MongoDB documentation on mongocryptd `. + +``mongocryptd`` performs the following: + +- Parses the automatic encryption rules specified in the client configuration. + If the ``schemaMap`` auto encryption driver option contains invalid syntax, + ``mongocryptd`` returns an error. + +- Uses the specified automatic encryption rules to mark fields in read and write + operations for encryption. + +- Rejects read/write operations that may return unexpected or incorrect results + when applied to an encrypted field. For supported and unsupported operations, + see :manual:`Supported Operations for Automatic Encryption `. + +A client configured with auto encryption will automatically spawn the +``mongocryptd`` process from the application's ``PATH``. Applications can control +the spawning behavior via various auto encryption +:php:`driver options `. + +``mongocryptd`` is only responsible for supporting automatic client-side encryption +and does not itself perform any encryption or decryption. + + +Managing Encryption Keys +------------------------ + +.. seealso:: :manual:`Encryption Key Management ` in the MongoDB manual + +Creating an Encryption Key +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. note:: + + The following examples use a local master key. While this is suitable for + development, a production application should use a supported cloud provider + (e.g. AWS KMS). The master key is used to encrypt locally stored data keys + and thus it is very important that you keep this key secure. + +To create an encryption key, create a +:php:`MongoDB\Driver\ClientEncryption ` +instance with encryption options and use the +:php:`createDataKey() ` +method. The method will return the key ID which can be used to reference the key +later. You can also pass multiple :ref:`alternate names ` for this key +and reference the key by these names instead of the key ID. + +Creating a new data encryption key would typically be done on initial +deployment, but depending on your use case you may want to use more than one +encryption key (e.g. user-specific encryption keys) or create them dynamically. + +.. literalinclude:: /examples/encryption/create_data_key.php + :language: php + + +.. _alt_name: + +Referencing Encryption Keys by an Alternative Name +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To reference keys in your application, you can use the ``keyAltName`` +attribute specified when creating the key. The following example creates an +encryption key with an alternative name, which could be done when deploying the +application. The script then encrypts data by referencing the key by its +alternative name using the ``keyAltName`` option instead of ``keyId``. + +.. note:: + + Prior to adding a new key alternate name, you must create a partial, unique + index on the ``keyAltNames`` field. Client-Side Field Level Encryption + depends on server-enforced uniqueness of key alternate names. + +.. literalinclude:: /examples/encryption/key_alt_name.php + :language: php + + +Client-Side Field Level Encryption +---------------------------------- + +Introduced in MongoDB 4.2, +:manual:`Client-Side Field Level Encryption ` allows an +application to encrypt specific data fields in addition to pre-existing MongoDB +encryption features such as +:manual:`Encryption at Rest ` and +:manual:`TLS/SSL (Transport Encryption) `. + +With field level encryption, applications can encrypt fields in documents prior +to transmitting data over the wire to the server. Client-side field level +encryption supports workloads where applications must guarantee that +unauthorized parties, including server administrators, cannot read the encrypted +data. + + +Automatic Client-Side Field Level Encryption +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. note:: + + Automatic client-side field level encryption requires MongoDB 4.2+ Enterprise + or a MongoDB 4.2+ Atlas cluster. + +Automatic client-side field level encryption is enabled by creating a client and +specifying the ``autoEncryption`` +:php:`driver option `. +The following examples demonstrate how to setup automatic client-side field +level encryption and use a +:php:`MongoDB\Driver\ClientEncryption ` +object to create a new encryption key. + + +.. _server-side: + +Server-Side Field Level Encryption Enforcement +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The MongoDB 4.2+ server supports using schema validation to enforce encryption +of specific fields in a collection. This schema validation will prevent an +application from inserting unencrypted values for any fields marked with the +:manual:`"encrypt" schema keyword `. + +The following example sets up a collection with automatic encryption using a +``$jsonSchema`` validator and +:manual:`Encryption Schema syntax `. +Data in the ``encryptedField`` field is automatically encrypted on insertion and +decrypted when reading on the client side. + +.. literalinclude:: /examples/encryption/csfle-automatic_encryption-server_side_schema.php + :language: php + + +Providing Local Automatic Encryption Rules +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The following example uses the ``schemaMap`` auto encryption driver option to +define encrypted fields using a +:manual:`strict subset of the JSON schema syntax `. + +Using ``schemaMap`` in conjunction with a :ref:`server-side schema ` +provides more security than relying entirely on a schema obtained from the +server. It protects against a malicious server advertising a false schema, which +could trick the client into sending unencrypted data that should be encrypted. + +.. note:: + + Only :manual:`Encryption Schema syntax ` + can be used with the ``schemaMap`` option. Do not specify document validation + keywords in the automatic encryption rules. To define document validation + rules, configure :manual:`schema validation `. + +.. literalinclude:: /examples/encryption/csfle-automatic_encryption-local_schema.php + :language: php + + +Explicit Encryption +~~~~~~~~~~~~~~~~~~~ + +Explicit encryption is a MongoDB community feature and does not use +``crypt_shared`` or ``mongocryptd``. Explicit encryption is provided by the +:php:`MongoDB\Driver\ClientEncryption ` class. + +.. literalinclude:: /examples/encryption/csfle-explicit_encryption.php + :language: php + + +Explicit Encryption with Automatic Decryption +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Although automatic encryption requires MongoDB 4.2+ enterprise or a MongoDB 4.2+ +Atlas cluster, automatic *decryption* is supported for all users. To configure +automatic decryption without automatic encryption set the +``bypassAutoEncryption`` auto encryption +:php:`driver option ` +when constructing a client. + +.. literalinclude:: /examples/encryption/csfle-explicit_encryption_automatic_decryption.php + :language: php + + +Queryable Encryption +-------------------- + +Introduced in MongoDB 7.0, +:manual:`Queryable Encryption ` is another +form of in-use encryption. Data is encrypted client-side. Queryable Encryption +supports indexed encrypted fields, which are further processed server-side. + + +Automatic Queryable Encryption +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. note:: + + Automatic queryable encryption requires MongoDB 7.0+ Enterprise or a MongoDB + 7.0+ Atlas cluster. + +Automatic encryption in Queryable Encryption utilizes ``crypt_shared`` or +``mongocryptd`` to automatically encrypt and decrypt data client-side. The data +in the ``encryptedIndexed`` and ``encryptedUnindexed`` fields will be +automatically encrypted on insertion and decrypted when querying on the client +side. Additionally, it is possible to query on the ``encryptedIndexed`` field. + +.. literalinclude:: /examples/encryption/queryable_encryption-automatic.php + :language: php + + +Explicit Queryable Encryption +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. note:: + + Explicit queryable encryption requires MongoDB 7.0+. + +Explicit encryption in Queryable Encryption is performed using the +:php:`MongoDB\Driver\ClientEncryption::encrypt() ` +and :php:`decrypt() ` methods. Although +values must be explicitly encrypted (e.g. insertions, query criteria), automatic +*decryption* for queries is possible by configuring ``encryptedFields`` on the +collection, as demonstrated in the following example: + +.. literalinclude:: /examples/encryption/queryable_encryption-explicit.php + :language: php diff --git a/source/tutorial/example-data.txt b/source/tutorial/example-data.txt new file mode 100644 index 00000000..d0b748cc --- /dev/null +++ b/source/tutorial/example-data.txt @@ -0,0 +1,47 @@ +============ +Example Data +============ + +.. default-domain:: mongodb + +Some examples in this documentation use example data fixtures from +`zips.json `_ and +`primer-dataset.json `_. + +Importing the dataset into MongoDB can be done in several ways. The following +example imports the ``zips.json`` file into a ``test.zips`` collection using the +:php:`extension ` directly: + +.. code-block:: php + + insert($document); + } + + $manager = new MongoDB\Driver\Manager('mongodb://127.0.0.1/'); + + $result = $manager->executeBulkWrite('test.zips', $bulk); + printf("Inserted %d documents\n", $result->getInsertedCount()); + +The output would then resemble: + +.. code-block:: none + + Inserted 29353 documents + +You may also import the datasets using :manual:`mongoimport +`, which is included with MongoDB: + +.. code-block:: sh + + mongoimport --db test --collection zips --file zips.json --drop + mongoimport --db test --collection restaurants --file primer-dataset.json --drop diff --git a/source/tutorial/gridfs.txt b/source/tutorial/gridfs.txt new file mode 100644 index 00000000..dc6afa15 --- /dev/null +++ b/source/tutorial/gridfs.txt @@ -0,0 +1,214 @@ +====== +GridFS +====== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +:manual:`GridFS ` is a specification for storing and retrieving +files in MongoDB. GridFS uses two collections to store files. One collection +stores the file chunks (e.g. ``fs.chunks``), and the other stores file metadata +(e.g. ``fs.files``). The :phpclass:`MongoDB\GridFS\Bucket` class provides an +interface around these collections for working with the files as PHP +:php:`Streams `. + +Creating a GridFS Bucket +------------------------ + +You can construct a GridFS bucket using the PHP extension's +:php:`MongoDB\Driver\Manager ` class, or select +a bucket from the |php-library|'s :phpclass:`MongoDB\Database` class via the +:phpmethod:`selectGridFSBucket() ` +method. + +The bucket can be constructed with various options: + +- ``bucketName`` determines the prefix for the bucket's metadata and chunk + collections. The default value is ``"fs"``. +- ``chunkSizeBytes`` determines the size of each chunk. GridFS divides the file + into chunks of this length, except for the last, which is only as large as + needed. The default size is ``261120`` (i.e. 255 KiB). +- ``readConcern``, ``readPreference`` and ``writeConcern`` options can be used + to specify defaults for read and write operations, much like the + :phpclass:`MongoDB\Collection` options. + +Uploading Files with Writable Streams +------------------------------------- + +To upload a file to GridFS using a writable stream, you can either open a stream +and write to it directly or write the entire contents of another readable stream +to GridFS all at once. + +To open an upload stream and write to it: + +.. code-block:: php + + test->selectGridFSBucket(); + + $stream = $bucket->openUploadStream('my-file.txt'); + + $contents = file_get_contents('/path/to/my-file.txt'); + fwrite($stream, $contents); + fclose($stream); + +To upload the entire contents of a readable stream in one call: + +.. code-block:: php + + test->selectGridFSBucket(); + + $file = fopen('/path/to/my-file.txt', 'rb'); + $bucket->uploadFromStream('my-file.txt', $file); + +Downloading Files with Readable Streams +--------------------------------------- + +To download a file from GridFS using a readable stream, you can either open a +stream and read from it directly or download the entire file all at once. + +To open a download stream and read from it: + +.. code-block:: php + + test->selectGridFSBucket(); + + $stream = $bucket->openDownloadStream($fileId); + $contents = stream_get_contents($stream); + +To download the file all at once and write it to a writable stream: + +.. code-block:: php + + test->selectGridFSBucket(); + + $file = fopen('/path/to/my-output-file.txt', 'wb'); + + $bucket->downloadToStream($fileId, $file); + +Selecting Files by Filename and Revision +---------------------------------------- + +You can also download a file specified by filename and (optionally) revision +number. Revision numbers are used to distinguish between files sharing the same +``filename`` metadata field, ordered by date of upload (i.e. the ``uploadDate`` +metadata field). The ``revision`` option accepted by +:phpmethod:`openDownloadStreamByName() +` and +:phpmethod:`downloadToStreamByName() +` can be positive or negative. + +A positive ``revision`` number may be used to select files in order of the +oldest upload date. A revision of ``0`` would denote the file with the oldest +upload date, a revision of ``1`` would denote the second oldest upload, and so +on. + +A negative revision may be used to select files in order of the most recent +upload date. A revision of ``-1`` would denote a file with the most recent +upload date, a revision of ``-2`` would denote the second most recent upload, +and so on. The ``revision`` option defaults to ``-1`` if not specified. + +The following example downloads the contents of the oldest version of a +particular file: + +.. code-block:: php + + test->selectGridFSBucket(); + + $stream = $bucket->openDownloadStreamByName('my-file.txt', ['revision' => 0]); + $contents = stream_get_contents($stream); + +Deleting Files +-------------- + +You can delete a GridFS file by its ``_id``. + +.. code-block:: php + + test->selectGridFSBucket(); + + $bucket->delete($fileId); + +Finding File Metadata +--------------------- + +The :phpmethod:`find() ` method allows you to +retrieve documents from the GridFS files collection, which contain metadata +about the GridFS files. + +.. code-block:: php + + test->selectGridFSBucket(); + + $cursor = $bucket->find(['filename' => 'my-file.txt']); + +Accessing File Metadata for an Existing Stream +---------------------------------------------- + +The :phpmethod:`getFileDocumentForStream() +` method may be used to get +the file document for an existing readable or writable GridFS stream. + +.. code-block:: php + + test->selectGridFSBucket(); + + $stream = $bucket->openDownloadStream($fileId); + $metadata = $bucket->getFileDocumentForStream($stream); + +.. note:: + + Since the file document for a writable stream is not committed to MongoDB + until the stream is closed, + :phpmethod:`getFileDocumentForStream() + ` can only return an + in-memory document, which will be missing some fields (e.g. ``length``, + ``md5``). + +The :phpmethod:`getFileIdForStream() +` method may be used to get the +``_id`` for an existing readable or writable GridFS stream. This is a +convenience for accessing the ``_id`` property of the object returned by +:phpmethod:`getFileDocumentForStream() +`. + +.. code-block:: php + + test->selectGridFSBucket(); + + $stream = $bucket->openDownloadStreamByName('my-file.txt'); + $fileId = $bucket->getFileIdForStream($stream); diff --git a/source/tutorial/indexes.txt b/source/tutorial/indexes.txt new file mode 100644 index 00000000..51d2d3f7 --- /dev/null +++ b/source/tutorial/indexes.txt @@ -0,0 +1,139 @@ +======= +Indexes +======= + +.. default-domain:: mongodb + +Indexes support the efficient execution of queries in MongoDB. Without indexes, +MongoDB must perform a *collection scan*, i.e. scan every document in a +collection, to select those documents that match the query statement. If an +appropriate index exists for a query, MongoDB can use the index to limit the +number of documents it must inspect. + +The PHP driver supports managing indexes through the +:phpclass:`MongoDB\Collection` class, which implements MongoDB's +cross-driver `Index Management +`_ +and `Enumerating Indexes +`_ +specifications. + +This document provides an introduction to creating, listing, and dropping +indexes using the |php-library|. The MongoDB Manual's :manual:`Indexes +` reference provides more thorough information about indexing in +MongoDB. + +Create Indexes +-------------- + +Create indexes with the :phpmethod:`MongoDB\Collection::createIndex()` or +:phpmethod:`MongoDB\Collection::createIndexes()` methods. Refer to the method +reference for more details about each method. + +The following example creates an ascending index on the ``state`` field using +the :phpmethod:`createIndex() ` method: + +.. code-block:: php + + test->zips; + + $result = $collection->createIndex(['state' => 1]); + + var_dump($result); + +When you create an index, the method returns its name, which is automatically +generated from its specification. The above example would output something +similar to: + +.. code-block:: none + + string(7) "state_1" + +List Indexes +------------ + +The :phpmethod:`MongoDB\Collection::listIndexes()` method provides information +about the indexes in a collection. The +:phpmethod:`MongoDB\Collection::listIndexes()` method returns an iterator of +:phpclass:`MongoDB\Model\IndexInfo` objects, which you can use to view +information about each index. Refer to the method reference for more details. + +The following example lists all indexes in the ``zips`` collection in the +``test`` database: + +.. code-block:: php + + test->zips; + + foreach ($collection->listIndexes() as $indexInfo) { + var_dump($indexInfo); + } + +The output would resemble: + +.. code-block:: none + + object(MongoDB\Model\IndexInfo)#10 (4) { + ["v"]=> + int(1) + ["key"]=> + array(1) { + ["_id"]=> + int(1) + } + ["name"]=> + string(4) "_id_" + ["ns"]=> + string(9) "test.zips" + } + object(MongoDB\Model\IndexInfo)#13 (4) { + ["v"]=> + int(1) + ["key"]=> + array(1) { + ["state"]=> + int(1) + } + ["name"]=> + string(7) "state_1" + ["ns"]=> + string(9) "test.zips" + } + +Drop Indexes +------------ + +The :phpmethod:`MongoDB\Collection::dropIndex()` method lets you drop a single +index while :phpmethod:`MongoDB\Collection::dropIndexes()` drops all of the +indexes on a collection. Refer to the method reference for more details about +each method. + +The following example drops a single index by its name, ``state_1``: + +.. code-block:: php + + test->zips; + + $result = $collection->dropIndex('state_1'); + + var_dump($result); + +The operation's output would resemble: + +.. code-block:: none + + object(MongoDB\Model\BSONDocument)#11 (1) { + ["storage":"ArrayObject":private]=> + array(2) { + ["nIndexesWas"]=> + int(2) + ["ok"]=> + float(1) + } + } diff --git a/source/tutorial/install-php-library.txt b/source/tutorial/install-php-library.txt new file mode 100644 index 00000000..913a945e --- /dev/null +++ b/source/tutorial/install-php-library.txt @@ -0,0 +1,99 @@ +========================= +Install the |php-library| +========================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +The |php-library| is a high-level abstraction for the +:php:`mongodb extension `. This page will briefly explain how to +install both the ``mongodb`` extension and the |php-library|. + +Installing the Extension +------------------------ + +Linux, Unix, and macOS users can either +:php:`install the extension with PECL ` +(recommended) or +:php:`manually compile from source `. +The following command may be used to install the extension with PECL: + +.. code-block:: sh + + sudo pecl install mongodb + +.. note:: + + If the build process for either installation method fails to find a TLS + library, check that the development packages (e.g. ``libssl-dev``) and + `pkg-config `_ are both installed. + +Once the extension is installed, add the following line to your ``php.ini`` +file: + +.. code-block:: ini + + extension=mongodb.so + +Windows users can download precompiled binaries of the extension from its +`GitHub releases `__. +After downloading the appropriate archive for your PHP environment, extract the +``php_mongodb.dll`` file to PHP's extension directory and add the following line +to your ``php.ini`` file: + +.. code-block:: ini + + extension=php_mongodb.dll + +See :php:`Installing the MongoDB PHP Driver on Windows ` +for additional information. + +Installing the Library +---------------------- + +Using Composer +~~~~~~~~~~~~~~ + +The preferred method of installing the |php-library| is with +`Composer `_ by running the following command from +your project root: + +.. code-block:: sh + + composer require mongodb/mongodb + +Once you have installed the library, ensure that your application includes +Composer's autoloader as in the following example: + +.. code-block:: php + + `_ for more +information about setting up autoloading. + +Manual Installation Without Composer +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +While not recommended, you may also manually install the library using a source +archive attached to the +`GitHub releases `__. +When installing the library without Composer, you must ensure that all library +classes *and* functions are loaded for your application: + +#. If you are using a `PSR-4 `_ autoloader, + map the top-level ``MongoDB\`` namespace to the ``src/`` directory. If you + are not using an autoloader, manually require _all_ class files found + recursively within the ``src/`` directory. + +#. Regardless of whether you are using an autoloader, manually require the + ``src/functions.php`` file. This is necessary because PHP does not support + autoloading for functions. diff --git a/source/tutorial/modeling-bson-data.txt b/source/tutorial/modeling-bson-data.txt new file mode 100644 index 00000000..5429b031 --- /dev/null +++ b/source/tutorial/modeling-bson-data.txt @@ -0,0 +1,217 @@ +================== +Modeling BSON Data +================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. _php-type-map: + +Type Maps +--------- + +Most methods that read data from MongoDB support a ``typeMap`` option, which +allows control over how BSON is converted to PHP. Additionally, +the :phpclass:`MongoDB\Client`, :phpclass:`MongoDB\Database`, and +:phpclass:`MongoDB\Collection` classes accept a ``typeMap`` option, which can +be used to specify a default type map to apply to any supporting methods and +selected classes (e.g. :phpmethod:`MongoDB\Client::selectDatabase()`). + +The :phpclass:`MongoDB\Client`, :phpclass:`MongoDB\Database`, and +:phpclass:`MongoDB\Collection` classes use the following type map by +default: + +.. code-block:: php + + [ + 'array' => 'MongoDB\Model\BSONArray', + 'document' => 'MongoDB\Model\BSONDocument', + 'root' => 'MongoDB\Model\BSONDocument', + ] + +The type map above will convert BSON documents and arrays to +:phpclass:`MongoDB\Model\BSONDocument` and +:phpclass:`MongoDB\Model\BSONArray` objects, respectively. The ``root`` and +``document`` keys are used to distinguish the top-level BSON document from +embedded documents, respectively. + +A type map may specify any class that implements +:php:`MongoDB\BSON\Unserializable ` as well as +``"array"``, ``"stdClass``", and ``"object"`` (``"stdClass``" and ``"object"`` +are aliases of one another). + +.. seealso:: + + :php:`Deserialization from BSON ` in the PHP manual + + +Persistable Classes +------------------- + +The extension's :php:`persistence specification ` outlines +how classes implementing its :php:`MongoDB\BSON\Persistable +` interface are serialized to and deserialized from +BSON. The :php:`Persistable ` interface is analogous +to PHP's :php:`Serializable interface `. + +The extension automatically handles serialization and deserialization for +classes implementing the :php:`Persistable ` interface +without requiring the use of the ``typeMap`` option. This is done by encoding +the name of the PHP class in a special property within the BSON document. + +.. note:: + + When deserializing a PHP variable from BSON, the encoded class name of a + :php:`Persistable ` object will override any class + specified in the type map, but it will not override ``"array"`` and + ``"stdClass"`` or ``"object"``. This is discussed in the + :php:`persistence specification ` but it bears + repeating. + +Consider the following class definition: + +.. code-block:: php + + id = new MongoDB\BSON\ObjectId; + $this->name = $name; + $this->createdAt = new MongoDB\BSON\UTCDateTime; + } + + function bsonSerialize() + { + return [ + '_id' => $this->id, + 'name' => $this->name, + 'createdAt' => $this->createdAt, + ]; + } + + function bsonUnserialize(array $data) + { + $this->id = $data['_id']; + $this->name = $data['name']; + $this->createdAt = $data['createdAt']; + } + } + +The following example constructs a ``Person`` object, inserts it into the +database, and reads it back as an object of the same type: + +.. code-block:: php + + test->persons; + + $result = $collection->insertOne(new Person('Bob')); + + $person = $collection->findOne(['_id' => $result->getInsertedId()]); + + var_dump($person); + +The output would then resemble: + +.. code-block:: none + + object(Person)#18 (3) { + ["id":"Person":private]=> + object(MongoDB\BSON\ObjectId)#15 (1) { + ["oid"]=> + string(24) "56fad2c36118fd2e9820cfc1" + } + ["name":"Person":private]=> + string(3) "Bob" + ["createdAt":"Person":private]=> + object(MongoDB\BSON\UTCDateTime)#17 (1) { + ["milliseconds"]=> + int(1459278531218) + } + } + +The same document in the MongoDB shell might display as: + +.. code-block:: js + + { + "_id" : ObjectId("56fad2c36118fd2e9820cfc1"), + "__pclass" : BinData(128,"UGVyc29u"), + "name" : "Bob", + "createdAt" : ISODate("2016-03-29T19:08:51.218Z") + } + +.. note:: + + :php:`MongoDB\BSON\Persistable ` may only be used + for root and embedded BSON documents. It may not be used for BSON arrays. + +Working with Enums +------------------ + +:php:`Backed enums ` can be used with BSON and will +serialize as their case value (i.e. integer or string). +:php:`Pure enums `, which have no backed cases, cannot be +directly serialized. This is similar to how enums are handled by +:php:`json_encode() `. + +Round-tripping a backed enum through BSON requires special handling. In the +following example, the ``bsonUnserialize()`` method in the class containing the +enum is responsible for converting the value back to an enum case: + +.. code-block:: php + + $this->_id, + 'username' => $this->username, + 'role' => $this->role, + ]; + } + + public function bsonUnserialize(array $data): void + { + $this->_id = $data['_id']; + $this->username = $data['username']; + $this->role = Role::from($data['role']); + } + } + +Enums are prohibited from implementing +:php:`MongoDB\BSON\Unserializable ` and +:php:`MongoDB\BSON\Persistable `, since enum cases +have no state and cannot be instantiated like ordinary objects. Pure and backed +enums can, however, implement +:php:`MongoDB\BSON\Serializable `, which can be +used to overcome the default behavior whereby backed enums are serialized as +their case value and pure enums cannot be serialized. diff --git a/source/tutorial/server-selection.txt b/source/tutorial/server-selection.txt new file mode 100644 index 00000000..c63ca5c9 --- /dev/null +++ b/source/tutorial/server-selection.txt @@ -0,0 +1,192 @@ +=============================== +Server Selection and Monitoring +=============================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +Server Selection and Monitoring +------------------------------- + +Before any operation can be executed, the |php-library| must first select a +server from the topology (e.g. replica set, sharded cluster). Selecting a server +requires an accurate view of the topology, so the extension regularly monitors +the servers to which it is connected. + +In most other drivers, server discovery and monitoring is handled by a +background thread; however, the PHP driver is single-threaded and must therefore +perform monitoring *between* operations initiated by the application. + +Consider the following example application: + +.. code-block:: php + + test; + + /** + * The library creates an internal object for this operation and must select + * a server to use for executing that operation. + * + * If this is the first operation on the underlying libmongoc client, it must + * first discover the topology. It does so by establishing connections to any + * host(s) in the seed list (this may entail TLS and OCSP verification) and + * issuing "hello" commands. + * + * In the case of a replica set, connecting to a single host in the seed list + * should allow the driver to discover all other members in the replica set. + * In the case of a sharded cluster, the driver will start with an initial + * seed list of mongos hosts and, if SRV polling is utilized, may discover + * additional mongos hosts over time. + * + * If the topology was already initialized (i.e. this is not the first + * operation on the client), the driver may still need to perform monitoring + * (i.e. "hello" commands) and refresh its view of the topology. This process + * may entail adding or removing hosts from the topology. + * + * Once the topology has been discovered and any necessary monitoring has + * been performed, the driver may select a server according to the rules + * outlined in the server selection specification (e.g. applying a read + * preference, filtering hosts by latency). + */ + $database->command(['ping' => 1]); + +Although the application consists of only a few lines of PHP, there is actually +quite a lot going on behind the scenes! Interested readers can find this process +discussed in greater detail in the following documents: + +- `Single-threaded Mode `_ in the libmongoc documentation +- `Server Discovery and Monitoring `_ specification +- `Server Selection `_ specification + +Connection String Options +------------------------- + +There are several connection string options relevant to server selection and +monitoring. + +connectTimeoutMS +~~~~~~~~~~~~~~~~ + +``connectTimeoutMS`` specifies the limit for both establishing a connection to +a server *and* the socket timeout for server monitoring (``hello`` commands). +This defaults to 10 seconds for single-threaded drivers such as PHP. + +When a server times out during monitoring, it will not be re-checked until at +least five seconds +(`cooldownMS `_) +have elapsed. This timeout is intended to avoid having single-threaded drivers +block for ``connectTimeoutMS`` on *each* subsequent scan after an error. + +Applications can consider setting this option to slightly more than the greatest +latency among servers in the cluster. For example, if the greatest ``ping`` time +between the PHP application server and a database server is 200ms, it may be +reasonable to specify a timeout of one second. This would allow ample time for +establishing a connection and monitoring an accessible server, while also +significantly reducing the time to detect an inaccessible server. + +heartbeatFrequencyMS +~~~~~~~~~~~~~~~~~~~~ + +``heartbeatFrequencyMS`` determines how often monitoring should occur. This +defaults to 60 seconds for single-threaded drivers and can be set as low as +500ms. + +serverSelectionTimeoutMS +~~~~~~~~~~~~~~~~~~~~~~~~ + +``serverSelectionTimeoutMS`` determines the maximum amount of time to spend in +the server selection loop. This defaults to 30 seconds, but applications will +typically fail sooner if ``serverSelectionTryOnce`` is ``true`` and a smaller +``connectTimeoutMS`` value is in effect. + +The original default was established at a time when replica set elections took +much longer to complete. Applications can consider setting this option to +slightly more than the expected completion time for an election. For example, +:manual:`Replica Set Elections ` states that +elections will not typically exceed 12 seconds, so a 15-second timeout may be +reasonable. Applications connecting to a sharded cluster may consider a smaller +value still, since ``mongos`` insulates the driver from elections. + +That said, ``serverSelectionTimeoutMS`` should generally not be set to a value +smaller than ``connectTimeoutMS``. + +serverSelectionTryOnce +~~~~~~~~~~~~~~~~~~~~~~ + +``serverSelectionTryOnce`` determines whether the driver should give up after +the first failed server selection attempt or continue waiting until +``serverSelectionTimeoutMS`` is reached. PHP defaults to ``true``, which allows +the driver to "fail fast" when a server cannot be selected (e.g. no primary +during a failover). + +The default behavior is generally desirable for a high-traffic web applications, +as it means the worker process will not be blocked in a server selection loop +and can instead return an error response and immediately go on to serve another +request. Additionally, other driver features such as retryable reads and writes +can still enable applications to avoid transient errors such as a failover. + +That said, applications that prioritize resiliency over response time (and +worker pool utilization) may want to specify ``false`` for +``serverSelectionTryOnce``. + +socketCheckIntervalMS +~~~~~~~~~~~~~~~~~~~~~ + +``socketCheckIntervalMS`` determines how often a socket should be checked (using +a ``ping`` command) if it has not been used recently. This defaults to 5 seconds +and is intentionally lower than ``heartbeatFrequencyMS`` to better allow +single-threaded drivers to recover dropped connections. + +socketTimeoutMS +~~~~~~~~~~~~~~~ + +``socketTimeoutMS`` determines the maximum amount of time to spend reading or +writing to a socket. Since server monitoring uses ``connectTimeoutMS`` for its +socket timeouts, ``socketTimeoutMS`` only applies to operations executed by the +application. + +``socketTimeoutMS`` defaults to 5 minutes; however, it's likely that a PHP web +request would be terminated sooner due to +`max_execution_time `_, +which defaults to 30 seconds for web SAPIs. In a CLI environment, where +``max_execution_time`` is unlimited by default, it is more likely that +``socketTimeoutMS`` could be reached. + +.. note:: + + ``socketTimeoutMS`` is not directly related to server selection and + monitoring; however, it is frequently associated with the other options and + therefore bears mentioning. diff --git a/source/tutorial/stable-api.txt b/source/tutorial/stable-api.txt new file mode 100644 index 00000000..d018162a --- /dev/null +++ b/source/tutorial/stable-api.txt @@ -0,0 +1,93 @@ +========== +Stable API +========== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Declaring an API Version +------------------------ + +To declare an API version, pass a ``serverApi`` driver option when creating your +client. The value is a +:php:`MongoDB\Driver\ServerApi ` instance that +contains API version information. This feature is introduced in MongoDB 5.0, +which will initially support only API version "1". Additional versions may be +introduced in future versions of the server. + +.. code-block:: php + + $serverApi]); + + // Command includes the declared API version + $client->database->collection->find([]); + +.. note:: + + Only declare an API version when connecting to a deployment that has no + pre-5.0 members. Older servers will error when encountering commands with a + declared API version. + +Strict API +---------- + +By default, declaring an API version guarantees behavior for commands that are +part of the stable API, but does not forbid using commands that are not part +of the API version. To only allow commands and options that are part of the +stable API, specify the ``strict`` option when creating the +:php:`MongoDB\Driver\ServerApi ` instance: + +.. code-block:: php + + $serverApi]); + + // Will fail as the tailable option is not supported in versioned API + $client->database->collection->find([], ['tailable' => true]); + +Fail on Deprecated Commands +--------------------------- + +The optional ``deprecationErrors`` option causes MongoDB to fail all commands +or behaviors that have been deprecated in the API version. This can be used in +testing to ensure a smooth transition to a future API version. + +.. code-block:: php + + $serverApi]); + +.. note:: + + At the time of this writing, no part of API version "1" has been deprecated. + +Usage with the Command Helper +----------------------------- + +When using the :phpmethod:`MongoDB\Database::command()` method to run arbitrary +commands, the API version declared to the client is automatically appended to +the command document. Setting any of the ``apiVersion``, ``apiStrict``, or +``apiDeprecationErrors`` command options in the command document and calling +:phpmethod:`MongoDB\Database::command()` from a client with a declared API +version is not supported and will lead to undefined behavior. diff --git a/source/tutorial/tailable-cursor.txt b/source/tutorial/tailable-cursor.txt new file mode 100644 index 00000000..6285676e --- /dev/null +++ b/source/tutorial/tailable-cursor.txt @@ -0,0 +1,190 @@ +.. _php-tailable-cursor: + +========================= +Tailable Cursor Iteration +========================= + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +Overview +-------- + +When the driver executes a query or command (e.g. +:manual:`aggregate `), results from the operation +are returned via a :php:`MongoDB\Driver\Cursor ` +object. The Cursor class implements PHP's :php:`Iterator ` +interface, which allows it to be iterated with ``foreach`` and interface with +any PHP functions that work with :php:`iterables `. Similar to +result objects in other database drivers, cursors in MongoDB only support +forward iteration, which means they cannot be rewound or used with ``foreach`` +multiple times. + +:manual:`Tailable cursors ` are a special type of +MongoDB cursor that allows the client to read some results and then wait until +more documents become available. These cursors are primarily used with +:manual:`Capped Collections ` and +:manual:`Change Streams `. + +While normal cursors can be iterated once with ``foreach``, that approach will +not work with tailable cursors. When ``foreach`` is used with a tailable cursor, +the loop will stop upon reaching the end of the initial result set. Attempting +to continue iteration on the cursor with a second ``foreach`` would throw an +exception, since PHP attempts to rewind the cursor. Therefore, reading from a +tailable cursor will require direct usage of the :php:`Iterator ` API. + +.. note:: + + Before version 1.9.0 of the ``ext-mongodb`` extension, the cursor class does + not implement the :php:`Iterator ` interface. To manually iterate + a cursor using the method below, it must first be wrapped with an + :php:`IteratorIterator `. + +Manually Iterating a Normal Cursor +---------------------------------- + +Before looking at how a tailable cursor can be iterated, we'll start by +examining how the ``Iterator`` methods interact with a normal cursor. + +The following example finds five restaurants and uses ``foreach`` to view the +results: + +.. code-block:: php + + test->restaurants; + + $cursor = $collection->find([], ['limit' => 5]); + + foreach ($cursor as $document) { + var_dump($document); + } + +While this example is quite concise, there is actually quite a bit going on. The +``foreach`` construct begins by rewinding the iterable (``$cursor`` in this +case). It then checks if the current position is valid. If the position is not +valid, the loop ends. Otherwise, the current key and value are accessed +accordingly and the loop body is executed. Assuming a :php:`break ` has +not occurred, the iterator then advances to the next position, control jumps +back to the validity check, and the loop continues. + +With the inner workings of ``foreach`` under our belt, we can now translate the +preceding example to use the Iterator methods directly: + +.. code-block:: php + + test->restaurants; + + $cursor = $collection->find([], ['limit' => 5]); + + $cursor->rewind(); + + while ($cursor->valid()) { + $document = $cursor->current(); + var_dump($document); + $cursor->next(); + } + +.. note:: + + Calling ``$cursor->next()`` after the ``while`` loop naturally ends would + throw an exception, since all results on the cursor have been exhausted. + +The purpose of this example is to demonstrate the functional equivalence between +``foreach`` and manual iteration with PHP's :php:`Iterator ` API. +For normal cursors, there is little reason to manually iterate results instead +of a concise ``foreach`` loop. + +Iterating a Tailable Cursor +--------------------------- + +In order to demonstrate a tailable cursor in action, we'll need two scripts: a +"producer" and a "consumer". The producer script will create a new capped +collection using :phpmethod:`MongoDB\Database::createCollection()` and proceed +to insert a new document into that collection each second. + +.. code-block:: php + + test; + + $database->createCollection('capped', [ + 'capped' => true, + 'size' => 16777216, + ]); + + $collection = $database->selectCollection('capped'); + + while (true) { + $collection->insertOne(['createdAt' => new MongoDB\BSON\UTCDateTime()]); + sleep(1); + } + +With the producer script still running, we will now execute a consumer script to +read the inserted documents using a tailable cursor, indicated by the +``cursorType`` option to :phpmethod:`MongoDB\Collection::find()`. We'll start +by using ``foreach`` to illustrate its shortcomings: + +.. code-block:: php + + test->capped; + + $cursor = $collection->find([], [ + 'cursorType' => MongoDB\Operation\Find::TAILABLE_AWAIT, + 'maxAwaitTimeMS' => 100, + ]); + + foreach ($cursor as $document) { + printf("Consumed document created at: %s\n", $document->createdAt); + } + +If you execute this consumer script, you'll notice that it quickly exhausts all +results in the capped collection and then terminates. We cannot add a second +``foreach``, as that would throw an exception when attempting to rewind the +cursor. This is a ripe use case for directly controlling the iteration process +using the :php:`Iterator ` interface. + +.. code-block:: php + + test->capped; + + $cursor = $collection->find([], [ + 'cursorType' => MongoDB\Operation\Find::TAILABLE_AWAIT, + 'maxAwaitTimeMS' => 100, + ]); + + $cursor->rewind(); + + while (true) { + if ($cursor->valid()) { + $document = $cursor->current(); + printf("Consumed document created at: %s\n", $document->createdAt); + } + + $cursor->next(); + } + +Much like the ``foreach`` example, this version on the consumer script will +start by quickly printing all results in the capped collection; however, it will +not terminate upon reaching the end of the initial result set. Since we're +working with a tailable cursor, calling ``next()`` will block and wait for +additional results rather than throw an exception. We will also use ``valid()`` +to check if there is actually data available to read at each step. + +Since we've elected to use a ``TAILABLE_AWAIT`` cursor, the server will delay +its response to the driver for a set amount of time. In this example, we've +requested that the server block for approximately 100 milliseconds by specifying +the ``maxAwaitTimeMS`` option to :phpmethod:`MongoDB\Collection::find()`. diff --git a/source/upgrade.txt b/source/upgrade.txt new file mode 100644 index 00000000..18e92e52 --- /dev/null +++ b/source/upgrade.txt @@ -0,0 +1,369 @@ +=========================== +Legacy Driver Upgrade Guide +=========================== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +Overview +-------- + +The |php-library| and underlying :php:`mongodb extension ` have notable +API differences from the legacy ``mongo`` extension. This page will summarize +those differences for the benefit of those upgrading from the legacy driver. + +Additionally, a community-developed `mongo-php-adapter +`_ library exists, which +implements the ``mongo`` extension API using this library and the ``mongodb`` +extension. While this adapter library is not officially supported by MongoDB, it +does bear mentioning. + +BSON +---- + +Type Classes +~~~~~~~~~~~~ + +When upgrading from the legacy driver, type classes such as MongoId must be +replaced with classes in the +`MongoDB\\BSON namespace `_. The new +driver also introduces interfaces for its BSON types, which should be preferred +if applications need to type hint against BSON values. + +The following table lists all legacy classes alongside the equivalent class in +the new driver. + +.. list-table:: + :header-rows: 1 + + * - Legacy class + - BSON type class + - BSON type interface + + * - MongoId + - :php:`MongoDB\BSON\ObjectId ` + - :php:`MongoDB\BSON\ObjectIdInterface ` + + * - MongoCode + - :php:`MongoDB\BSON\Javascript ` + - :php:`MongoDB\BSON\JavascriptInterface ` + + * - MongoDate + - :php:`MongoDB\BSON\UTCDateTime ` + - :php:`MongoDB\BSON\UTCDateTimeInterface ` + + * - MongoRegex + - :php:`MongoDB\BSON\Regex ` + - :php:`MongoDB\BSON\RegexInterface ` + + * - MongoBinData + - :php:`MongoDB\BSON\Binary ` + - :php:`MongoDB\BSON\BinaryInterface ` + + * - MongoInt32 + - Not implemented. [1]_ + - + + * - MongoInt64 + - :php:`MongoDB\BSON\Int64 ` + - Not implemented. [2]_ + + * - MongoDBRef + - Not implemented. [3]_ + - + + * - MongoMinKey + - :php:`MongoDB\BSON\MinKey ` + - :php:`MongoDB\BSON\MinKeyInterface ` + + * - MongoMaxKey + - :php:`MongoDB\BSON\MaxKey ` + - :php:`MongoDB\BSON\MaxKeyInterface ` + + * - MongoTimestamp + - :php:`MongoDB\BSON\Timestamp ` + - :php:`MongoDB\BSON\TimestampInterface ` + +.. [1] The new driver does not implement an equivalent class for MongoInt32. + When decoding BSON, 32-bit integers will always be represented as a PHP + integer. When encoding BSON, PHP integers will encode as either a 32-bit or + 64-bit integer depending on their value. + +.. [2] :php:`MongoDB\BSON\Int64 ` does not have an + interface defined. + +.. [3] The new driver does not implement an equivalent class for MongoDBRef + since :manual:`DBRefs ` are merely a BSON + document with a particular structure and not a proper BSON type. The new + driver also does not provide any helpers for working with DBRef objects, + since their use is not encouraged. + +Emulating the Legacy Driver +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The legacy ``mongo`` extension returned both BSON documents and arrays as PHP +arrays. While PHP arrays are convenient to work with, this behavior was +problematic: + +- Different BSON types could deserialize to the same PHP value (e.g. + ``{"0": "foo"}`` and ``["foo"]``), which made it impossible to infer the + original BSON type. + +- Numerically-indexed PHP arrays would be serialized as BSON documents if there + was a gap in their key sequence. Such gaps were caused by unsetting a key to + remove an element and forgetting to numerically reindex the array. + +The |php-library|'s :phpclass:`BSONDocument ` and +:phpclass:`BSONArray ` classes address these concerns +by preserving the BSON type information during serialization and +deserialization; however, some users may still prefer the legacy behavior. If +desired, you can use the ``typeMap`` option to have the library return +everything as a PHP array: + +.. code-block:: php + + [ + 'array' => 'array', + 'document' => 'array', + 'root' => 'array', + ], + ] + ); + + $document = $client->test->zips->findOne(['_id' => '94301']); + + var_dump($document); + +The above example would output something similar to: + +.. code-block:: php + + array(5) { + ["_id"]=> + string(5) "94301" + ["city"]=> + string(9) "PALO ALTO" + ["loc"]=> + array(2) { + [0]=> + float(-122.149685) + [1]=> + float(37.444324) + } + ["pop"]=> + int(15965) + ["state"]=> + string(2) "CA" + } + +Collection API +-------------- + +This library's :phpclass:`MongoDB\Collection` class implements MongoDB's +cross-driver `CRUD +`_ +and `Index Management +`_ +specifications. Although some method names have changed in accordance with the +new specifications, the new class provides the same functionality as the legacy +driver's MongoCollection class with some notable exceptions. + +A guiding principle in designing the new APIs was that explicit method names are +preferable to overloaded terms found in the old API. For instance, +``MongoCollection::save()`` and ``MongoCollection::findAndModify()`` have +different modes of operation, depending on their arguments. Methods were also +split to distinguish between :manual:`updating specific fields +` and :manual:`full-document replacement +`. + +The following table lists all legacy methods alongside the +equivalent method(s) in the new driver. + +.. list-table:: + :header-rows: 1 + + * - MongoCollection method + - :phpclass:`MongoDB\Collection` method(s) + + * - ``MongoCollection::aggregate()`` + - :phpmethod:`MongoDB\Collection::aggregate()` + + * - ``MongoCollection::aggregateCursor()`` + - :phpmethod:`MongoDB\Collection::aggregate()` + + * - ``MongoCollection::batchInsert()`` + - :phpmethod:`MongoDB\Collection::insertMany()` + + * - ``MongoCollection::count()`` + - :phpmethod:`MongoDB\Collection::count()` + + * - ``MongoCollection::createDBRef()`` + - Not yet implemented. [3]_ + + * - ``MongoCollection::createIndex()`` + - :phpmethod:`MongoDB\Collection::createIndex()` + + * - ``MongoCollection::deleteIndex()`` + - :phpmethod:`MongoDB\Collection::dropIndex()` + + * - ``MongoCollection::deleteIndexes()`` + - :phpmethod:`MongoDB\Collection::dropIndexes()` + + * - ``MongoCollection::drop()`` + - :phpmethod:`MongoDB\Collection::drop()` + + * - ``MongoCollection::distinct()`` + - :phpmethod:`MongoDB\Collection::distinct()` + + * - ``MongoCollection::ensureIndex()`` + - :phpmethod:`MongoDB\Collection::createIndex()` + + * - ``MongoCollection::find()`` + - :phpmethod:`MongoDB\Collection::find()` + + * - ``MongoCollection::findAndModify()`` + - :phpmethod:`MongoDB\Collection::findOneAndDelete()`, + :phpmethod:`MongoDB\Collection::findOneAndReplace()`, and + :phpmethod:`MongoDB\Collection::findOneAndUpdate()` + + * - ``MongoCollection::findOne()`` + - :phpmethod:`MongoDB\Collection::findOne()` + + * - ``MongoCollection::getDBRef()`` + - Not implemented. [3]_ + + * - ``MongoCollection::getIndexInfo()`` + - :phpmethod:`MongoDB\Collection::listIndexes()` + + * - ``MongoCollection::getName()`` + - :phpmethod:`MongoDB\Collection::getCollectionName()` + + * - ``MongoCollection::getReadPreference()`` + - :phpmethod:`MongoDB\Collection::getReadPreference()` + + * - ``MongoCollection::getSlaveOkay()`` + - Not implemented. + + * - ``MongoCollection::getWriteConcern()`` + - :phpmethod:`MongoDB\Collection::getWriteConcern()` + + * - ``MongoCollection::group()`` + - Not implemented. Use :phpmethod:`MongoDB\Database::command()`. See + :ref:`Group Command Helper ` for an example. + + * - ``MongoCollection::insert()`` + - :phpmethod:`MongoDB\Collection::insertOne()` + + * - ``MongoCollection::parallelCollectionScan()`` + - Not implemented. + + * - ``MongoCollection::remove()`` + - :phpmethod:`MongoDB\Collection::deleteMany()` and + :phpmethod:`MongoDB\Collection::deleteOne()` + + * - ``MongoCollection::save()`` + - :phpmethod:`MongoDB\Collection::insertOne()` or + :phpmethod:`MongoDB\Collection::replaceOne()` with the ``upsert`` + option. + + * - ``MongoCollection::setReadPreference()`` + - Not implemented. Use :phpmethod:`MongoDB\Collection::withOptions()`. + + * - ``MongoCollection::setSlaveOkay()`` + - Not implemented. + + * - ``MongoCollection::setWriteConcern()`` + - Not implemented. Use :phpmethod:`MongoDB\Collection::withOptions()`. + + * - ``MongoCollection::update()`` + - :phpmethod:`MongoDB\Collection::replaceOne()`, + :phpmethod:`MongoDB\Collection::updateMany()`, and + :phpmethod:`MongoDB\Collection::updateOne()`. + + * - ``MongoCollection::validate()`` + - Not implemented. + +Accessing IDs of Inserted Documents +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In the legacy driver, ``MongoCollection::insert()``, +``MongoCollection::batchInsert()``, and ``MongoCollection::save()`` (when +inserting) would modify their input argument by injecting an ``_id`` key with a +generated ObjectId (i.e. MongoId object). This behavior was a bit of a hack, as +it did not rely on the argument being :php:`passed by reference +`; instead, it directly modified memory through the +extension API and could not be implemented in PHP userland. As such, it is no +longer done in the new driver. + +IDs of inserted documents (whether generated or not) may be accessed through the +following methods on the write result objects: + +- :phpmethod:`MongoDB\InsertOneResult::getInsertedId()` for + :phpmethod:`MongoDB\Collection::insertOne()` +- :phpmethod:`MongoDB\InsertManyResult::getInsertedIds()` for + :phpmethod:`MongoDB\Collection::insertMany()` +- :phpmethod:`MongoDB\BulkWriteResult::getInsertedIds()` for + :phpmethod:`MongoDB\Collection::bulkWrite()` + +Bulk Write Operations +~~~~~~~~~~~~~~~~~~~~~ + +The legacy driver's MongoWriteBatch classes have been replaced with a +general-purpose :phpmethod:`MongoDB\Collection::bulkWrite()` method. Whereas +the legacy driver only allowed bulk operations of the same type, the new method +allows operations to be mixed (e.g. inserts, updates, and deletes). + +MongoCollection::save() Removed +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +``MongoCollection::save()``, which was syntactic sugar for an insert or upsert +operation, has been removed in favor of explicitly using +:phpmethod:`MongoDB\Collection::insertOne()` or +:phpmethod:`MongoDB\Collection::replaceOne()` (with the ``upsert`` option). + +While the ``save`` method does have its uses for interactive environments, such +as the MongoDB shell, it was intentionally excluded from the +`CRUD specification `_ +for language drivers. Generally, application code should know if the document +has an identifier and be able to explicitly insert or replace the document and +handle the returned :phpclass:`MongoDB\InsertOneResult` or +:phpclass:`MongoDB\UpdateResult`, respectively. This also helps avoid +inadvertent and potentially dangerous :manual:`full-document replacements +`. + +.. _group-command-helper: + +Group Command Helper +~~~~~~~~~~~~~~~~~~~~ + +:phpclass:`MongoDB\Collection` does not have a helper method for the +:manual:`group ` command. The following example +demonstrates how to execute a group command using the +:phpmethod:`MongoDB\Database::command()` method: + +.. code-block:: php + + selectDatabase('db_name'); + $cursor = $database->command([ + 'group' => [ + 'ns' => 'collection_name', + 'key' => ['field_name' => 1], + 'initial' => ['total' => 0], + '$reduce' => new MongoDB\BSON\Javascript('...'), + ], + ]); + + $resultDocument = $cursor->toArray()[0];