MongoDB driver

目录

Unlike the mongo extension, this extension is developed atop the » libmongoc and » libbson libraries. It provides a minimal API for core driver functionality: commands, queries, writes, connection management, and BSON serialization.

Userland PHP libraries that depend on this extension may provide higher level APIs, such as query builders, individual command helper methods, and GridFS. Application developers should consider using this extension in conjunction with the » MongoDB PHP library, which implements the same higher level APIs found in MongoDB drivers for other languages. This separation of concerns allows the driver to focus on essential features for which an extension implementation is paramount for performance.

安装/配置

目录

需求

The driver requires PHP 5.5 or higher.

The driver requires » libbson and » libmongoc, and will use bundled versions of both libraries by default.

The driver requires » OpenSSL and will rely on PHP to find its headers (i.e. PHP_SETUP_OPENSSL). If the build process fails to find OpenSSL, check that the OpenSSL development package (e.g. libssl-dev) and » pkg-config are both installed.

Due to potential problems representing 64-bit integers on 32-bit platforms, users are advised to use 64-bit environments. When using a 32-bit platform, be aware that any 64-bit integer read from the database will be returned as a MongoDB\BSON\Int64 instance instead of a PHP integer type.

» Cyrus SASL is an optional dependency and will be used if available.

安装

目录

Installing the MongoDB PHP Driver with PECL

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等,都在此处: » https://pecl.php.net/package/mongodb

Linux, Unix, and macOS users may run the following command to install the driver:

$ sudo pecl install mongodb

If your system has multiple version of PHP installed (e.g. macOS default, Homebrew, » XAMPP), note that that each version of PHP has its own pecl command and php.ini file.

Installing the driver via PECL will use bundled versions of » libbson and » libmongoc and attempt to automatically configure them.

Note: If the build process fails to find an SSL library, check that the development packages (e.g. libssl-dev) and » pkg-config are both installed. If that does not resolve the problem, consider using the manual installation process.

Finally, add the following line to your php.ini file:

extension=mongodb.so

Installing the MongoDB PHP Driver on macOS with Homebrew

» Homebrew 1.5.0 deprecated the » Homebrew/php tap and removed formulae for individual PHP extensions. Going forward, macOS users are advised to install the » php formula and follow the standard PECL installation instructions using the pecl command provided by the Homebrew PHP installation.

Installing the MongoDB PHP Driver on Windows

Precompiled binaries for each release are available from » PECL for a variety of combinations of versions, thread safety, and VC libraries. Extract the archive and put php_mongodb.dll in your PHP extension directory ("ext" by default).

Add the following line to your php.ini file:

extension=php_mongodb.dll

Note: Additional DLL dependencies for Windows Users

为了使此扩展生效, DLL 文件必须能在 Windows 系统的 PATH 指示的路径下找到。如何操作的信息,请参见题为“如何在 Windows 中将 PHP 目录加到 PATH 中”的FAQ。虽然将 DLL 文件从 PHP 文件夹复制到 Windows 系统目录也行,但不建议这样做。 此扩展需要下列文件在 PATH 路径中: libsasl.dll

Building the MongoDB PHP Driver from source

For driver developers and people interested in the latest bugfixes, you can compile the driver from the latest source code on » Github. Run the following commands to clone and build the project:

$ git clone https://github.com/mongodb/mongo-php-driver.git
$ cd mongo-php-driver
$ git submodule update --init
$ phpize
$ ./configure
$ make all
$ sudo make install

If your system has multiple version of PHP installed (e.g. macOS default and » XAMPP), note that each version of PHP has its own phpize command and php.ini file.

By default, the driver will use bundled versions of » libbson, » libmongoc, and » libmongocrypt and attempt to configure them on its own. If these libraries are already installed as system libraries, you can instruct the driver to utilize them by specifying --with-libbson=yes --with--libmongoc=yes as arguments to configure. Starting with version 1.7.0 of the extension, these arguments are deprecated and you should use --with-mongodb-system-libs=yes instead.

For a complete list of configure options, run configure --help.

When using bundled versions of libbson and libmongoc, the driver will also attempt to select an SSL library according to the --with-mongodb-ssl option for configure. The default value is --with-mongodb-ssl=auto, which will search for Secure Transport (macOS only), OpenSSL, and LibreSSL, in that order. Additionally, you may specify openssl, libressl, or darwin to force selection of a particular library, respectively.

Note:

If the build process fails to find an SSL library, check that the development packages (e.g. libssl-dev) and » pkg-config are both installed.

When using Homebrew on macOS, it is common for a system to have multiple versions of OpenSSL installed. To ensure that the desired version of OpenSSL is selected, the PKG_CONFIG_PATH environment variable may be used to control the search path for pkg-config. If pkg-config is not used, configure also supports a --with-openssl-dir=DIR argument, which can be used to specify a manual search path (for OpenSSL only).

The final build step, make install, will report where mongodb.so has been installed, similar to:

Installing shared extensions:     /usr/lib/php/extensions/debug-non-zts-20151012/

Ensure that the extension_dir option in php.ini points to the directory where mongodb.so was installed. You can query for the option by running:

$ php -i | grep extension_dir
  extension_dir => /usr/lib/php/extensions/debug-non-zts-20151012 =>
                   /usr/lib/php/extensions/debug-non-zts-20151012

If the directories differ, either change extension_dir in php.ini or manually move mongodb.so to the correct directory.

Finally, add the following line to your php.ini file:

extension=mongodb.so

运行时配置

这些函数的行为受 php.ini 中的设置影响。

名字默认可修改范围更新日志Comments
mongodb.debug""PHP_INI_ALL 

这是配置指令的简短说明。

mongodb.debug string
Store full activity debug log in this directory or stream. The special value "stderr" can be provided to write to STDERR.

Note:

Please note that the debug log can contain sensitive information, such as credentials to the MongoDB server and full documents written to or read from the server. Please review any debug logs before sharing them with other people.

预定义常量

下列常量由此扩展定义,且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

MONGODB_VERSION (string)
x.y.z style version number of the extension

MONGODB_STABILITY (string)
Current stability (alpha/beta/stable)

Tutorials

目录

In this section you will find several tutorials on how to use the MongoDB driver for PHP.

Using the PHP Library for MongoDB (PHPLIB)

After the initial driver set-up, we will continue explaining how to get started with the MongoDB driver and corresponding userland library to write our first project.

Installing the PHP Library with Composer

The last thing we still need to install to get started on the application itself, is the PHP library.

The library needs to be installed with » Composer, a package manager for PHP. Instructions for installing Composer on various platforms may be found on its website.

Install the library by running:

$ composer require mongodb/mongodb

It will output something akin to:

./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing mongodb/mongodb (1.0.0)
    Downloading: 100%         

Writing lock file
Generating autoload files

Composer will create several files: composer.json, composer.lock, and a vendor directory that will contain the library and any other dependencies your project might require.

Using the PHP Library

In addition to managing your dependencies, Composer will also provide you with an autoloader (for those dependencies' classes). Ensure that it is included at the start of your script or in your application's bootstrap code:

<?php
// This path should point to Composer's autoloader
require 'vendor/autoload.php';

With this done, you can now use any of the functionality as described in the » library documentation.

If you have previously used the old driver (i.e. mongo extension), the library's API should look familiar. It contains a » Client class for connecting to MongoDB, and » Database class for database-level operations (e.g. commands, collection management) and a » Collection class for collection-level operations (e.g. » CRUD methods, index management). Various Collection methods have been renamed for clarity, and to be in accordance with a new language-agnostic » specification.

As an example, this is how you insert a document into the beers collection of the demo database:

<?php
require 'vendor/autoload.php'; // include Composer's autoloader

$client = new MongoDB\Client("mongodb://localhost:27017");
$collection = $client->demo->beers;

$result = $collection->insertOne( [ 'name' => 'Hinterland', 'brewery' => 'BrewDog' ] );

echo "Inserted with Object ID '{$result->getInsertedId()}'";
?>

Instead of injecting the generated _id field into the input document (as was done in the old driver), it is now made available through the result object returned by the insertOne method.

After insertion, you can of course also query the data that you have just inserted. For that, you use the find method, which returns an iterable cursor:

<?php
require 'vendor/autoload.php'; // include Composer's autoloader

$client = new MongoDB\Client("mongodb://localhost:27017");
$collection = $client->demo->beers;

$result = $collection->find( [ 'name' => 'Hinterland', 'brewery' => 'BrewDog' ] );

foreach ($result as $entry) {
    echo $entry['_id'], ': ', $entry['name'], "\n";
}
?>

While it may not be apparent in the examples, BSON documents and arrays are unserialized as type classes in the library by default. These classes ensure that values preserve their type when being serialized back into BSON, which avoids a caveat in the old driver where arrays might turn into documents, and vice versa. Additionally, the classes extend ArrayObject for enhanced usability. You can find more information on how serialization and deserialization between PHP variables and BSON is handled by the driver and library by reading the specification.

Application Performance Monitoring (APM)

Since version 1.3, the MongoDB driver contains an API for performance monitoring. This API allows you to find out how long specific operations take by setting up subscribers. Each subscriber is required to implement one or more interfaces under the MongoDB\Driver\Monitoring namespace. Currently, only the MongoDB\Driver\Monitoring\CommandSubscriber interface is available.

The MongoDB\Driver\Monitoring\CommandSubscriber interface defines three methods: commandStarted, commandSucceeded, and commandFailed. Each of these three methods accept a single event argument of a specific class for the respective event. For example, the commandSucceeded's $event argument is a MongoDB\Driver\Monitoring\CommandSucceededEvent object.

In this tutorial we will implement a subscriber that creates a list of all the query profiles and the average time they took.

Subscriber Class Scaffolding

We start with the framework for our subscriber:

<?php

class QueryTimeCollector implements \MongoDB\Driver\Monitoring\CommandSubscriber
{
    public function commandStarted( \MongoDB\Driver\Monitoring\CommandStartedEvent $event )
    {
    }

    public function commandSucceeded( \MongoDB\Driver\Monitoring\CommandSucceededEvent $event )
    {
    }

    public function commandFailed( \MongoDB\Driver\Monitoring\CommandFailedEvent $event )
    {
    }
}

?>

Registering the Subscriber

Once a subscriber object is instantiated, it needs to be registered with the driver's monitoring system. This is done by calling MongoDB\Driver\Monitoring\addSubscriber.

<?php

\MongoDB\Driver\Monitoring\addSubscriber( new QueryTimeCollector() );

?>

Implementing the Logic

With the object registered, the only thing left is to implement the logic in the subscriber class. To correlate the two events that make up a successfully executed command (commandStarted and commandSucceeded), each event object exposes a requestId field.

To record the average time per query shape, we will start by checking for a find command in the commandStarted event. We will then add an item to the pendingCommands property indexed by its requestId and with its value representing the query shape.

If we receive a corresponding commandSucceeded event with the same requestId, we add the duration of the event (from durationMicros) to the total time and increment the operation count.

If a corresponding commandFailed event is encountered, we just remove the entry from the pendingCommands property.

<?php

class QueryTimeCollector implements \MongoDB\Driver\Monitoring\CommandSubscriber
{
    private $pendingCommands = [];
    private $queryShapeStats = [];

    /* Creates a query shape out of the filter argument. Right now it only
     * takes the top level fields into account */
    private function createQueryShape( array $filter )
    {
        return json_encode( array_keys( $filter ) );
    }

    public function commandStarted( \MongoDB\Driver\Monitoring\CommandStartedEvent $event )
    {
        if ( array_key_exists( 'find', (array) $event->getCommand() ) )
        {
            $queryShape = $this->createQueryShape( (array) $event->getCommand()->filter );
            $this->pendingCommands[$event->getRequestId()] = $queryShape;
        }
    }

    public function commandSucceeded( \MongoDB\Driver\Monitoring\CommandSucceededEvent $event )
    {
        $requestId = $event->getRequestId();
        if ( array_key_exists( $requestId, $this->pendingCommands ) )
        {
            $this->queryShapeStats[$this->pendingCommands[$requestId]]['count']++;
            $this->queryShapeStats[$this->pendingCommands[$requestId]]['duration'] += $event->getDurationMicros();
            unset( $this->pendingCommands[$requestId] );
        }
    }

    public function commandFailed( \MongoDB\Driver\Monitoring\CommandFailedEvent $event )
    {
        if ( array_key_exists( $event->getRequestId(), $this->pendingCommands ) )
        {
            unset( $this->pendingCommands[$event->getRequestId()] );
        }
    }

    public function __destruct()
    {
        foreach( $this->queryShapeStats as $shape => $stats )
        {
            echo "Shape: ", $shape, " (", $stats['count'], ")\n  ",
                $stats['duration'] / $stats['count'], "µs\n\n";
        }
    }
}

$m = new \MongoDB\Driver\Manager( 'mongodb://localhost:27016' );

/* Add the subscriber */
\MongoDB\Driver\Monitoring\addSubscriber( new QueryTimeCollector() );

/* Do a bunch of queries */
$query = new \MongoDB\Driver\Query( [
    'region_slug' => 'scotland-highlands', 'age' => [ '$gte' => 20 ]
] );
$cursor = $m->executeQuery( 'dramio.whisky', $query );

$query = new \MongoDB\Driver\Query( [
    'region_slug' => 'scotland-lowlands', 'age' => [ '$gte' => 15 ]
] );
$cursor = $m->executeQuery( 'dramio.whisky', $query );

$query = new \MongoDB\Driver\Query( [ 'region_slug' => 'scotland-lowlands' ] );
$cursor = $m->executeQuery( 'dramio.whisky', $query );

?>

Explains the driver architecture, and special features

目录

Architecture Overview

This section explains how all the different parts of the driver fit together. From the different language runtimes, through the extension and to the PHP libraries on top. This new architecture has replaced the old mongo extension. We refer to the new one as the mongodb extension.

Architecture Diagram

At the top of this stack sits a pure » PHP library, which we will distribute as a Composer package. This library will provide an API similar to what users have come to expect from the old mongo driver (e.g. CRUD methods, database and collection objects, command helpers) and we expect it to be a common dependency for most applications built with MongoDB. This library will also implement common » specifications, in the interest of improving API consistency across all of the » drivers maintained by MongoDB (and hopefully some community drivers, too).

Sitting below that library we have the lower level driver. This extension will effectively form the glue between PHP and our system libraries (» libmongoc and » libbson). This extension will expose an identical public API for the most essential and performance-sensitive functionality:

  • Connection management
  • BSON encoding and decoding
  • Object document serialization (to support ODM libraries)
  • Executing commands and write operations
  • Handling queries and cursors

By decoupling the driver internals and a high-level API into an extension and PHP libraries, respectively, we hope to reduce our maintainence burden and allow for faster iteration on new features. As a welcome side effect, this also makes it easier for anyone to contribute to the driver. Additionally, an identical public API will make it that much easier to port an application across PHP runtimes, whether the application uses the low-level driver directly or a higher-level PHP library.

» GridFS is a great example of why we chose this direction. Although we implemented GridFS in C for our old mongo driver, it is actually quite a high-level specification. Its API is just an abstraction for accessing two collections: files (i.e. metadata) and chunks (i.e. blocks of data). Likewise, all of the syntactic sugar found in the old mongo driver, such as processing uploaded files or exposing GridFS files as PHP streams, can be implemented in pure PHP. Provided we have performant methods for reading from and writing to GridFS' collections – and thanks to our low level extensions, we will – shifting this API to PHP is win-win.

Earlier I mentioned that we expect the PHP library to be a common dependency for most applications, but not all. Some users may prefer to stick to the no-frills API offered by the extensions, or create their own high-level abstraction (akin to » Doctrine MongoDB for the old mongo driver). Future libraries could include a PHP library geared for MongoDB administration, which provides an API for various user management and ops commands. The next major version of » Doctrine MongoDB ODM will likely also sit directly atop the extensions.

While we will continue to maintain and support the old mongo driver and its users for the foreseeable future, we invite everyone to use the next-generation driver and consider it for any new projects going forward. You can find all of the essential components across GitHub and JIRA:

ProjectGitHubJIRA
PHP Library» mongodb/mongo-php-library» PHPLIB
PHP 5 and PHP 7 Driver (phongo)» mongodb/mongo-php-driver» PHPC

The existing » PHP project in JIRA will remain open for reporting bugs against the old mongo driver, but we would ask that you use the new projects above for anything pertaining to our next-generation drivers.

Connection handling and persistence

Note: On Unix platforms, the MongoDB driver is sensitive to scripts that use the fork() system call without also calling exec(). Users are advised not to re-use class="classname">MongoDB\Driver\Manager instances in a forked child process.

Connection and topology persistence (PHP version since 1.2.0)

All versions of the driver since 1.2.0 persist the » libmongoc client object in the PHP worker process, which allows it to re-use database connections, authentication states, and topology information across multiple requests.

When MongoDB\Driver\Manager::__construct is invoked, a hash is created from its arguments (i.e. URI string and array options). The driver will attempt to find a previously persisted » libmongoc client object for that hash. If an existing client cannot be found for the hash, a new client will be created (and persisted for future use).

Each client contains its own database connections and a view of the server topology (e.g. standalone, replica set, shard cluster). By persisting the client between PHP requests, the driver is able to re-use established database connections and remove the need for » discovering the server topology on each request.

Consider the following example:

<?php

$managers = [
    new MongoDB\Driver\Manager('mongodb://127.0.0.1'),
    new MongoDB\Driver\Manager('mongodb://127.0.0.1'),
    new MongoDB\Driver\Manager('mongodb://127.0.0.1:27017'),
    new MongoDB\Driver\Manager('mongodb://rs1.example.com,rs2.example.com/', ['replicaSet' => 'myReplicaSet']),
];

foreach ($managers as $manager) {
    $manager->executeCommand('test', new MongoDB\Driver\Command(['ping' => 1]));
}

?>

The first two Manager objects will share the same » libmongoc client since their constructor arguments are identical. The third and fourth objects will each use their own client. In total, three clients will be created and the PHP worker executing this script will open two connections to 127.0.0.1 and one connection to each of rs1.example.com and rs2.example.com. If the driver discovers additional members of the replica set after issuing isMaster commands, it will open additional connections to those servers as well.

If the same worker executes the script again in a second request, the three clients will be re-used and no new connections should be made. Depending on how long ago the previous request was served, the driver may need to issue additional isMaster commands to update its view of the topologies.

Socket persistence (PHP versions before 1.2.0)

Versions of the PHP driver before 1.2.0 utilize PHP's Streams API for database connections, using an API within » libmongoc to designate custom handlers for socket communication; however, a new libmongoc client is created for each MongoDB\Driver\Manager. As a result, the driver persists individual database connections but not authentication state or topology information. This means that the driver needs to issue commands at the start of each request to authenticate and » discover the server topology.

Database connections are persisted by a hash derived from the server's host, port, and the URI string used to construct the MongoDB\Driver\Manager. The constructor's array options are not included in this hash.

Note: Versions of the driver >= 1.1.8 and < 1.2.0 do not persist sockets for SSL connections. See » PHPC-720 for additional information.

Despite its shortcomings with persisting SSL connections when and topology information, this version of the driver supports all SSL context options since it uses PHP's Streams API.

Serialization and deserialization of PHP variables into MongoDB

目录

This document discusses the methods how compound structures (documents, arrays, objects) are persisted through the drivers. And how they are brought back into PHP land.

Serialization to BSON

Arrays

If an array is a packed array — i.e. the keys start at 0 and are sequential without gaps: BSON array.

If the array is not packed — i.e. having associative (string) keys, the keys don't start at 0, or when there are gaps:: BSON object

A top-level (root) document, always serializes as a BSON document.

Examples

These serialize as a BSON array:

[ 8, 5, 2, 3 ] => [ 8, 5, 2, 3 ]
[ 0 => 4, 1 => 9 ] => [ 4, 9 ]

These serialize as a BSON document:

[ 0 => 1, 2 => 8, 3 => 12 ] => { "0" : 1, "2" : 8, "3" : 12 }
[ "foo" => 42 ] => { "foo" : 42 }
[ 1 => 9, 0 => 10 ] => { "1" : 9, "0" : 10 }

Note that the five examples are extracts of a full document, and represent only one value inside a document.

Objects

If an object is of the stdClass class, serialize as a BSON document.

If an object is a supported class that implements MongoDB\BSON\Type, then use the BSON serialization logic for that specific type. MongoDB\BSON\Type instances (excluding MongoDB\BSON\Serializable may only be serialized as a document field value. Attempting to serialize such an object as a root document will throw a MongoDB\Driver\Exception\UnexpectedValueException

If an object is of an unknown class implementing the MongoDB\BSON\Type interface, then throw a MongoDB\Driver\Exception\UnexpectedValueException

If an object is of any other class, without implementing any special interface, serialize as a BSON document. Keep only public properties, and ignore protected and private properties.

If an object is of a class that implements the MongoDB\BSON\Serializable interface, call MongoDB\BSON\Serializable::bsonSerialize and use the returned array or stdClass to serialize as a BSON document or array. The BSON type will be determined by the following:

  1. Root documents must be serialized as a BSON document.

  2. MongoDB\BSON\Persistable objects must be serialized as a BSON document.

  3. If MongoDB\BSON\Serializable::bsonSerialize returns a packed array, serialize as a BSON array.

  4. If MongoDB\BSON\Serializable::bsonSerialize returns a non-packed array or stdClass, serialize as a BSON document.

  5. If MongoDB\BSON\Serializable::bsonSerialize did not return an array or stdClass, throw an MongoDB\Driver\Exception\UnexpectedValueException exception.

If an object is of a class that implements the MongoDB\BSON\Persistable interface (which implies MongoDB\BSON\Serializable), obtain the properties in a similar way as in the previous paragraphs, but also add an additional property __pclass as a Binary value, with subtype 0x80 and data bearing the fully qualified class name of the object that is being serialized.

The __pclass property is added to the array or object returned by MongoDB\BSON\Serializable::bsonSerialize, which means it will overwrite any __pclass key/property in the MongoDB\BSON\Serializable::bsonSerialize return value. If you want to avoid this behaviour and set your own __pclass value, you must not implement MongoDB\BSON\Persistable and should instead implement MongoDB\BSON\Serializable directly.

Examples

<?php

class stdClass {
  public $foo = 42;
} // => { "foo" : 42 }

class MyClass {
  public $foo = 42;
  protected $prot = "wine";
  private $fpr = "cheese";
} // => { "foo" : 42 }

class AnotherClass1 implements MongoDB\BSON\Serializable {
  public $foo = 42;
  protected $prot = "wine";
  private $fpr = "cheese";
  function bsonSerialize() {
      return [ 'foo' => $this->foo, 'prot' => $this->prot ];
  }
} // => { "foo" : 42, "prot" : "wine" }

class AnotherClass2 implements MongoDB\BSON\Serializable {
  public $foo = 42;
  function bsonSerialize() {
      return $this;
  }
} // => MongoDB\Driver\Exception\UnexpectedValueException("bsonSerialize() did not return an array or stdClass")

class AnotherClass3 implements MongoDB\BSON\Serializable {
  private $elements = [ 'foo', 'bar' ];
  function bsonSerialize() {
      return $this->elements;
  }
} // => { "0" : "foo", "1" : "bar" }

class ContainerClass implements MongoDB\BSON\Serializable {
  public $things = AnotherClass4 implements MongoDB\BSON\Serializable {
    private $elements = [ 0 => 'foo', 2 => 'bar' ];
    function bsonSerialize() {
      return $this->elements;
    }
  }
  function bsonSerialize() {
      return [ 'things' => $this->things ];
  }
} // => { "things" : { "0" : "foo", "2" : "bar" } }

class ContainerClass implements MongoDB\BSON\Serializable {
  public $things = AnotherClass5 implements MongoDB\BSON\Serializable {
    private $elements = [ 0 => 'foo', 2 => 'bar' ];
    function bsonSerialize() {
      return array_values($this->elements);
    }
  }
  function bsonSerialize() {
      return [ 'things' => $this->things ];
  }
} // => { "things" : [ "foo", "bar" ] }

class ContainerClass implements MongoDB\BSON\Serializable {
  public $things = AnotherClass6 implements MongoDB\BSON\Serializable {
    private $elements = [ 'foo', 'bar' ];
    function bsonSerialize() {
      return (object) $this->elements;
    }
  }
  function bsonSerialize() {
      return [ 'things' => $this->things ];
  }
} // => { "things" : { "0" : "foo", "1" : "bar" } }

class UpperClass implements MongoDB\BSON\Persistable {
  public $foo = 42;
  protected $prot = "wine";
  private $fpr = "cheese";
  function bsonSerialize() {
      return [ 'foo' => $this->foo, 'prot' => $this->prot ];
  }
} // => { "foo" : 42, "prot" : "wine", "__pclass" : { "$type" : "80", "$binary" : "VXBwZXJDbGFzcw==" } }

Deserialization from BSON

The legacy mongo extension deserialized both BSON documents and arrays as PHP arrays. While PHP arrays are convenient to work with, this behavior was problematic because different BSON types could deserialize to the same PHP value (e.g. {"0": "foo"} and ["foo"]) and make it impossible to infer the original BSON type. By default, the current driver addresses this concern by ensuring that BSON arrays and documents are converted to PHP arrays and objects, respectively.

For compound types, there are three data types:

root
refers to the top-level BSON document only

document
refers to embedded BSON documents only

array
refers to a BSON array

Besides the three collective types, it is also possible to configure specific fields in your document to map to the data types mentioned below. As an example, the following type map allows you to map each embedded document within an "addresses" array to an Address class and each "city" field within those embedded address documents to a City class:

[
    'fieldPaths' => [
        'addresses.$' => 'MyProject\Address',
        'addresses.$.city' => 'MyProject\City',
    ],
]

Each of those three data types, as well as the field specific mappings, can be mapped against different PHP types. The possible mapping values are:

not set or NULL (default)

  • A BSON array will be deserialized as a PHP array.

  • A BSON document (root or embedded) without a __pclass property [1] becomes a PHP stdClass object, with each BSON document key set as a public stdClass property.

  • A BSON document (root or embedded) with a __pclass property [1] becomes a PHP object of the class name as defined by the __pclass property.

    If the named class implements the MongoDB\BSON\Persistable interface, then the properties of the BSON document, including the __pclass property, are sent as an associative array to the MongoDB\BSON\Unserializable::bsonUnserialize function to initialise the object's properties.

    If the named class does not exist or does not implement the MongoDB\BSON\Persistable interface, stdClass will be used and each BSON document key (including __pclass) will be set as a public stdClass property.

    The __pclass functionality relies on the property being part of a retrieved MongoDB document. If you use a projection when querying for documents, you need to include the __pclass field in the projection for this functionality to work.

"array"
Turns a BSON array or BSON document into a PHP array. There will be no special treatment of a __pclass property [1], but it may be set as an element in the returned array if it was present in the BSON document.

"object" or "stdClass"
Turns a BSON array or BSON document into a stdClass object. There will be no special treatment of a __pclass property [1], but it may be set as a public property in the returned object if it was present in the BSON document.

any other string
Defines the class name that the BSON array or BSON object should be deserialized as. For BSON objects that include __pclass properties, that class will take priority.

If the named class does not exist, is not concrete (i.e. it is abstract or an interface), or does not implement MongoDB\BSON\Unserializable then an MongoDB\Driver\Exception\InvalidArgumentException exception is thrown.

If the BSON object has a __pclass property and that class exists and implements MongoDB\BSON\Persistable it will supersede the class provided in the type map.

The properties of the BSON document, including the __pclass property if it exists, will be sent as an associative array to the MongoDB\BSON\Unserializable::bsonUnserialize function to initialise the object's properties.

TypeMaps

TypeMaps can be set through the MongoDB\Driver\Cursor::setTypeMap method on a MongoDB\Driver\Cursor object, or the $typeMap argument of MongoDB\BSON\toPHP. Each of the three classes (root, document, and array) can be individually set, in addition to the field specific types.

If the value in the map is NULL, it means the same as the default value for that item.

Examples

These examples use the following classes:

MyClass
which does not implement any interface

YourClass
which implements MongoDB\BSON\Unserializable

OurClass
which implements MongoDB\BSON\Persistable

TheirClass
which extends OurClass

The MongoDB\BSON\Unserializable::bsonUnserialize method of YourClass, OurClass, TheirClass iterate over the array and set the properties without modifications. It also sets the $unserialized property to true:

<?php

function bsonUnserialize( array $map )
{
    foreach ( $map as $k => $value )
    {
        $this->$k = $value;
    }
    $this->unserialized = true;
}
/* typemap: [] (all defaults) */
{ "foo": "yes", "bar" : false }
  -> stdClass { $foo => 'yes', $bar => false }

{ "foo": "no", "array" : [ 5, 6 ] }
  -> stdClass { $foo => 'no', $array => [ 5, 6 ] }

{ "foo": "no", "obj" : { "embedded" : 3.14 } }
  -> stdClass { $foo => 'no', $obj => stdClass { $embedded => 3.14 } }

{ "foo": "yes", "__pclass": "MyClass" }
  -> stdClass { $foo => 'yes', $__pclass => 'MyClass' }

{ "foo": "yes", "__pclass": { "$type" : "80", "$binary" : "MyClass" } }
  -> stdClass { $foo => 'yes', $__pclass => Binary(0x80, 'MyClass') }

{ "foo": "yes", "__pclass": { "$type" : "80", "$binary" : "YourClass") }
  -> stdClass { $foo => 'yes', $__pclass => Binary(0x80, 'YourClass') }

{ "foo": "yes", "__pclass": { "$type" : "80", "$binary" : "OurClass") }
  -> OurClass { $foo => 'yes', $__pclass => Binary(0x80, 'OurClass'), $unserialized => true }

{ "foo": "yes", "__pclass": { "$type" : "44", "$binary" : "YourClass") }
  -> stdClass { $foo => 'yes', $__pclass => Binary(0x44, 'YourClass') }
/* typemap: [ "root" => "MissingClass" ] */
{ "foo": "yes" }
  -> MongoDB\Driver\Exception\InvalidArgumentException("MissingClass does not exist")

/* typemap: [ "root" => "MyClass" ] */
{ "foo": "yes", "__pclass" : { "$type": "80", "$binary": "MyClass" } }
  -> MongoDB\Driver\Exception\InvalidArgumentException("MyClass does not implement Unserializable interface")

/* typemap: [ "root" => "MongoDB\BSON\Unserializable" ] */
{ "foo": "yes" }
  -> MongoDB\Driver\Exception\InvalidArgumentException("Unserializable is not a concrete class")

/* typemap: [ "root" => "YourClass" ] */
{ "foo": "yes", "__pclass" : { "$type": "80", "$binary": "MongoDB\BSON\Unserializable" } }
  -> YourClass { $foo => "yes", $__pclass => Binary(0x80, "MongoDB\BSON\Unserializable"), $unserialized => true }

/* typemap: [ "root" => "YourClass" ] */
{ "foo": "yes", "__pclass" : { "$type": "80", "$binary": "MyClass" } }
  -> YourClass { $foo => "yes", $__pclass => Binary(0x80, "MyClass"), $unserialized => true }

/* typemap: [ "root" => "YourClass" ] */
{ "foo": "yes", "__pclass" : { "$type": "80", "$binary": "OurClass" } }
  -> OurClass { $foo => "yes", $__pclass => Binary(0x80, "OurClass"), $unserialized => true }

/* typemap: [ "root" => "YourClass" ] */
{ "foo": "yes", "__pclass" : { "$type": "80", "$binary": "TheirClass" } }
  -> TheirClass { $foo => "yes", $__pclass => Binary(0x80, "TheirClass"), $unserialized => true }

/* typemap: [ "root" => "OurClass" ] */
{ foo: "yes", "__pclass" : { "$type": "80", "$binary": "TheirClass" } }
  -> TheirClass { $foo => "yes", $__pclass => Binary(0x80, "TheirClass"), $unserialized => true }
/* typemap: [ 'root' => 'YourClass' ] */
{ foo: "yes", "__pclass" : { "$type": "80", "$binary": "YourClass" } }
  -> YourClass { $foo => 'yes', $__pclass => Binary(0x80, 'YourClass'), $unserialized => true }
/* typemap: [ 'root' => 'array', 'document' => 'array' ] */
{ "foo": "yes", "bar" : false }
  -> [ "foo" => "yes", "bar" => false ]

{ "foo": "no", "array" : [ 5, 6 ] }
  -> [ "foo" => "no", "array" => [ 5, 6 ] ]

{ "foo": "no", "obj" : { "embedded" : 3.14 } }
  -> [ "foo" => "no", "obj" => [ "embedded => 3.14 ] ]

{ "foo": "yes", "__pclass": "MyClass" }
  -> [ "foo" => "yes", "__pclass" => "MyClass" ]

{ "foo": "yes", "__pclass" : { "$type": "80", "$binary": "MyClass" } }
  -> [ "foo" => "yes", "__pclass" => Binary(0x80, "MyClass") ]

{ "foo": "yes", "__pclass" : { "$type": "80", "$binary": "OurClass" } }
  -> [ "foo" => "yes", "__pclass" => Binary(0x80, "OurClass") ]
/* typemap: [ 'root' => 'object', 'document' => 'object' ] */
{ "foo": "yes", "__pclass": { "$type": "80", "$binary": "MyClass" } }
  -> stdClass { $foo => "yes", "__pclass" => Binary(0x80, "MyClass") }

[1] A __pclass property is only deemed to exist if there exists a property with that name, and it is a Binary value, and the sub-type of the Binary value is 0x80. If any of these three conditions is not met, the __pclass property does not exist and should be treated as any other normal property.

Security

目录

Request Injection Attacks

If you are passing $_GET (or $_POST) parameters to your queries, make sure that they are cast to strings first. Users can insert associative arrays in GET and POST requests, which could then become unwanted $-queries.

A fairly innocuous example: suppose you are looking up a user's information with the request http://www.example.com?username=bob. Your application creates the query $q = new \MongoDB\Driver\Query( [ 'username' => $_GET['username'] ]).

Someone could subvert this by getting http://www.example.com?username[$ne]=foo, which PHP will magically turn into an associative array, turning your query into $q = new \MongoDB\Driver\Query( [ 'username' => [ '$ne' => 'foo' ] ] ), which will return all users not named "foo" (all of your users, probably).

This is a fairly easy attack to defend against: make sure $_GET and $_POST parameters are the type you expect before you send them to the database. PHP has the filter_var function to assist with this.

Note that this type of attack can be used with any database interaction that locates a document, including updates, upserts, deletes, and findAndModify commands.

See » the main documentation for more information about SQL-injection-like issues with MongoDB.

Script Injection Attacks

If you are using JavaScript, make sure that any variables that cross the PHP- to-JavaScript boundry are passed in the scope field of MongoDB\BSON\Javascript, not interpolated into the JavaScript string. This can come up when using $where clauses in queries, mapReduce and group commands, and any other time you may pass JavaScript into the database.

For example, suppose we have some JavaScript to greet a user in the database logs. We could do:

<?php
$m = new MongoDB\Driver\Manager;

// Don't do this!!!
$username = $_GET['field']; 

$cmd = new \MongoDB\Driver\Command( [
    'eval' => "print('Hello, $username!');"
] );

$r = $m->executeCommand( 'dramio', $cmd );
?>

However, what if a malicious user passes in some JavaScript?

<?php
$m = new MongoDB\Driver\Manager;

// Don't do this!!!
$username = $_GET['field']; 
// $username is set to "'); db.users.drop(); print('"

$cmd = new \MongoDB\Driver\Command( [
    'eval' => "print('Hello, $username!');"
] );

$r = $m->executeCommand( 'dramio', $cmd );
?>

Now MongoDB executes the JavaScript string "print('Hello, '); db.users.drop(); print('!');". This attack is easy to avoid: use args to pass variables from PHP to JavaScript:

<?php
$m = new MongoDB\Driver\Manager;

$_GET['field'] = 'derick';
$args = [ $_GET['field'] ];

$cmd = new \MongoDB\Driver\Command( [
    'eval' => "function greet(username) { print('Hello, ' + username + '!'); }",
    'args' => $args,
] );

$r = $m->executeCommand( 'dramio', $cmd );
?>

This adds an argument to the JavaScript scope, which gets used as argument for the greet function. Now if someone tries to send malicious code, MongoDB will harmlessly print Hello, '); db.dropDatabase(); print('!.

Using arguments helps to prevent malicious input from being executed by the database. However, you must make sure that your code does not turn around and execute the input anyway! It is best to avoid executing any JavaScript on the server in the first place.

You are strongly recommended to stay clear of the » $where clause with queries, as it impacts performance significantly. Where possible, use either normal query operators, or the » Aggregation Framework.

As alternative to » MapReduce, which uses JavaScript, consider using the » Aggregation Framework. Unlike Map/Reduce, it uses an idiomatic language to construct queries, without having to write, and use, the slower JavaScript approach that Map/Reduce requires.

The » eval command has been deprecated since MongoDB 3.0, and should also be avoided.

MongoDB 驱动类

目录

简介

The MongoDB\Driver\Manager is the main entry point to the extension. It is responsible for maintaining connections to MongoDB (be it standalone server, replica set, or sharded cluster).

No connection to MongoDB is made upon instantiating the Manager. This means the MongoDB\Driver\Manager can always be constructed, even though one or more MongoDB servers are down.

Any write or query can throw connection exceptions as connections are created lazily. A MongoDB server may also become unavailable during the life time of the script. It is therefore important that all actions on the Manager to be wrapped in try/catch statements.

类摘要

MongoDB\Driver\Manager

final class MongoDB\Driver\Manager {

/* 方法 */

final public __construct ([ string $uri = "mongodb://127.0.0.1/" [, array $uriOptions = array() [, array $driverOptions = array() ]]] )

final public MongoDB\Driver\ClientEncryption createClientEncryption ( array $options )

final public MongoDB\Driver\WriteResult executeBulkWrite ( string $namespace , MongoDB\Driver\BulkWrite $bulk [, array $options = array() ] )

final public MongoDB\Driver\Cursor executeCommand ( string $db , MongoDB\Driver\Command $command [, array $options = array() ] )

final public MongoDB\Driver\Cursor executeQuery ( string $namespace , MongoDB\Driver\Query $query [, array $options = array() ] )

final public MongoDB\Driver\Cursor executeReadCommand ( string $db , MongoDB\Driver\Command $command [, array $options = array() ] )

final public MongoDB\Driver\Cursor executeReadWriteCommand ( string $db , MongoDB\Driver\Command $command [, array $options = array() ] )

final public MongoDB\Driver\Cursor executeWriteCommand ( string $db , MongoDB\Driver\Command $command [, array $options = array() ] )

final public MongoDB\Driver\ReadConcern getReadConcern ( void )

final public MongoDB\Driver\ReadPreference getReadPreference ( void )

final public array getServers ( void )

final public MongoDB\Driver\WriteConcern getWriteConcern ( void )

final public MongoDB\Driver\Server selectServer ( MongoDB\Driver\ReadPreference $readPreference )

final public MongoDB\Driver\Session startSession ([ array $options ] )

}

范例

示例 #1 MongoDB\Driver\Manager::__construct basic example

var_dumping a MongoDB\Driver\Manager will print out various details about the manager that are otherwise not normally exposed. This can be useful to debug how the driver views your MongoDB setup, and which options are used.

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
var_dump($manager);

?>

以上例程的输出类似于:

object(MongoDB\Driver\Manager)#1 (3) {
  ["request_id"]=>
  int(1714636915)
  ["uri"]=>
  string(25) "mongodb://localhost:27017"
  ["cluster"]=>
  array(13) {
    ["mode"]=>
    string(6) "direct"
    ["state"]=>
    string(4) "born"
    ["request_id"]=>
    int(0)
    ["sockettimeoutms"]=>
    int(300000)
    ["last_reconnect"]=>
    int(0)
    ["uri"]=>
    string(25) "mongodb://localhost:27017"
    ["requires_auth"]=>
    int(0)
    ["nodes"]=>
    array(...)
    ["max_bson_size"]=>
    int(16777216)
    ["max_msg_size"]=>
    int(50331648)
    ["sec_latency_ms"]=>
    int(15)
    ["peers"]=>
    array(0) {
    }
    ["replSet"]=>
    NULL
  }
}

MongoDB\Driver\Manager::__construct

Create new MongoDB Manager

说明

final public MongoDB\Driver\Manager::__construct ([ string $uri = "mongodb://127.0.0.1/" [, array $uriOptions = array() [, array $driverOptions = array() ]]] )

Constructs a new MongoDB\Driver\Manager object with the specified options.

Note: Per the » Server Discovery and Monitoring Specification, this constructor performs no I/O. Connections will be initialized on demand, when the first operation is executed.

Note: When specifying any SSL or TLS URI options via the connection string or uriOptions parameter, the driver will implicitly enable TLS for its connections. To avoid this, either explicitly disable the tls option or don't specify any TLS options.

Note: On Unix platforms, the MongoDB driver is sensitive to scripts that use the fork() system call without also calling exec(). Users are advised not to re-use class="classname">MongoDB\Driver\Manager instances in a forked child process.

参数

uri
A » mongodb:// connection URI:

mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]

For details on supported options, see » Connection String Options in the MongoDB manual. » Connection pool options are not supported, as the PHP driver does not implement connection pools.

The uri is a URL, hence any special characters in its components need to be URL 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 rawurlencode function may be used to encode constituent parts of the URI.

uriOptions
Additional » connection string options, which will overwrite any options with the same name in the uri parameter.

uriOptions
Option Type Description
appname string

MongoDB 3.4+ has the ability to annotate connections with metadata provided by the connecting client. This metadata is included in the server's logs upon establishing a connection and also recorded in slow query logs when database profiling is enabled.

This option may be used to specify an application name, which will be included in the metadata. The value cannot exceed 128 characters in length.

authMechanism string

The authentication mechanism that MongoDB will use to authenticate the connection. For additional details and a list of supported values, see » Authentication Options in the MongoDB manual.

authMechanismProperties array

Properties for the selected authentication mechanism. For additional details and a list of supported properties, see the » Driver Authentication Specification.

Note: When not specified in the URI string, this option is expressed as an array of key/value pairs. The keys and values in this array should be strings.

authSource string

The database name associated with the user's credentials. Defaults to the database component of the connection URI.

For authentication mechanisms that delegate credential storage to other services (e.g. GSSAPI), this should be "$external".

canonicalizeHostname boolean

If TRUE, the driver will resolve the real hostname for the server IP address before authenticating via SASL. Some underlying GSSAPI layers already do this, but the functionality may be disabled in their config (e.g. krb.conf). Defaults to FALSE.

This option is a deprecated alias for the "CANONICALIZE_HOST_NAME" property of the "authMechanismProperties" URI option.

compressors string

A prioritized, comma-delimited list of compressors that the client wants to use. Messages are only compressed if the client and server share any compressors in common, and the compressor used in each direction will depend on the individual configuration of the server or driver. See the » Driver Compression Specification for more information.

connectTimeoutMS integer

The time in milliseconds to attempt a connection before timing out. Defaults to 10,000 milliseconds.

gssapiServiceName string

Set the Kerberos service name when connecting to Kerberized MongoDB instances. This value must match the service name set on MongoDB instances (i.e. » saslServiceName server parameter). Defaults to "mongodb".

This option is a deprecated alias for the "SERVICE_NAME" property of the "authMechanismProperties" URI option.

heartbeatFrequencyMS integer

Specifies the interval in milliseconds between the driver's checks of the MongoDB topology, counted from the end of the previous check until the beginning of the next one. Defaults to 60,000 milliseconds.

Per the » Server Discovery and Monitoring Specification, this value cannot be less than 500 milliseconds.

journal boolean

Corresponds to the default write concern's journal parameter. If TRUE, writes will require acknowledgement from MongoDB that the operation has been written to the journal. For details, see MongoDB\Driver\WriteConcern.

localThresholdMS integer

The size in milliseconds of the latency window for selecting among multiple suitable MongoDB instances while resolving a read preference. Defaults to 15 milliseconds.

maxStalenessSeconds integer

Corresponds to the read preference's "maxStalenessSeconds". Specifies, in seconds, how stale a secondary can be before the client stops using it for read operations. By default, there is no maximum staleness and clients will not consider a secondary’s lag when choosing where to direct a read operation. For details, see MongoDB\Driver\ReadPreference.

If specified, the max staleness must be a signed 32-bit integer greater than or equal to MongoDB\Driver\ReadPreference::SMALLEST_MAX_STALENESS_SECONDS (i.e. 90 seconds).

password string The password for the user being authenticated. This option is useful if the password contains special characters, which would otherwise need to be URL encoded for the connection URI.
readConcernLevel string Corresponds to the read concern's level parameter. Specifies the level of read isolation. For details, see MongoDB\Driver\ReadConcern.
readPreference string

Corresponds to the read preference's mode parameter. Defaults to "primary". For details, see MongoDB\Driver\ReadPreference.

readPreferenceTags array

Corresponds to the read preference's tagSets parameter. Tag sets allow you to target read operations to specific members of a replica set. For details, see MongoDB\Driver\ReadPreference.

Note: When not specified in the URI string, this option is expressed as an array consistent with the format expected by MongoDB\Driver\ReadPreference::__construct.

replicaSet string

Specifies the name of the replica set.

retryReads boolean

Specifies whether or not the driver should automatically retry certain read operations that fail due to transient network errors or replica set elections. This functionality requires MongoDB 3.6+. Defaults to TRUE.

See the » Retryable Reads Specification for more information.

retryWrites boolean

Specifies whether or not the driver should automatically retry certain write operations that fail due to transient network errors or replica set elections. This functionality requires MongoDB 3.6+. Defaults to TRUE.

See » Retryable Writes in the MongoDB manual for more information.

safe boolean

If TRUE, specifies 1 for the default write concern's w parameter. If FALSE, 0 is specified. For details, see MongoDB\Driver\WriteConcern.

This option is deprecated and should not be used.

serverSelectionTimeoutMS integer

Specifies how long in milliseconds to block for server selection before throwing an exception. Defaults to 30,000 milliseconds.

serverSelectionTryOnce boolean

When TRUE, instructs the driver to scan the MongoDB deployment exactly once after server selection fails and then either select a server or raise an error. When FALSE, the driver blocks and searches for a server up to the "serverSelectionTimeoutMS" value. Defaults to TRUE.

slaveOk boolean

Specifies "secondaryPreferred" for the read preference mode if TRUE. For details, see MongoDB\Driver\ReadPreference.

This option is deprecated and should not be used.

socketCheckIntervalMS integer

If a socket has not been used recently, the driver must check it via an isMaster command before using it for any operation. Defaults to 5,000 milliseconds.

socketTimeoutMS integer

The time in milliseconds to attempt a send or receive on a socket before timing out. Defaults to 300,000 milliseconds (i.e. five minutes).

ssl boolean

Initiates the connection with TLS/SSL if TRUE. Defaults to FALSE.

This option is a deprecated alias for the "tls" URI option.

tls boolean

Initiates the connection with TLS/SSL if TRUE. Defaults to FALSE.

tlsAllowInvalidCertificates boolean

Specifies whether or not the driver should error when the server's TLS certificate is invalid. Defaults to FALSE.

Warning

Disabling certificate validation creates a vulnerability.

tlsAllowInvalidHostnames boolean

Specifies whether or not the driver should error when there is a mismatch between the server's hostname and the hostname specified by the TLS certificate. Defaults to FALSE.

Warning

Disabling certificate validation creates a vulnerability. Allowing invalid hostnames may expose the driver to a » man-in-the-middle attack.

tlsCAFile string

Path to file with either a single or bundle of certificate authorities to be considered trusted when making a TLS connection. The system certificate store will be used by default.

tlsCertificateKeyFile string

Path to the client certificate file or the client private key file; in the case that they both are needed, the files should be concatenated.

tlsCertificateKeyFilePassword string

Password to decrypt the client private key (i.e. "tlsCertificateKeyFile" URI option) to be used for TLS connections.

tlsInsecure boolean

Relax TLS constraints as much as possible. Specifying TRUE for this option has the same effect as specifying TRUE for both the tlsAllowInvalidCertificates and "tlsAllowInvalidHostnames" URI options. Defaults to FALSE.

Warning

Disabling certificate validation creates a vulnerability. Allowing invalid hostnames may expose the driver to a » man-in-the-middle attack.

username string The username for the user being authenticated. This option is useful if the username contains special characters, which would otherwise need to be URL encoded for the connection URI.
w integer|string

Corresponds to the default write concern's w parameter. For details, see MongoDB\Driver\WriteConcern.

wTimeoutMS integer|string

Corresponds to the default write concern's wtimeout parameter. Specifies a time limit, in milliseconds, for the write concern. For details, see MongoDB\Driver\WriteConcern.

If specified, wTimeoutMS must be a signed 32-bit integer greater than or equal to zero.

zlibCompressionLevel integer

Specifies the compression level to use for the zlib compressor. This option has no effect if zlib is not included in the "compressors" URI option. See the » Driver Compression Specification for more information.

driverOptions

driverOptions
Option Type Description
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.

This option is a deprecated alias for the "tlsAllowInvalidHostnames" URI option.

autoEncryption array

Provides options to enable automatic client-side field level encryption. The following options are supported:

Options for automatic encryption
Option Type Description
keyVaultClient MongoDB\Driver\Manager The Manager used to route data key queries to a separate MongoDB cluster. By default, the current Manager and cluster is used.
keyVaultNamespace string A fully qualified namespace (e.g. "databaseName.collectionName") denoting the collection that contains all data keys used for encryption and decryption.
kmsProviders array

A document containing the configuration for one or more KMS providers, which are used to encrypt data keys. Currently aws or localare supported and at least one must be specified.

The format for aws is as follows:

aws: {
    accessKeyId: <string>,
    secretAccessKey: <string>
}

The format for local is as follows:

local: {
    // The master key used to encrypt/decrypt data keys
    key: <96-byte MongoDB\BSON\Binary with subtype 0>
}
schemaMap array

Allows specifying a local JSON schema that is used to configure encryption.

Note: Supplying a schemaMap provides more security than relying on JSON schemas obtained from the server. It protects against a malicious server advertising a false JSON schema, which could trick the client into sending unencrypted data that should be encrypted.

Note: Schemas supplied in the schemaMap only apply to configuring automatic encryption for client side encryption. Other validation rules in the JSON schema will not be enforced by the driver and will result in an error.

bypassAutoEncryption boolean With this option set to TRUE, mongocryptd will not be spawned automatically. This is used to disable automatic encryption.
extraOptions array The extraOptions relate to the mongocryptd process. See the » Client-Side Encryption Specification for more information.

Note: Automatic encryption is an enterprise only feature that only applies to operations on a collection. Automatic encryption is not supported for operations on a database or view, and operations that are not bypassed will result in error. To bypass automatic encryption for all operations, set bypassAutoEncryption=true in autoEncryption. For more information on whitelisted operations, see the » Client-Side Encryption Specification.

ca_dir string

Path to a correctly hashed certificate directory. The system certificate store will be used by default.

ca_file string

Path to file with either a single or bundle of certificate authorities to be considered trusted when making a TLS connection. The system certificate store will be used by default.

This option is a deprecated alias for the "tlsCAFile" URI option.

context resource

SSL context options to be used as fallbacks if a driver option or its equivalent URI option, if any, is not specified. Note that the driver does not consult the default stream context (i.e. stream_context_get_default). The following context options are supported:

SSL context option fallbacks
Driver option Context option (fallback)
ca_dir capath
ca_file cafile
pem_file local_cert
pem_pwd passphrase
weak_cert_validation allow_self_signed

This option is supported for backwards compatibility, but should be considered deprecated.

crl_file string Path to a certificate revocation list file.
driver array

Allows custom drivers to append their own metadata to the server handshake. By default, the driver submits its own name, its version as well as the PHP version to the handshake. Drivers can submit their own name, version, and platform information in this array.

Note: Handshake information is limited to 512 bytes. The driver will truncate handshake data to fit within this 512 byte string. Drivers and ODMs are encouraged to keep their own metadata concise.

pem_file string

Path to a PEM encoded certificate to use for client authentication.

This option is a deprecated alias for the "tlsCertificateKeyFile" URI option.

pem_pwd string

Passphrase for the PEM encoded certificate (if applicable).

This option is a deprecated alias for the "tlsCertificateKeyFilePassword" URI option.

weak_cert_validation boolean

Disables certificate validation if TRUE. Defaults to FALSE

This option is a deprecated alias for the "tlsAllowInvalidHostnames" URI option.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\RuntimeException if the uri format is invalid

更新日志

版本 说明
1.7.0

Added the "autoEncryption" driver option.

Specifying any SSL or TLS option via the driverOptions parameter will now implicitly enable TLS, as is done for the corresponding URI options.

1.8.0

Added the "driver" driver option.

1.6.0

Added the "retryReads", "tls", "tlsAllowInvalidCertificates", "tlsAllowInvalidHostnames", "tlsCAFile", "tlsCertificateKeyFile", "tlsCertificateKeyFilePassword", and "tlsInsecure" URI options.

The "retryWrites" URI option defaults to TRUE.

Specifying any SSL or TLS URI option via the connection string or uriOptions parameter will now implicitly enable TLS unless ssl or tls is FALSE. TLS is not implicitly enabled for any options in the driverOptions parameter, which is unchanged from previous versions.

1.5.0

"wtimeoutMS" is now always validated and applied to the write concern. Previously, the option was ignored if "w" was <= 1, since the timeout only applies to replication.

1.4.0

Added the "compressors", "retryWrites", and "zlibCompressionLevel" URI options.

1.3.0

The uriOptions argument now accepts "authMechanism" and "authMechanismProperties" options. Previously, these options were only supported in the uri argument.

1.2.0

The uri argument defaults to "mongodb://127.0.0.1/". The default port remains 27017.

Added the "appname" URI option.

Added the "allow_invalid_hostname", "ca_file", "ca_dir", "clr_file", "pem_file", "pem_pwd", and "weak_cert_validation" driver options.

The PHP Streams API is no longer used for socket communication. The "connectTimeoutMS" URI option now defaults to 10 seconds instead of default_socket_timeout in previous versions. Additionally, the driver no longer supports all SSL context options via the "context" driver option.

1.1.0

The uri argument is optional and defaults to "mongodb://localhost:27017/".

范例

示例 #1 MongoDB\Driver\Manager::__construct basic examples

Connecting to standalone MongoDB node:

<?php

$manager = new MongoDB\Driver\Manager("mongodb://example.com:27017");

?>

Connecting to standalone MongoDB node via a Unix domain socket. The socket path may include special characters such as slashes and should be encoded with rawurlencode.

<?php

$manager = new MongoDB\Driver\Manager("mongodb://" . rawurlencode("/tmp/mongodb-27017.sock"));

?>

Connecting to a replica set:

<?php

$manager = new MongoDB\Driver\Manager("mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet");

?>

Connecting to a sharded cluster (i.e. one or more mongos instances):

<?php

$manager = new MongoDB\Driver\Manager("mongodb://mongos1.example.com,mongos2.example.com/");

?>

Connecting to MongoDB with authentication credentials for a particular user and database:

<?php

$manager = new MongoDB\Driver\Manager("mongodb://myusername:mypassword@example.com/mydatabase");

?>

Connecting to MongoDB with authentication credentials for a particular user and database, where the username or password includes special characters (e.g. @, :, %). In the following example, the password string myp@ss:w%rd has been manually escaped; however, rawurlencode may also be used to escape URI components that may contain special characters.

<?php

$manager = new MongoDB\Driver\Manager("mongodb://myusername:myp%40ss%3Aw%25rd@example.com/mydatabase");

?>

Connecting to MongoDB with X509 authentication:

<?php

$manager = new MongoDB\Driver\Manager(
    "mongodb://example.com/?ssl=true&authMechanism=MONGODB-X509",
    [],
    [
        "pem_file" => "/path/to/client.pem",
    ]
);
?>

参见

MongoDB\Driver\Manager::createClientEncryption

Create a new ClientEncryption object

说明

final public MongoDB\Driver\ClientEncryption MongoDB\Driver\Manager::createClientEncryption ( array $options )

Constructs a new MongoDB\Driver\ClientEncryption object with the specified options.

参数

options

options
Option Type Description
keyVaultClient MongoDB\Driver\Manager The Manager used to route data key queries to a separate MongoDB cluster. By default, the current Manager and cluster is used.
keyVaultNamespace string A fully qualified namespace (e.g. "databaseName.collectionName") denoting the collection that contains all data keys used for encryption and decryption.
kmsProviders array

A document containing the configuration for one or more KMS providers, which are used to encrypt data keys. Currently aws or localare supported and at least one must be specified.

The format for aws is as follows:

aws: {
    accessKeyId: <string>,
    secretAccessKey: <string>
}

The format for local is as follows:

local: {
    // The master key used to encrypt/decrypt data keys
    key: <96-byte MongoDB\BSON\Binary with subtype 0>
}

返回值

Returns a new MongoDB\Driver\ClientEncryption instance.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\RuntimeException if the extension was compiled without libmongocrypt support

参见

MongoDB\Driver\Manager::executeBulkWrite

Execute one or more write operations

说明

final public MongoDB\Driver\WriteResult MongoDB\Driver\Manager::executeBulkWrite ( string $namespace , MongoDB\Driver\BulkWrite $bulk [, array $options = array() ] )

Executes one or more write operations on the primary server.

A MongoDB\Driver\BulkWrite can be constructed with one or more write operations of varying types (e.g. updates, deletes, and inserts). The driver will attempt to send operations of the same type to the server in as few requests as possible to optimize round trips.

参数

namespace (string)
A fully qualified namespace (e.g. "databaseName.collectionName").

bulk (MongoDB\Driver\BulkWrite)
The write(s) to execute.

options
| Option | Type | Description | |--------------|--------------------------------------------------------------|--------------------------------------------| | session | MongoDB\Driver\Session | A session to associate with the operation. | | writeConcern | MongoDB\Driver\WriteConcern | A write concern to apply to the operation. |

返回值

Returns MongoDB\Driver\WriteResult on success.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException if bulk does not contain any write operations.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if bulk has already been executed. MongoDB\Driver\BulkWrite objects may not be executed multiple times.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used in combination with an unacknowledged write concern.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\BulkWriteException on any write failure (e.g. write error, failure to apply a write concern)
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors.

更新日志

版本说明
1.4.4MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the "session" option is used in combination with an unacknowledged write concern.
1.4.0The third parameter is now an options array. For backwards compatibility, this paramater will still accept a MongoDB\Driver\WriteConcern object.
1.3.0MongoDB\Driver\Exception\InvalidArgumentException is now thrown if bulk does not contain any write operations. Previously, a MongoDB\Driver\Exception\BulkWriteException was thrown.

范例

示例 #1 MongoDB\Driver\Manager::executeBulkWrite example

<?php

$bulk = new MongoDB\Driver\BulkWrite();

$bulk->insert(['_id' => 1, 'x' => 1]);
$bulk->insert(['_id' => 2, 'x' => 2]);

$bulk->update(['x' => 2], ['$set' => ['x' => 1]], ['multi' => false, 'upsert' => false]);
$bulk->update(['x' => 3], ['$set' => ['x' => 3]], ['multi' => false, 'upsert' => true]);
$bulk->update(['_id' => 3], ['$set' => ['x' => 3]], ['multi' => false, 'upsert' => true]);

$bulk->insert(['_id' => 4, 'x' => 2]);

$bulk->delete(['x' => 1], ['limit' => 1]);

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 100);
$result = $manager->executeBulkWrite('db.collection', $bulk, $writeConcern);

printf("Inserted %d document(s)\n", $result->getInsertedCount());
printf("Matched  %d document(s)\n", $result->getMatchedCount());
printf("Updated  %d document(s)\n", $result->getModifiedCount());
printf("Upserted %d document(s)\n", $result->getUpsertedCount());
printf("Deleted  %d document(s)\n", $result->getDeletedCount());

foreach ($result->getUpsertedIds() as $index => $id) {
    printf('upsertedId[%d]: ', $index);
    var_dump($id);
}

/* If the WriteConcern could not be fulfilled */
if ($writeConcernError = $result->getWriteConcernError()) {
    printf("%s (%d): %s\n", $writeConcernError->getMessage(), $writeConcernError->getCode(), var_export($writeConcernError->getInfo(), true));
}

/* If a write could not happen at all */
foreach ($result->getWriteErrors() as $writeError) {
    printf("Operation#%d: %s (%d)\n", $writeError->getIndex(), $writeError->getMessage(), $writeError->getCode());
}
?>

以上例程的输出类似于:

Inserted 3 document(s)
Matched  1 document(s)
Updated  1 document(s)
Upserted 2 document(s)
Deleted  1 document(s)
upsertedId[3]: object(MongoDB\BSON\ObjectId)#5 (1) {
  ["oid"]=>
  string(24) "54d3adc3ce7a792f4d703756"
}
upsertedId[4]: int(3)

参见

  • MongoDB\Driver\BulkWrite
  • MongoDB\Driver\WriteResult
  • MongoDB\Driver\WriteConcern
  • MongoDB\Driver\Server::executeBulkWrite

MongoDB\Driver\Manager::executeCommand

Execute a database command

说明

final public MongoDB\Driver\Cursor MongoDB\Driver\Manager::executeCommand ( string $db , MongoDB\Driver\Command $command [, array $options = array() ] )

Selects a server according to the "readPreference" option and executes the command on that server. By default, the read preference from the MongoDB Connection URI will be used.

This method applies no special logic to the command. Although this method accepts "readConcern" and "writeConcern" options, which will be incorporated into the command document, those options will not default to corresponding values from the MongoDB Connection URI nor will the MongoDB server version be taken into account. Users are therefore encouraged to use specific read and/or write command methods if possible.

参数

db (string)
The name of the database on which to execute the command.

command (MongoDB\Driver\Command)
The command to execute.

options

options
Option Type Description
readConcern MongoDB\Driver\ReadConcern

A read concern to apply to the operation.

This option is available in MongoDB 3.2+ and will result in an exception at execution time if specified for an older server version.

readPreference MongoDB\Driver\ReadPreference

A read preference to use for selecting a server for the operation.

session MongoDB\Driver\Session

A session to associate with the operation.

writeConcern MongoDB\Driver\WriteConcern

A write concern to apply to the operation.

Warning If you are using a "session" which has a transaction in progress, you cannot specify a "readConcern" or "writeConcern" option. This will result in an MongoDB\Driver\Exception\InvalidArgumentException being thrown. Instead, you should set these two options when you create the transaction with MongoDB\Driver\Session::startTransaction.

返回值

Returns MongoDB\Driver\Cursor on success.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used with an associated transaction in combination with a "readConcern" or "writeConcern" option.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used in combination with an unacknowledged write concern.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command, issuing a write command to a secondary).

更新日志

版本说明
1.4.4MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the "session" option is used in combination with an unacknowledged write concern.
1.4.0The third parameter is now an options array. For backwards compatibility, this paramater will still accept a MongoDB\Driver\ReadPreference object.

范例

示例 #1 MongoDB\Driver\Manager::executeCommand with a command returning a single result document

<?php

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$command = new MongoDB\Driver\Command(['ping' => 1]);

try {
    $cursor = $manager->executeCommand('admin', $command);
} catch(MongoDB\Driver\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

/* The ping command returns a single result document, so we need to access the
 * first result in the cursor. */
$response = $cursor->toArray()[0];

var_dump($response);

?>

以上例程会输出:

array(1) {
  ["ok"]=>
  float(1)
}

示例 #2 MongoDB\Driver\Manager::executeCommand with a command returning a cursor

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1, 'y' => 'foo']);
$bulk->insert(['x' => 2, 'y' => 'bar']);
$bulk->insert(['x' => 3, 'y' => 'bar']);
$manager->executeBulkWrite('db.collection', $bulk);

$command = new MongoDB\Driver\Command([
    'aggregate' => 'collection',
    'pipeline' => [
        ['$group' => ['_id' => '$y', 'sum' => ['$sum' => '$x']]],
    ],
    'cursor' => new stdClass,
]);
$cursor = $manager->executeCommand('db', $command);

/* The aggregate command can optionally return its results in a cursor instead
 * of a single result document. In this case, we can iterate on the cursor
 * directly to access those results. */
foreach ($cursor as $document) {
    var_dump($document);
}

?>

以上例程会输出:

object(stdClass)#6 (2) {
  ["_id"]=>
  string(3) "bar"
  ["sum"]=>
  int(10)
}
object(stdClass)#7 (2) {
  ["_id"]=>
  string(3) "foo"
  ["sum"]=>
  int(2)
}

示例 #3 Limiting execution time for a command

The execution time of a command may be limited by specifying a value for "maxTimeMS" in the MongoDB\Driver\Command document. Note that this time limit is enforced on the server side and does not take network latency into account. See » Terminate Running Operations in the MongoDB manual for more information.

<?php

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');

$command = new MongoDB\Driver\Command([
    'count' => 'collection',
    'query' => ['x' => ['$gt' => 1]],
    'maxTimeMS' => 1000,
]);

$cursor = $manager->executeCommand('db', $command);

var_dump($cursor->toArray()[0]);

?>

If the command fails to complete after one second of execution time on the server, a MongoDB\Driver\Exception\ExecutionTimeoutException will be thrown.

注释

Note: If a secondary readPreference is used, it is the caller's responsibility to ensure that the command can be executed on a secondary. No validation is done by the driver.

参见

  • MongoDB\Driver\Command
  • MongoDB\Driver\Cursor
  • MongoDB\Driver\Manager::executeReadCommand
  • MongoDB\Driver\Manager::executeReadWriteCommand
  • MongoDB\Driver\Manager::executeWriteCommand
  • MongoDB\Driver\Server::executeCommand

MongoDB\Driver\Manager::executeQuery

Execute a database query

说明

final public MongoDB\Driver\Cursor MongoDB\Driver\Manager::executeQuery ( string $namespace , MongoDB\Driver\Query $query [, array $options = array() ] )

Selects a server according to the "readPreference" option and executes the query on that server. By default, the read preference from the MongoDB Connection URI will be used.

参数

namespace (string)
A fully qualified namespace (e.g. "databaseName.collectionName").

query (MongoDB\Driver\Query)
The query to execute.

options
| Option | Type | Description | |----------------|----------------------------------------------------------------|--------------------------------------------------------------------| | readPreference | MongoDB\Driver\ReadPreference | A read preference to use for selecting a server for the operation. | | session | MongoDB\Driver\Session | A session to associate with the operation. |

返回值

Returns MongoDB\Driver\Cursor on success.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid query operators).

更新日志

版本说明
1.4.0The third parameter is now an options array. For backwards compatibility, this paramater will still accept a MongoDB\Driver\ReadPreference object.

范例

示例 #1 MongoDB\Driver\Manager::executeQuery example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->insert(['x' => 2]);
$bulk->insert(['x' => 3]);
$manager->executeBulkWrite('db.collection', $bulk);

$filter = ['x' => ['$gt' => 1]];
$options = [
    'projection' => ['_id' => 0],
    'sort' => ['x' => -1],
];

$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery('db.collection', $query);

foreach ($cursor as $document) {
    var_dump($document);
}

?>

以上例程会输出:

object(stdClass)#6 (1) {
  ["x"]=>
  int(3)
}
object(stdClass)#7 (1) {
  ["x"]=>
  int(2)
}

示例 #2 Limiting execution time for a query

The "maxTimeMS" MongoDB\Driver\Query option may be used to limit the execution time of a query. Note that this time limit is enforced on the server side and does not take network latency into account. See » Terminate Running Operations in the MongoDB manual for more information.

<?php

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');

$filter = ['x' => ['$gt' => 1]];
$options = [
    'maxTimeMS' => 1000,
];

$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery('db.collection', $query);

foreach ($cursor as $document) {
    var_dump($document);
}

?>

If the query fails to complete after one second of execution time on the server, a MongoDB\Driver\Exception\ExecutionTimeoutException will be thrown.

参见

  • MongoDB\Driver\Cursor
  • MongoDB\Driver\Query
  • MongoDB\Driver\ReadPreference
  • MongoDB\Driver\Server::executeQuery

MongoDB\Driver\Manager::executeReadCommand

Execute a database command that reads

说明

final public MongoDB\Driver\Cursor MongoDB\Driver\Manager::executeReadCommand ( string $db , MongoDB\Driver\Command $command [, array $options = array() ] )

Selects a server according to the "readPreference" option and executes the command on that server. By default, the read preference from the MongoDB Connection URI will be used.

This method will apply logic that is specific to commands that read (e.g. » count) and take the MongoDB server version into account. The "readConcern" option will default to the corresponding value from the MongoDB Connection URI.

参数

db (string)
The name of the database on which to execute the command.

command (MongoDB\Driver\Command)
The command to execute.

options

options
Option Type Description
readConcern MongoDB\Driver\ReadConcern

A read concern to apply to the operation.

This option is available in MongoDB 3.2+ and will result in an exception at execution time if specified for an older server version.

readPreference MongoDB\Driver\ReadPreference

A read preference to use for selecting a server for the operation.

session MongoDB\Driver\Session

A session to associate with the operation.

Warning If you are using a "session" which has a transaction in progress, you cannot specify a "readConcern" or "writeConcern" option. This will result in an MongoDB\Driver\Exception\InvalidArgumentException being thrown. Instead, you should set these two options when you create the transaction with MongoDB\Driver\Session::startTransaction.

返回值

Returns MongoDB\Driver\Cursor on success.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used with an associated transaction in combination with a "readConcern" or "writeConcern" option.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command).

参见

  • MongoDB\Driver\Command
  • MongoDB\Driver\Cursor
  • MongoDB\Driver\Manager::executeCommand
  • MongoDB\Driver\Manager::executeReadWriteCommand
  • MongoDB\Driver\Manager::executeWriteCommand
  • MongoDB\Driver\Server::executeReadCommand

MongoDB\Driver\Manager::executeReadWriteCommand

Execute a database command that reads and writes

说明

final public MongoDB\Driver\Cursor MongoDB\Driver\Manager::executeReadWriteCommand ( string $db , MongoDB\Driver\Command $command [, array $options = array() ] )

Executes the command on the primary server.

This method will apply logic that is specific to commands that read and write (e.g. » findAndModify) and take the MongoDB server version into account. The "readConcern" and "writeConcern" options will default to the corresponding values from the MongoDB Connection URI.

参数

db (string)
The name of the database on which to execute the command.

command (MongoDB\Driver\Command)
The command to execute.

options

options
Option Type Description
readConcern MongoDB\Driver\ReadConcern

A read concern to apply to the operation.

This option is available in MongoDB 3.2+ and will result in an exception at execution time if specified for an older server version.

session MongoDB\Driver\Session

A session to associate with the operation.

writeConcern MongoDB\Driver\WriteConcern

A write concern to apply to the operation.

Warning If you are using a "session" which has a transaction in progress, you cannot specify a "readConcern" or "writeConcern" option. This will result in an MongoDB\Driver\Exception\InvalidArgumentException being thrown. Instead, you should set these two options when you create the transaction with MongoDB\Driver\Session::startTransaction.

返回值

Returns MongoDB\Driver\Cursor on success.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used with an associated transaction in combination with a "readConcern" or "writeConcern" option.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used in combination with an unacknowledged write concern.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command).

更新日志

版本说明
1.4.4MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the "session" option is used in combination with an unacknowledged write concern.

参见

  • MongoDB\Driver\Command
  • MongoDB\Driver\Cursor
  • MongoDB\Driver\Manager::executeCommand
  • MongoDB\Driver\Manager::executeReadCommand
  • MongoDB\Driver\Manager::executeWriteCommand
  • MongoDB\Driver\Server::executeReadWriteCommand

MongoDB\Driver\Manager::executeWriteCommand

Execute a database command that writes

说明

final public MongoDB\Driver\Cursor MongoDB\Driver\Manager::executeWriteCommand ( string $db , MongoDB\Driver\Command $command [, array $options = array() ] )

Executes the command on the primary server.

This method will apply logic that is specific to commands that write (e.g. » drop) and take the MongoDB server version into account. The "writeConcern" option will default to the corresponding value from the MongoDB Connection URI.

Note: This method is not intended to be used to execute » insert, » update, or » delete commands. Users are encouraged to use class="function">MongoDB\Driver\Manager::executeBulkWrite for those commands.

参数

db (string)
The name of the database on which to execute the command.

command (MongoDB\Driver\Command)
The command to execute.

options
| Option | Type | Description | |--------------|--------------------------------------------------------------|--------------------------------------------| | session | MongoDB\Driver\Session | A session to associate with the operation. | | writeConcern | MongoDB\Driver\WriteConcern | A write concern to apply to the operation. |

Warning If you are using a "session" which has a transaction in progress, you cannot specify a "readConcern" or "writeConcern" option. This will result in an MongoDB\Driver\Exception\InvalidArgumentException being thrown. Instead, you should set these two options when you create the transaction with MongoDB\Driver\Session::startTransaction.

返回值

Returns MongoDB\Driver\Cursor on success.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used with an associated transaction in combination with a "readConcern" or "writeConcern" option.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used in combination with an unacknowledged write concern.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command).

更新日志

版本说明
1.4.4MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the "session" option is used in combination with an unacknowledged write concern.

参见

  • MongoDB\Driver\Command
  • MongoDB\Driver\Cursor
  • MongoDB\Driver\Manager::executeCommand
  • MongoDB\Driver\Manager::executeReadCommand
  • MongoDB\Driver\Manager::executeReadWriteCommand
  • MongoDB\Driver\Server::executeWriteCommand

MongoDB\Driver\Manager::getReadConcern

Return the ReadConcern for the Manager

说明

final public MongoDB\Driver\ReadConcern MongoDB\Driver\Manager::getReadConcern ( void )

Returns the MongoDB\Driver\ReadConcern for the Manager, which is derived from its URI options. This is the default read concern for queries and commands executed on the Manager.

参数

此函数没有参数。

返回值

The MongoDB\Driver\ReadConcern for the Manager.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\Manager::getReadConcern example

<?php

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
var_dump($manager->getReadConcern());

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017/?readConcernLevel=local');
var_dump($manager->getReadConcern());

?>

以上例程的输出类似于:

object(MongoDB\Driver\ReadConcern)#2 (0) {
}
object(MongoDB\Driver\ReadConcern)#1 (1) {
  ["level"]=>
  string(5) "local"
}

参见

  • MongoDB\Driver\ReadConcern
  • MongoDB\Driver\Manager::__construct

MongoDB\Driver\Manager::getReadPreference

Return the ReadPreference for the Manager

说明

final public MongoDB\Driver\ReadPreference MongoDB\Driver\Manager::getReadPreference ( void )

Returns the MongoDB\Driver\ReadPreference for the Manager, which is derived from its URI options. This is the default read preference for queries and commands executed on the Manager.

参数

此函数没有参数。

返回值

The MongoDB\Driver\ReadPreference for the Manager.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\Manager::getReadPreference example

<?php

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
var_dump($manager->getReadPreference());

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017/?readPreference=secondaryPreferred&readPreferenceTags=dc:ny,rack:1&readPreferenceTags=dc:ny&readPreferenceTags=');
var_dump($manager->getReadPreference());

?>

以上例程的输出类似于:

object(MongoDB\Driver\ReadPreference)#2 (1) {
  ["mode"]=>
  string(7) "primary"
}
object(MongoDB\Driver\ReadPreference)#1 (2) {
  ["mode"]=>
  string(18) "secondaryPreferred"
  ["tags"]=>
  array(3) {
    [0]=>
    object(stdClass)#3 (2) {
      ["dc"]=>
      string(2) "ny"
      ["rack"]=>
      string(1) "1"
    }
    [1]=>
    object(stdClass)#4 (1) {
      ["dc"]=>
      string(2) "ny"
    }
    [2]=>
    object(stdClass)#5 (0) {
    }
  }
}

参见

  • MongoDB\Driver\ReadPreference
  • MongoDB\Driver\Manager::__construct

MongoDB\Driver\Manager::getServers

Return the servers to which this manager is connected

说明

final public array MongoDB\Driver\Manager::getServers ( void )

Returns an array of MongoDB\Driver\Server instances to which this manager is connected.

Note: Since the driver connects to the database lazily, this method may return an empty class="type">array if called before executing an operation on the MongoDB\Driver\Manager.

参数

此函数没有参数。

返回值

Returns an array of MongoDB\Driver\Server instances to which this manager is connected.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\Manager::getServers example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

/* The driver connects to the database server lazily, so Manager::getServers()
 * may initially return an empty array. */
var_dump($manager->getServers());

$command = new MongoDB\Driver\Command(['ping' => 1]);
$manager->executeCommand('db', $command);

var_dump($manager->getServers());

?>

以上例程的输出类似于:

array(0) {
}
array(1) {
  [0]=>
  object(MongoDB\Driver\Server)#3 (10) {
    ["host"]=>
    string(9) "localhost"
    ["port"]=>
    int(27017)
    ["type"]=>
    int(1)
    ["is_primary"]=>
    bool(false)
    ["is_secondary"]=>
    bool(false)
    ["is_arbiter"]=>
    bool(false)
    ["is_hidden"]=>
    bool(false)
    ["is_passive"]=>
    bool(false)
    ["last_is_master"]=>
    array(8) {
      ["ismaster"]=>
      bool(true)
      ["maxBsonObjectSize"]=>
      int(16777216)
      ["maxMessageSizeBytes"]=>
      int(48000000)
      ["maxWriteBatchSize"]=>
      int(1000)
      ["localTime"]=>
      object(MongoDB\BSON\UTCDateTime)#4 (1) {
        ["milliseconds"]=>
        int(1447267964517)
      }
      ["maxWireVersion"]=>
      int(3)
      ["minWireVersion"]=>
      int(0)
      ["ok"]=>
      float(1)
    }
    ["round_trip_time"]=>
    int(554)
  }
}

参见

  • MongoDB\Driver\Server
  • MongoDB\Driver\Manager::selectServer

MongoDB\Driver\Manager::getWriteConcern

Return the WriteConcern for the Manager

说明

final public MongoDB\Driver\WriteConcern MongoDB\Driver\Manager::getWriteConcern ( void )

Returns the MongoDB\Driver\WriteConcern for the Manager, which is derived from its URI options. This is the default write concern for writes and commands executed on the Manager.

参数

此函数没有参数。

返回值

The MongoDB\Driver\WriteConcern for the Manager.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\Manager::getWriteConcern example

<?php

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
var_dump($manager->getWriteConcern());

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017/?w=majority&wtimeoutMS=2000');
var_dump($manager->getWriteConcern());

?>

以上例程的输出类似于:

object(MongoDB\Driver\WriteConcern)#2 (0) {
}
object(MongoDB\Driver\WriteConcern)#1 (2) {
  ["w"]=>
  string(8) "majority"
  ["wtimeout"]=>
  int(2000)
}

参见

  • MongoDB\Driver\WriteConcern
  • MongoDB\Driver\Manager::__construct

MongoDB\Driver\Manager::selectServer

Select a server matching a read preference

说明

final public MongoDB\Driver\Server MongoDB\Driver\Manager::selectServer ( MongoDB\Driver\ReadPreference $readPreference )

Selects a MongoDB\Driver\Server matching readPreference. This may be used to preselect a server in order to perform version checking before executing an operation.

Note: Unlike class="function">MongoDB\Driver\Manager::getServers, this method will initialize database connections and perform server discovery if necessary. See the » Server Selection Specification for additional information.

参数

readPreference (MongoDB\Driver\ReadPreference)
The read preference to use for selecting a server.

返回值

Returns a MongoDB\Driver\Server matching the read preference.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\RuntimeException if a server matching the read preference could not be found.

参见

MongoDB\Driver\Manager::startSession

Start a new client session for use with this client

说明

final public MongoDB\Driver\Session MongoDB\Driver\Manager::startSession ([ array $options ] )

Creates a MongoDB\Driver\Session for the given options. The session may then be specified when executing commands, queries, and write operations.

Note: A class="classname">MongoDB\Driver\Session can only be used with the MongoDB\Driver\Manager from which it was created.

参数

options

options
Option Type Description Default
causalConsistency boolean

Configure causal consistency in a session. If TRUE, each operation in the session will be causally ordered after the previous read or write operation. Set to FALSE to disable causal consistency.

See » Casual Consistency in the MongoDB manual for more information.

TRUE
defaultTransactionOptions array

Default options to apply to newly created transactions. These options are used unless they are overridden when a transaction is started with different value for each option.

options
Option Type Description
maxCommitTimeMS integer

The maximum amount of time in milliseconds to allow a single commitTransaction command to run.

If specified, maxCommitTimeMS must be a signed 32-bit integer greater than or equal to zero.

readConcern MongoDB\Driver\ReadConcern

A read concern to apply to the operation.

This option is available in MongoDB 3.2+ and will result in an exception at execution time if specified for an older server version.

readPreference MongoDB\Driver\ReadPreference

A read preference to use for selecting a server for the operation.

writeConcern MongoDB\Driver\WriteConcern

A write concern to apply to the operation.

This option is available in MongoDB 4.0+.

[]

返回值

Returns a MongoDB\Driver\Session.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\RuntimeException if the session could not be created (e.g. libmongoc does not support crypto).

更新日志

版本说明
1.6.0The "maxCommitTimeMS" option was added to "defaultTransactionOptions".
1.5.0The "defaultTransactionOptions" option was added.

参见

简介

The MongoDB\Driver\Command class is a value object that represents a database command.

To provide “Command Helpers” the MongoDB\Driver\Command object should be composed.

类摘要

MongoDB\Driver\Command

final class MongoDB\Driver\Command {

/* 方法 */

final public __construct ( array|object $document [, array $commandOptions ] )

}

范例

示例 #1 Composing MongoDB\Driver\Command to provide a helper to create collections

<?php
class CreateCollection {
    protected $cmd = array();

    function __construct($collectionName) {
        $this->cmd["create"] = (string)$collectionName;
    }
    function setCappedCollection($maxBytes, $maxDocuments = false) {
        $this->cmd["capped"] = true;
        $this->cmd["size"]   = (int)$maxBytes;

        if ($maxDocuments) {
            $this->cmd["max"] = (int)$maxDocuments;
        }
    }
    function usePowerOf2Sizes($bool) {
        if ($bool) {
            $this->cmd["flags"] = 1;
        } else {
            $this->cmd["flags"] = 0;
        }
    }
    function setFlags($flags) {
        $this->cmd["flags"] = (int)$flags;
    }
    function getCommand() {
        return new MongoDB\Driver\Command($this->cmd);
    }
    function getCollectionName() {
        return $this->cmd["create"];
    }
}


$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

$createCollection = new CreateCollection("cappedCollection");
$createCollection->setCappedCollection(64 * 1024);

try {
    $command = $createCollection->getCommand();
    $cursor = $manager->executeCommand("databaseName", $command);
    $response = $cursor->toArray()[0];
    var_dump($response);

    $collstats = ["collstats" => $createCollection->getCollectionName()];
    $cursor = $manager->executeCommand("databaseName", new MongoDB\Driver\Command($collstats));
    $response = $cursor->toArray()[0];
    var_dump($response);
} catch(MongoDB\Driver\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

?>

以上例程会输出:

object(MongoDB\Driver\Command)#3 (1) {
  ["command"]=>
  array(3) {
    ["create"]=>
    string(16) "cappedCollection"
    ["capped"]=>
    bool(true)
    ["size"]=>
    int(65536)
  }
}
array(1) {
  ["ok"]=>
  float(1)
}
array(16) {
  ["ns"]=>
  string(29) "databaseName.cappedCollection"
  ["count"]=>
  int(0)
  ["size"]=>
  int(0)
  ["numExtents"]=>
  int(1)
  ["storageSize"]=>
  int(65536)
  ["nindexes"]=>
  int(1)
  ["lastExtentSize"]=>
  float(65536)
  ["paddingFactor"]=>
  float(1)
  ["paddingFactorNote"]=>
  string(101) "paddingFactor is unused and unmaintained in 2.8. It remains hard coded to 1.0 for compatibility only."
  ["userFlags"]=>
  int(0)
  ["capped"]=>
  bool(true)
  ["max"]=>
  int(9223372036854775807)
  ["maxSize"]=>
  int(65536)
  ["totalIndexSize"]=>
  int(8176)
  ["indexSizes"]=>
  object(stdClass)#4 (1) {
    ["_id_"]=>
    int(8176)
  }
  ["ok"]=>
  float(1)
}

MongoDB\Driver\Command::__construct

Create a new Command

说明

final public MongoDB\Driver\Command::__construct ( array|object $document [, array $commandOptions ] )

Constructs a new MongoDB\Driver\Command, which is an immutable value object that represents a database command. The command may then be executed with MongoDB\Driver\Manager::executeCommand.

The complete command document, which includes the command name and its options, should be expressed in the document parameter. The commandOptions parameter is only used to specify options related to the execution of the command and the resulting MongoDB\Driver\Cursor.

参数

document
The complete command document, which will be sent to the server.

commandOptions

Note: Do not use this parameter to specify options described in the command's reference in the MongoDB manual. This parameter should only be used for the options explicitly listed below.

OptionTypeDescription
maxAwaitTimeMSintegerPositive 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 in conjunction with commands that return a tailable cursor (e.g. » Change Streams).

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

更新日志

版本说明
1.4.0Added a second commandOptions argument, which supports the "maxAwaitTimeMS" option.

范例

示例 #1 MongoDB\Driver\Command::__construct example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$command = new MongoDB\Driver\Command(array("buildinfo" => 1));

try {
    $cursor = $manager->executeCommand("admin", $command);
    $response = $cursor->toArray()[0];
} catch(MongoDB\Driver\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}
var_dump($response);

?>

以上例程的输出类似于:

array(13) {
  ["version"]=>
  string(14) "2.8.0-rc2-pre-"
  ["gitVersion"]=>
  string(62) "b743d7158f7642f4da6b7eac8320374b3b88dc2e modules: subscription"
  ["OpenSSLVersion"]=>
  string(25) "OpenSSL 1.0.1f 6 Jan 2014"
  ["sysInfo"]=>
  string(104) "Linux infant 3.16.0-24-generic #32-Ubuntu SMP Tue Oct 28 13:07:32 UTC 2014 x86_64 BOOST_LIB_VERSION=1_49"
  ["loaderFlags"]=>
  string(91) "-fPIC -pthread -Wl,-z,now -rdynamic -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-z,now -Wl,-E"
  ["compilerFlags"]=>
  string(301) "-Wnon-virtual-dtor -Woverloaded-virtual -std=c++11 -fPIC -fno-strict-aliasing -ggdb -pthread -Wall -Wsign-compare -Wno-unknown-pragmas -Winvalid-pch -pipe -Werror -O3 -Wno-unused-local-typedefs -Wno-unused-function -Wno-deprecated-declarations -Wno-unused-but-set-variable -fno-builtin-memcmp -std=c99"
  ["allocator"]=>
  string(8) "tcmalloc"
  ["versionArray"]=>
  array(4) {
    [0]=>
    int(2)
    [1]=>
    int(8)
    [2]=>
    int(0)
    [3]=>
    int(-8)
  }
  ["javascriptEngine"]=>
  string(2) "V8"
  ["bits"]=>
  int(64)
  ["debug"]=>
  bool(false)
  ["maxBsonObjectSize"]=>
  int(16777216)
  ["ok"]=>
  float(1)
}

示例 #2 MongoDB\Driver\Command::__construct example

Commands can accept options as well, as part of the normal structure that you create to send to the server. For example, the maxTimeMS option can be passed with most commands to restrict the amount of time a specific command can run for on the server.

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$command = new MongoDB\Driver\Command(
    array(
        "distinct" => "beer",
        "key" => "beer_name",
        "maxTimeMS" => 10,
    )
);

try {
    $cursor = $manager->executeCommand("beerdb", $command);
    $response = $cursor->toArray()[0];
} catch(MongoDB\Driver\Exception\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}
var_dump($response);

?>

以上例程的输出类似于:

operation exceeded time limit

参见

  • MongoDB\Driver\Manager::executeCommand
  • MongoDB\Driver\Cursor

简介

The MongoDB\Driver\Query class is a value object that represents a database query.

类摘要

MongoDB\Driver\Query

final class MongoDB\Driver\Query {

/* 方法 */

final public __construct ( array|object $filter [, array $queryOptions ] )

}

MongoDB\Driver\Query::__construct

Create a new Query

说明

final public MongoDB\Driver\Query::__construct ( array|object $filter [, array $queryOptions ] )

Constructs a new MongoDB\Driver\Query, which is an immutable value object that represents a database query. The query may then be executed with MongoDB\Driver\Manager::executeQuery.

参数

filter (array|object)
The » query predicate. An empty predicate will match all documents in the collection.

Note: When evaluating query criteria, MongoDB compares types and values according to its own » comparison rules for BSON types, which differs from PHP's comparison and type juggling rules. When matching a special BSON type the query criteria should use the respective BSON class (e.g. use MongoDB\BSON\ObjectId to match an » ObjectId).

queryOptions

queryOptions
Option Type Description
allowDiskUse boolean

Allows MongoDB to use temporary disk files to store data exceeding the 100 megabyte system memory limit while processing a blocking sort operation.

allowPartialResults boolean

For queries against a sharded collection, returns partial results from the mongos if some shards are unavailable instead of throwing an error.

Falls back to the deprecated "partial" option if not specified.

awaitData boolean Use in conjunction with the "tailable" option to block a getMore operation on the cursor temporarily if at the end of data rather than returning no data. After a timeout period, the query returns as normal.
batchSize integer

The number of documents to return in the first batch. Defaults to 101. A batch size of 0 means that the cursor will be established, but no documents will be returned in the first batch.

In versions of MongoDB before 3.2, where queries use the legacy wire protocol OP_QUERY, a batch size of 1 will close the cursor irrespective of the number of matched documents.

collation array|object

» 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 » 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.

This option is available in MongoDB 3.4+ and will result in an exception at execution time if specified for an older server version.

comment string

A comment to attach to the query to help interpret and trace query profile data.

Falls back to the deprecated "$comment" modifier if not specified.

exhaust boolean

Stream the data down full blast in multiple "more" packages, on the assumption that the client will fully read all data queried. Faster when you are pulling a lot of data and know you want to pull it all down. Note: the client is not allowed to not read all the data unless it closes the connection.

This option is not supported by the find command in MongoDB 3.2+ and will force the driver to use the legacy wire protocol version (i.e. OP_QUERY).

explain boolean

If TRUE, the returned MongoDB\Driver\Cursor will contain a single document that describes the process and indexes used to return the query.

Falls back to the deprecated "$explain" modifier if not specified.

This option is not supported by the find command in MongoDB 3.2+ and will only be respected when using the legacy wire protocol version (i.e. OP_QUERY). The » explain command should be used on MongoDB 3.0+.

hint string|array|object

Index specification. Specify either the index name as a string or the index key pattern. If specified, then the query system will only consider plans using the hinted index.

Falls back to the deprecated "hint" option if not specified.

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 will be interpreted as a positive limit with the "singleBatch" option set to TRUE. This behavior is supported for backwards compatibility, but should be considered deprecated.

max array|object

The exclusive upper bound for a specific index.

Falls back to the deprecated "$max" modifier if not specified.

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 in conjunction with the "tailable" and "awaitData" options.

maxScan integer
Warning

This option is deprecated and should not be used.

Positive integer denoting the maximum number of documents or index keys to scan when executing the query.

Falls back to the deprecated "$maxScan" modifier if not specified.

maxTimeMS integer

The cumulative time limit in milliseconds for processing operations on the cursor. MongoDB aborts the operation at the earliest following interrupt point.

Falls back to the deprecated "$maxTimeMS" modifier if not specified.

min array|object

The inclusive lower bound for a specific index.

Falls back to the deprecated "$min" modifier if not specified.

modifiers array » Meta operators modifying 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:

[ 'ts' => [ '$gte' => <timestamp> ] ]

Note: This option is deprecated as of the 1.8.0 release.

projection array|object

The » projection specification to determine which fields to include in the returned documents.

If you are using the ODM functionality to deserialise documents as their original PHP class, make sure that you include the __pclass field in the projection. This is required for the deserialization to work and without it, the driver will return (by default) a stdClass object instead.

readConcern MongoDB\Driver\ReadConcern

A read concern to apply to the operation. By default, the read concern from the MongoDB Connection URI will be used.

This option is available in MongoDB 3.2+ and will result in an exception at execution time if specified for an older server version.

returnKey boolean

If TRUE, returns only the index keys in the resulting documents. Default value is FALSE. If TRUE and the find command does not use an index, the returned documents will be empty.

Falls back to the deprecated "$returnKey" modifier if not specified.

showRecordId boolean

Determines whether to return the record identifier for each document. If TRUE, adds a top-level "$recordId" field to the returned documents.

Falls back to the deprecated "$showDiskLoc" modifier if not specified.

singleBatch boolean Determines whether to close the cursor after the first batch. Defaults to FALSE.
skip integer Number of documents to skip. Defaults to 0.
slaveOk boolean Allow query of replica set secondaries
snapshot boolean
Warning

This option is deprecated and should not be used.

Prevents the cursor from returning a document more than once because of an intervening write operation.

Falls back to the deprecated "$snapshot" modifier if not specified.

sort array|object

The sort specification for the ordering of the results.

Falls back to the deprecated "$orderby" modifier if not specified.

tailable boolean Returns a tailable cursor for a capped collection.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

更新日志

版本 说明
1.8.0

Added the "allowDiskUse" option.

The "oplogReplay" option is deprecated.

1.5.0

The "maxScan" and "snapshot" options are deprecated.

1.3.0

Added the "maxAwaitTimeMS" option.

1.2.0

Added the "allowPartialResults", "collation", "comment", "hint", "max", "maxScan", "maxTimeMS", "min", "returnKey", "showRecordId", and "snapshot" options.

Renamed the "partial" option to "allowPartialResults". For backwards compatibility, "partial" will still be read if "allowPartialResults" is not specified.

Removed the "slaveOk" option, which is obsolete. For queries using the legacy wire protocol OP_QUERY, the driver will set the slaveOk bit as needed in accordance with the » Server Selection Specification.

1.1.0 Added the "readConcern" option.

范例

示例 #1 MongoDB\Driver\Query::__construct example

<?php
/* Select only documents authord by "bjori" with at least 100 views */
$filter = [
    'author' => 'bjori',
    'views' => [
        '$gte' => 100,
    ],
];

$options = [
    /* Only return the following fields in the matching documents */
    'projection' => [
        'title' => 1,
        'article' => 1,
    ],
    /* Return the documents in descending order of views */
    'sort' => [
        'views' => -1
    ],
];

$query = new MongoDB\Driver\Query($filter, $options);

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$readPreference = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
$cursor = $manager->executeQuery('databaseName.collectionName', $query, $readPreference);

foreach($cursor as $document) {
    var_dump($document);
}

?>

参见

  • MongoDB\Driver\Manager::executeQuery
  • MongoDB\Driver\Cursor

简介

The MongoDB\Driver\BulkWrite collects one or more write operations that should be sent to the server. After adding any number of insert, update, and delete operations, the collection may be executed via MongoDB\Driver\Manager::executeBulkWrite.

Write operations may either be ordered (default) or unordered. Ordered write operations are sent to the server, in the order provided, for serial execution. If a write fails, any remaining operations will be aborted. Unordered operations are sent to the server in an arbitrary order where they may be executed in parallel. Any errors that occur are reported after all operations have been attempted.

类摘要

MongoDB\Driver\BulkWrite

final class MongoDB\Driver\BulkWrite implements Countable {

/* 方法 */

public __construct ([ array $options ] )

public int count ( void )

public void delete ( array|object $filter [, array $deleteOptions ] )

public mixed insert ( array|object $document )

public void update ( array|object $filter , array|object $newObj [, array $updateOptions ] )

}

范例

示例 #1 Mixed write operations are grouped by type

Mixed write operations (i.e. inserts, updates, and deletes) will be assembled into typed write commands to be sent sequentially to the server.

<?php

$bulk = new MongoDB\Driver\BulkWrite(['ordered' => true]);
$bulk->insert(['_id' => 1, 'x' => 1]);
$bulk->insert(['_id' => 2, 'x' => 2]);
$bulk->update(['x' => 2], ['$set' => ['x' => 1]]);
$bulk->insert(['_id' => 3, 'x' => 3]);
$bulk->delete(['x' => 1]);

?>

Will result in four write commands (i.e. roundtrips) being executed. Since the operations are ordered, the third insertion cannot be sent until the preceding update is executed.

示例 #2 Ordered write operations causing an error

<?php

$bulk = new MongoDB\Driver\BulkWrite(['ordered' => true]);
$bulk->delete([]);
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 2]);
$bulk->insert(['_id' => 3, 'hello' => 'world']);
$bulk->update(['_id' => 3], ['$set' => ['hello' => 'earth']]);
$bulk->insert(['_id' => 4, 'hello' => 'pluto']);
$bulk->update(['_id' => 4], ['$set' => ['hello' => 'moon']]);
$bulk->insert(['_id' => 3]);
$bulk->insert(['_id' => 4]);
$bulk->insert(['_id' => 5]);

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);

try {
    $result = $manager->executeBulkWrite('db.collection', $bulk, $writeConcern);
} catch (MongoDB\Driver\Exception\BulkWriteException $e) {
    $result = $e->getWriteResult();

    // Check if the write concern could not be fulfilled
    if ($writeConcernError = $result->getWriteConcernError()) {
        printf("%s (%d): %s\n",
            $writeConcernError->getMessage(),
            $writeConcernError->getCode(),
            var_export($writeConcernError->getInfo(), true)
        );
    }

    // Check if any write operations did not complete at all
    foreach ($result->getWriteErrors() as $writeError) {
        printf("Operation#%d: %s (%d)\n",
            $writeError->getIndex(),
            $writeError->getMessage(),
            $writeError->getCode()
        );
    }
} catch (MongoDB\Driver\Exception\Exception $e) {
    printf("Other error: %s\n", $e->getMessage());
    exit;
}

printf("Inserted %d document(s)\n", $result->getInsertedCount());
printf("Updated  %d document(s)\n", $result->getModifiedCount());

?>

以上例程会输出:

Operation#7: E11000 duplicate key error index: db.collection.$_id_ dup key: { : 3 } (11000)
Inserted 4 document(s)
Updated  2 document(s)

If the write concern could not be fullfilled, the example above would output something like:

waiting for replication timed out (64): array (
  'wtimeout' => true,
)
Operation#7: E11000 duplicate key error index: databaseName.collectionName.$_id_ dup key: { : 3 } (11000)
Inserted 4 document(s)
Updated  2 document(s)

If we execute the example above, but allow for unordered writes:

<?php

$bulk = new MongoDB\Driver\BulkWrite(['ordered' => false]);
/* ... */

?>

以上例程会输出:

Operation#7: E11000 duplicate key error index: db.collection.$_id_ dup key: { : 3 } (11000)
Operation#8: E11000 duplicate key error index: db.collection.$_id_ dup key: { : 4 } (11000)
Inserted 5 document(s)
Updated  2 document(s)

参见

  • MongoDB\Driver\Manager::executeBulkWrite
  • MongoDB\Driver\WriteResult
  • MongoDB\Driver\WriteConcern
  • MongoDB\Driver\WriteConcernError
  • MongoDB\Driver\WriteError

MongoDB\Driver\BulkWrite::__construct

Create a new BulkWrite

说明

public MongoDB\Driver\BulkWrite::__construct ([ array $options ] )

Constructs a new MongoDB\Driver\BulkWrite, which is a mutable object to which one or more write operations may be added. The write(s) may then be executed with MongoDB\Driver\Manager::executeBulkWrite.

参数

options (array)

options
Option Type Description Default
bypassDocumentValidation boolean

If TRUE, allows insert and update operations to circumvent document level validation.

This option is available in MongoDB 3.2+ and is ignored for older server versions, which do not support document level validation.

FALSE
ordered boolean Ordered operations (TRUE) are executed serially on the MongoDB server, while unordered operations (FALSE) are sent to the server in an arbitrary order and may be executed in parallel. TRUE

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

更新日志

版本说明
1.1.0Added the "bypassDocumentValidation" option.

范例

示例 #1 MongoDB\Driver\BulkWrite::__construct example

<?php

$bulk = new MongoDB\Driver\BulkWrite(['ordered' => true]);
$bulk->delete([]);
$bulk->insert(['_id' => 1, 'x' => 1]);
$bulk->insert(['_id' => 2, 'x' => 2]);
$bulk->update(
    ['x' => 2],
    ['$set' => ['x' => 1]],
    ['limit' => 1, 'upsert' => false]
);
$bulk->delete(['x' => 1], ['limit' => 1]);
$bulk->update(
    ['_id' => 3],
    ['$set' => ['x' => 3]],
    ['limit' => 1, 'upsert' => true]
);

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$writeConcern = new MongoDB\Driver\WriteConcern(1);

try {
    $result = $manager->executeBulkWrite('db.collection', $bulk, $writeConcern);
} catch (MongoDB\Driver\Exception\BulkWriteException $e) {
    $result = $e->getWriteResult();

    // Check if the write concern could not be fulfilled
    if ($writeConcernError = $result->getWriteConcernError()) {
        printf("%s (%d): %s\n",
            $writeConcernError->getMessage(),
            $writeConcernError->getCode(),
            var_export($writeConcernError->getInfo(), true)
        );
    }

    // Check if any write operations did not complete at all
    foreach ($result->getWriteErrors() as $writeError) {
        printf("Operation#%d: %s (%d)\n",
            $writeError->getIndex(),
            $writeError->getMessage(),
            $writeError->getCode()
        );
    }
} catch (MongoDB\Driver\Exception\Exception $e) {
    printf("Other error: %s\n", $e->getMessage());
    exit;
}

printf("Inserted %d document(s)\n", $result->getInsertedCount());
printf("Updated  %d document(s)\n", $result->getModifiedCount());
printf("Upserted %d document(s)\n", $result->getUpsertedCount());
printf("Deleted  %d document(s)\n", $result->getDeletedCount());

?>

以上例程会输出:

Inserted 2 document(s)
Updated  1 document(s)
Upserted 1 document(s)
Deleted  1 document(s)

参见

  • MongoDB\Driver\Manager::executeBulkWrite
  • MongoDB\Driver\WriteResult

MongoDB\Driver\BulkWrite::count

Count number of write operations in the bulk

说明

public int MongoDB\Driver\BulkWrite::count ( void )

Returns the number of write operations added to the MongoDB\Driver\BulkWrite object.

参数

此函数没有参数。

返回值

Returns number of write operations added to the MongoDB\Driver\BulkWrite object.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

更新日志

版本说明
1.2.0Returns the number of write operations added to the MongoDB\Driver\BulkWrite object. Earlier versions returned the expected number of client-to-server roundtrips required to execute all write operations.

范例

示例 #1 MongoDB\Driver\BulkWrite::count example

<?php

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['_id' => 1, 'x' => 1]);
$bulk->insert(['_id' => 2, 'x' => 2]);
$bulk->update(['x' => 2], ['$set' => ['x' => 1]]);
$bulk->delete(['x' => 1]);

var_dump(count($bulk));

?>

以上例程会输出:

int(4)

MongoDB\Driver\BulkWrite::delete

Add a delete operation to the bulk

说明

public void MongoDB\Driver\BulkWrite::delete ( array|object $filter [, array $deleteOptions ] )

Adds a delete operation to the MongoDB\Driver\BulkWrite.

参数

filter (array|object)
The » query predicate. An empty predicate will match all documents in the collection.

Note: When evaluating query criteria, MongoDB compares types and values according to its own » comparison rules for BSON types, which differs from PHP's comparison and type juggling rules. When matching a special BSON type the query criteria should use the respective BSON class (e.g. use MongoDB\BSON\ObjectId to match an » ObjectId).

deleteOptions

deleteOptions
Option Type Description Default
collation array|object

» 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 » 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.

This option is available in MongoDB 3.4+ and will result in an exception at execution time if specified for an older server version.

limit boolean Delete all matching documents (FALSE), or only the first matching document (TRUE) FALSE

返回值

没有返回值。

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

更新日志

版本说明
1.2.0Added the "collation" option.

范例

示例 #1 MongoDB\Driver\BulkWrite::delete example

<?php

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->delete(['x' => 1], ['limit' => 1]);
$bulk->delete(['x' => 2], ['limit' => 0]);

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$result = $manager->executeBulkWrite('db.collection', $bulk);

?>

参见

  • MongoDB\Driver\Manager::executeBulkWrite
  • MongoDB\Driver\WriteResult

MongoDB\Driver\BulkWrite::insert

Add an insert operation to the bulk

说明

public mixed MongoDB\Driver\BulkWrite::insert ( array|object $document )

Adds an insert operation to the MongoDB\Driver\BulkWrite.

参数

document (array|object)
A document to insert.

返回值

Returns the _id of the inserted document. If the document did not have an _id, the MongoDB\BSON\ObjectId generated for the insert will be returned.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

更新日志

版本说明
1.3.0The _id of the inserted document is always returned. Previously, the method only returned a value if a MongoDB\BSON\ObjectId was generated.

范例

示例 #1 MongoDB\Driver\BulkWrite::insert example

<?php

$bulk = new MongoDB\Driver\BulkWrite;

$document1 = ['title' => 'one'];
$document2 = ['_id' => 'custom ID', 'title' => 'two'];
$document3 = ['_id' => new MongoDB\BSON\ObjectId, 'title' => 'three'];

$_id1 = $bulk->insert($document1);
$_id2 = $bulk->insert($document2);
$_id3 = $bulk->insert($document3);

var_dump($_id1, $_id2, $_id3);

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$result = $manager->executeBulkWrite('db.collection', $bulk);

?>

以上例程的输出类似于:

object(MongoDB\BSON\ObjectId)#3 (1) {
  ["oid"]=>
  string(24) "54d51146bd21b91405401d92"
}
NULL
NULL

参见

  • MongoDB\Driver\Manager::executeBulkWrite
  • MongoDB\Driver\WriteResult
  • MongoDB\BSON\ObjectId
  • MongoDB\BSON\Persistable

MongoDB\Driver\BulkWrite::update

Add an update operation to the bulk

说明

public void MongoDB\Driver\BulkWrite::update ( array|object $filter , array|object $newObj [, array $updateOptions ] )

Adds an update operation to the MongoDB\Driver\BulkWrite.

参数

filter (array|object)
The » query predicate. An empty predicate will match all documents in the collection.

Note: When evaluating query criteria, MongoDB compares types and values according to its own » comparison rules for BSON types, which differs from PHP's comparison and type juggling rules. When matching a special BSON type the query criteria should use the respective BSON class (e.g. use MongoDB\BSON\ObjectId to match an » ObjectId).

newObj (array|object)
A document containing either update operators (e.g. $set), a replacement document (i.e. only field:value expressions), or an » aggregation pipeline.

updateOptions

updateOptions
Option Type Description Default
arrayFilters array

An array of filter documents that determines which array elements to modify for an update operation on an array field. See » Specify arrayFilters for Array Update Operations in the MongoDB manual for more information.

This option is available in MongoDB 3.6+ and will result in an exception at execution time if specified for an older server version.

collation array|object

» 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 » 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.

This option is available in MongoDB 3.4+ and will result in an exception at execution time if specified for an older server version.

hint string|array|object

Index specification. Specify either the index name as a string or the index key pattern. If specified, then the query system will only consider plans using the hinted index.

multi boolean Update only the first matching document if FALSE, or all matching documents TRUE. This option cannot be TRUE if newObj is a replacement document. FALSE
upsert boolean If filter does not match an existing document, insert a single document. The document will be created from newObj if it is a replacement document (i.e. no update operators); otherwise, the operators in newObj will be applied to filter to create the new document. FALSE

返回值

没有返回值。

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

更新日志

版本说明
1.6.0The newObj parameter now accepts an aggregation pipeline. This feature requires MongoDB 4.2+ and will result in an exception at execution time if specified for an older server version.
1.5.0Using the "arrayFilters" option will result in an exception at execution time if unsupported by the server. Previously, no exception would be thrown and the option may have been ignored.
1.4.0Added the "arrayFilters" option.
1.2.0Added the "collation" option.

范例

示例 #1 MongoDB\Driver\BulkWrite::update example

<?php

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->update(
    ['x' => 2],
    ['$set' => ['y' => 3]],
    ['multi' => false, 'upsert' => false]
);

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$result = $manager->executeBulkWrite('db.collection', $bulk);

?>

参见

  • MongoDB\Driver\Manager::executeBulkWrite
  • MongoDB\Driver\WriteResult

简介

MongoDB\Driver\WriteConcern describes the level of acknowledgement requested from MongoDB for write operations to a standalone mongod or to replica sets or to sharded clusters. In sharded clusters, mongos instances will pass the write concern on to the shards.

类摘要

MongoDB\Driver\WriteConcern

final class MongoDB\Driver\WriteConcern implements MongoDB\BSON\Serializable , Serializable {

/* Constants */

const string MongoDB\Driver\WriteConcern::MAJORITY = "majority" ;

/* 方法 */

final public object bsonSerialize ( void )

final public __construct ( string|integer $w [, int $wtimeout [, bool $journal ]] )

final public boolean|null getJournal ( void )

final public string|integer|null getW ( void )

final public int|MongoDB\BSON\Int64 getWtimeout ( void )

final public bool isDefault ( void )

final public string serialize ( void )

final public void unserialize ( string $serialized )

}

预定义常量

MongoDB\Driver\WriteConcern::MAJORITY
Majority of all the members in the set; arbiters, non-voting members, passive members, hidden members and delayed members are all included in the definition of majority write concern.

更新日志

版本说明
1.7.0Implements Serializable.
1.2.0Implements MongoDB\BSON\Serializable.

MongoDB\Driver\WriteConcern::bsonSerialize

Returns an object for BSON serialization

说明

final public object MongoDB\Driver\WriteConcern::bsonSerialize ( void )

参数

此函数没有参数。

返回值

Returns an object for serializing the WriteConcern as BSON.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\WriteConcern::bsonSerialize with majority write concern

<?php

$wc = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY);
var_dump($wc->bsonSerialize());

echo "\n", MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($wc));

?>

以上例程的输出类似于:

object(stdClass)#2 (1) {
  ["w"]=>
  string(8) "majority"
}

{ "w" : "majority" }

示例 #2 MongoDB\Driver\WriteConcern::bsonSerialize with wtimeout and journal

<?php

$wc = new MongoDB\Driver\WriteConcern(2, 1000, true);
var_dump($wc->bsonSerialize());

echo "\n", MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($wc));

?>

以上例程的输出类似于:

object(stdClass)#2 (3) {
  ["w"]=>
  int(2)
  ["j"]=>
  bool(true)
  ["wtimeout"]=>
  int(1000)
}

{ "w" : 2, "j" : true, "wtimeout" : 1000 }

参见

MongoDB\Driver\WriteConcern::__construct

Create a new WriteConcern

说明

final public MongoDB\Driver\WriteConcern::__construct ( string|integer $w [, int $wtimeout [, bool $journal ]] )

Constructs a new MongoDB\Driver\WriteConcern, which is an immutable value object.

参数

w

Write concern
Value Description
1 Requests acknowledgement that the write operation has propagated to the standalone mongod or the primary in a replica set. This is the default write concern for MongoDB.
0 Requests no acknowledgment of the write operation. However, this may return information about socket exceptions and networking errors to the application.
<integer greater than 1> Numbers greater than 1 are valid only for replica sets to request acknowledgement from specified number of members, including the primary.
MongoDB\Driver\WriteConcern::MAJORITY

Requests acknowledgment that write operations have propagated to the majority of voting nodes, including the primary, and have been written to the on-disk journal for these nodes.

Prior to MongoDB 3.0, this refers to the majority of replica set members (not just voting nodes).

string A string value is interpereted as a tag set. Requests acknowledgement that the write operations have propagated to a replica set member with the specified tag.

wtimeout
How long to wait (in milliseconds) for secondaries before failing.

wtimeout causes write operations to return with an error (WriteConcernError) after the specified limit, even if the required write concern will eventually succeed. When these write operations return, MongoDB does not undo successful data modifications performed before the write concern exceeded the wtimeout time limit.

If specified, wtimeout must be a signed 64-bit integer greater than or equal to zero.

ValueDescription
0Block indefinitely. This is the default.
<integer greater than 0>Milliseconds to wait until returning.

journal
Wait until mongod has applied the write to the journal.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if w is invalid or wtimeout is either negative or greater than the bounds of a signed 32-bit integer.

更新日志

版本说明
1.7.0The wTimeout parameter now accepts 64-bit values.

范例

示例 #1 MongoDB\Driver\WriteConcern::__construct example

<?php

/* Request write acknowledgement from the majority of the replica set nodes */
$wc = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 500);

/* Request write acknowledgement from a node configured with the "MultipleDC" tag */
$wc = new MongoDB\Driver\WriteConcern("MultipleDC", 500);

?>

参见

MongoDB\Driver\WriteConcern::getJournal

Returns the WriteConcern's "journal" option

说明

final public boolean|null MongoDB\Driver\WriteConcern::getJournal ( void )

参数

此函数没有参数。

返回值

Returns the WriteConcern's "journal" option.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\WriteConcern::getJournal example

<?php

$wc = new MongoDB\Driver\WriteConcern(1);
var_dump($wc->getJournal());

$wc = new MongoDB\Driver\WriteConcern(1, 0, true);
var_dump($wc->getJournal());

$wc = new MongoDB\Driver\WriteConcern(1, 0, false);
var_dump($wc->getJournal());

?>

以上例程会输出:

NULL
bool(true)
bool(false)

参见

MongoDB\Driver\WriteConcern::getW

Returns the WriteConcern's "w" option

说明

final public string|integer|null MongoDB\Driver\WriteConcern::getW ( void )

参数

此函数没有参数。

返回值

Returns the WriteConcern's "w" option.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\WriteConcern::getW example

<?php

$wc = new MongoDB\Driver\WriteConcern(1);
var_dump($wc->getW());

$wc = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY);
var_dump($wc->getW());

?>

以上例程会输出:

int(1)
string(8) "majority"

参见

MongoDB\Driver\WriteConcern::getWtimeout

Returns the WriteConcern's "wtimeout" option

说明

final public int|MongoDB\BSON\Int64 MongoDB\Driver\WriteConcern::getWtimeout ( void )

参数

此函数没有参数。

返回值

Returns the WriteConcern's "wtimeout" option.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

更新日志

版本说明
1.7.0On 32-bit systems, this method will return a MongoDB\BSON\Int64 instance if the WriteConcern object was created with a wTimeout that exceeds the 32-bit range. On 64-bit systems, this method will always return an integer value.

范例

示例 #1 MongoDB\Driver\WriteConcern::getWtimeout example

<?php

$wc = new MongoDB\Driver\WriteConcern(1);
var_dump($wc->getWtimeout());

$wc = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 3000);
var_dump($wc->getWtimeout());

?>

以上例程会输出:

int(0)
int(3000)

参见

MongoDB\Driver\WriteConcern::isDefault

Checks if this is the default write concern

说明

final public bool MongoDB\Driver\WriteConcern::isDefault ( void )

Returns whether this is the default write concern (i.e. no options are specified). This method is primarily intended to be used in conjunction with MongoDB\Driver\Manager::getWriteConcern to determine whether the Manager has been constructed without any write concern options.

The driver will not include a default write concern in its write operations (e.g. MongoDB\Driver\Manager::executeBulkWrite) in order to allow the server to apply its own default, which may have been » modified. Libraries that access the Manager's write concern to include it in their own write commands should use this method to ensure that default write concerns are left unset.

参数

此函数没有参数。

返回值

Returns TRUE if this is the default write concern and FALSE otherwise.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\WriteConcern::isDefault example

<?php

$wc = new MongoDB\Driver\WriteConcern(1);
var_dump($wc->isDefault());

$manager = new MongoDB\Driver\Manager('mongodb://127.0.0.1/?w=majority');
$wc = $manager->getWriteConcern();
var_dump($wc->isDefault());

$manager = new MongoDB\Driver\Manager('mongodb://127.0.0.1/');
$wc = $manager->getWriteConcern();
var_dump($wc->isDefault());

?>

以上例程会输出:

bool(false)
bool(false)
bool(true)

参见

MongoDB\Driver\WriteConcern::serialize

Serialize a WriteConcern

说明

final public string MongoDB\Driver\WriteConcern::serialize ( void )

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\Driver\WriteConcern.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

MongoDB\Driver\WriteConcern::unserialize

Unserialize a WriteConcern

说明

final public void MongoDB\Driver\WriteConcern::unserialize ( string $serialized )

参数

serialized
The serialized MongoDB\Driver\WriteConcern.

返回值

Returns the unserialized MongoDB\Driver\WriteConcern.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

参见

简介

类摘要

MongoDB\Driver\ReadPreference

final class MongoDB\Driver\ReadPreference implements MongoDB\BSON\Serializable , Serializable {

/* Constants */

const integer MongoDB\Driver\ReadPreference::RP_PRIMARY = 1 ;

const integer MongoDB\Driver\ReadPreference::RP_PRIMARY_PREFERRED = 5 ;

const integer MongoDB\Driver\ReadPreference::RP_SECONDARY = 2 ;

const integer MongoDB\Driver\ReadPreference::RP_SECONDARY_PREFERRED = 6 ;

const integer MongoDB\Driver\ReadPreference::RP_NEAREST = 10 ;

const string MongoDB\Driver\ReadPreference::PRIMARY = primary ;

const string MongoDB\Driver\ReadPreference::PRIMARY_PREFERRED = primaryPreferred ;

const string MongoDB\Driver\ReadPreference::SECONDARY = secondary ;

const string MongoDB\Driver\ReadPreference::SECONDARY_PREFERRED = secondaryPreferred ;

const string MongoDB\Driver\ReadPreference::NEAREST = nearest ;

const integer MongoDB\Driver\ReadPreference::NO_MAX_STALENESS = -1 ;

const integer MongoDB\Driver\ReadPreference::SMALLEST_MAX_STALENESS_SECONDS = 90 ;

/* 方法 */

final public object bsonSerialize ( void )

final public __construct ( string|integer $mode [, array $tagSets = NULL [, array $options = array() ]] )

final public int getMaxStalenessSeconds ( void )

final public int getMode ( void )

final public string getModeString ( void )

final public array getTagSets ( void )

final public string serialize ( void )

final public void unserialize ( string $serialized )

}

预定义常量

MongoDB\Driver\ReadPreference::RP_PRIMARY
All operations read from the current replica set primary. This is the default read preference for MongoDB.

MongoDB\Driver\ReadPreference::RP_PRIMARY_PREFERRED
In most situations, operations read from the primary but if it is unavailable, operations read from secondary members.

MongoDB\Driver\ReadPreference::RP_SECONDARY
All operations read from the secondary members of the replica set.

MongoDB\Driver\ReadPreference::RP_SECONDARY_PREFERRED
In most situations, operations read from secondary members but if no secondary members are available, operations read from the primary.

MongoDB\Driver\ReadPreference::RP_NEAREST
Operations read from member of the replica set with the least network latency, irrespective of the member's type.

MongoDB\Driver\ReadPreference::PRIMARY
All operations read from the current replica set primary. This is the default read preference for MongoDB.

MongoDB\Driver\ReadPreference::PRIMARY_PREFERRED
In most situations, operations read from the primary but if it is unavailable, operations read from secondary members.

MongoDB\Driver\ReadPreference::SECONDARY
All operations read from the secondary members of the replica set.

MongoDB\Driver\ReadPreference::SECONDARY_PREFERRED
In most situations, operations read from secondary members but if no secondary members are available, operations read from the primary.

MongoDB\Driver\ReadPreference::NEAREST
Operations read from member of the replica set with the least network latency, irrespective of the member's type.

MongoDB\Driver\ReadPreference::NO_MAX_STALENESS
The default value for the "maxStalenessSeconds" option is to specify no limit on maximum staleness, which means that the driver will not consider a secondary's lag when choosing where to direct a read operation.

MongoDB\Driver\ReadPreference::SMALLEST_MAX_STALENESS_SECONDS
The minimum value for the "maxStalenessSeconds" option is 90 seconds. The driver estimates secondaries' staleness by periodically checking the latest write date of each replica set member. Since these checks are infrequent, the staleness estimate is coarse. Thus, the driver cannot enforce a max staleness value of less than 90 seconds.

更新日志

版本 说明
1.7.0

Added the MongoDB\Driver\ReadPreference::PRIMARY, MongoDB\Driver\ReadPreference::PRIMARY_PREFERRED, MongoDB\Driver\ReadPreference::SECONDARY, MongoDB\Driver\ReadPreference::SECONDARY_PREFERRED, MongoDB\Driver\ReadPreference::NEAREST constants.

Implements Serializable.

1.2.0

Added the MongoDB\Driver\ReadPreference::NO_MAX_STALENESS and MongoDB\Driver\ReadPreference::SMALLEST_MAX_STALENESS_SECONDS constants.

Implements MongoDB\BSON\Serializable.

MongoDB\Driver\ReadPreference::bsonSerialize

Returns an object for BSON serialization

说明

final public object MongoDB\Driver\ReadPreference::bsonSerialize ( void )

参数

此函数没有参数。

返回值

Returns an object for serializing the ReadPreference as BSON.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\ReadPreference::bsonSerialize with primary read preference

<?php

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
var_dump($rp->bsonSerialize());

echo "\n", MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($rp));

?>

以上例程的输出类似于:

object(stdClass)#2 (1) {
  ["mode"]=>
  string(7) "primary"
}

{ "mode" : "primary" }

示例 #2 MongoDB\Driver\ReadPreference::bsonSerialize with secondary read preference and tag sets

<?php

$rp = new MongoDB\Driver\ReadPreference(
    MongoDB\Driver\ReadPreference::RP_SECONDARY,
    [
        ['dc' => 'ny'],
        ['dc' => 'sf', 'use' => 'reporting'],
        []
    ]
);
var_dump($rp->bsonSerialize());

echo "\n", MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($rp));

?>

以上例程的输出类似于:

object(stdClass)#2 (2) {
  ["mode"]=>
  string(9) "secondary"
  ["tags"]=>
  array(3) {
    [0]=>
    object(stdClass)#1 (1) {
      ["dc"]=>
      string(2) "ny"
    }
    [1]=>
    object(stdClass)#5 (2) {
      ["dc"]=>
      string(2) "sf"
      ["use"]=>
      string(9) "reporting"
    }
    [2]=>
    object(stdClass)#4 (0) {
    }
  }
}

{ "mode" : "secondary", "tags" : [ { "dc" : "ny" }, { "dc" : "sf", "use" : "reporting" }, {  } ] }

示例 #3 MongoDB\Driver\ReadPreference::bsonSerialize with secondary read preference and max staleness

<?php

$rp = new MongoDB\Driver\ReadPreference(
    MongoDB\Driver\ReadPreference::RP_SECONDARY,
    null,
    ['maxStalenessSeconds' => 120]
);
var_dump($rp->bsonSerialize());

echo "\n", MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($rp));

?>

以上例程的输出类似于:

object(stdClass)#2 (2) {
  ["mode"]=>
  string(9) "secondary"
  ["maxStalenessSeconds"]=>
  int(120)
}

{ "mode" : "secondary", "maxStalenessSeconds" : 120 }

参见

MongoDB\Driver\ReadPreference::__construct

Create a new ReadPreference

说明

final public MongoDB\Driver\ReadPreference::__construct ( string|integer $mode [, array $tagSets = NULL [, array $options = array() ]] )

Constructs a new MongoDB\Driver\ReadPreference, which is an immutable value object.

参数

mode
| Value | Description | |---------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------| | MongoDB\Driver\ReadPreference::RP_PRIMARY or "primary" | All operations read from the current replica set primary. This is the default read preference for MongoDB. | | MongoDB\Driver\ReadPreference::RP_PRIMARY_PREFERRED or "primaryPreferred" | In most situations, operations read from the primary but if it is unavailable, operations read from secondary members. | | MongoDB\Driver\ReadPreference::RP_SECONDARY or "secondary" | All operations read from the secondary members of the replica set. | | MongoDB\Driver\ReadPreference::RP_SECONDARY_PREFERRED or "secondaryPreferred" | In most situations, operations read from secondary members but if no secondary members are available, operations read from the primary. | | MongoDB\Driver\ReadPreference::RP_NEAREST or "nearest" | Operations read from member of the replica set with the least network latency, irrespective of the member's type. |

tagSets
Tag sets allow you to target read operations to specific members of a replica set. This parameter should be an array of associative arrays, each of which contain zero or more key/value pairs. When selecting a server for a read operation, the driver attempt to select a node having all tags in a set (i.e. the associative array of key/value pairs). If selection fails, the driver will attempt subsequent sets. An empty tag set (array()) will match any node and may be used as a fallback.

Tags are not compatible with the MongoDB\Driver\ReadPreference::RP_PRIMARY mode and, in general, only apply when selecting a secondary member of a set for a read operation. However, the MongoDB\Driver\ReadPreference::RP_NEAREST mode, when combined with a tag set, selects the matching member with the lowest network latency. This member may be a primary or secondary.

options

options
Option Type Description
maxStalenessSeconds integer

Specifies a maximum replication lag, or "staleness", for reads from secondaries. When a secondary's estimated staleness exceeds this value, the driver stops using it for read operations.

If specified, the max staleness must be a signed 32-bit integer greater than or equal to MongoDB\Driver\ReadPreference::SMALLEST_MAX_STALENESS_SECONDS.

Defaults to MongoDB\Driver\ReadPreference::NO_MAX_STALENESS, which means that the driver will not consider a secondary's lag when choosing where to direct a read operation.

This option is not compatible with the MongoDB\Driver\ReadPreference::RP_PRIMARY mode. Specifying a max staleness also requires all MongoDB instances in the deployment to be using MongoDB 3.4+. An exception will be thrown at execution time if any MongoDB instances in the deployment are of an older server version.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if mode is invalid.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if tagSets is provided for a primary read preference or is malformed (i.e. not an array of zero or more documents).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "maxStalenessSeconds" option is provided for a primary read preference or is out of range.

更新日志

版本说明
1.3.0The mode argument now accepts a string value, which is consistent with the "readPreference" URI option for MongoDB\Driver\Manager::__construct.
1.2.0Added a third options argument, which supports the "maxStalenessSeconds" option.

范例

示例 #1 MongoDB\Driver\ReadPreference::__construct example

<?php

/* Prefer a secondary node but fall back to a primary. */
var_dump(new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY_PREFERRED));

/* Prefer a node in the New York data center with lowest latency. */
var_dump(new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_NEAREST, [['dc' => 'ny']]));

/* Require a secondary node whose replication lag is within two minutes of the primary */
var_dump(new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY, null, ['maxStalenessSeconds' => 120]));

?>

以上例程会输出:

object(MongoDB\Driver\ReadPreference)#1 (1) {
  ["mode"]=>
  string(18) "secondaryPreferred"
}
object(MongoDB\Driver\ReadPreference)#1 (2) {
  ["mode"]=>
  string(7) "nearest"
  ["tags"]=>
  array(1) {
    [0]=>
    object(stdClass)#2 (1) {
      ["dc"]=>
      string(2) "ny"
    }
  }
}
object(MongoDB\Driver\ReadPreference)#1 (2) {
  ["mode"]=>
  string(9) "secondary"
  ["maxStalenessSeconds"]=>
  int(120)
}

参见

MongoDB\Driver\ReadPreference::getMaxStalenessSeconds

Returns the ReadPreference's "maxStalenessSeconds" option

说明

final public int MongoDB\Driver\ReadPreference::getMaxStalenessSeconds ( void )

参数

此函数没有参数。

返回值

Returns the ReadPreference's "maxStalenessSeconds" option. If no max staleness has been specified, MongoDB\Driver\ReadPreference::NO_MAX_STALENESS will be returned.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\ReadPreference::getMaxStalenessSeconds example

<?php

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY);
var_dump($rp->getMaxStalenessSeconds());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY, null, [
    'maxStalenessSeconds' => MongoDB\Driver\ReadPreference::NO_MAX_STALENESS,
]);
var_dump($rp->getMaxStalenessSeconds());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY, null, [
    'maxStalenessSeconds' => MongoDB\Driver\ReadPreference::SMALLEST_MAX_STALENESS_SECONDS,
]);
var_dump($rp->getMaxStalenessSeconds());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY, null, [
    'maxStalenessSeconds' => 1000,
]);
var_dump($rp->getMaxStalenessSeconds());

?>

以上例程会输出:

int(-1)
int(-1)
int(90)
int(1000)

参见

MongoDB\Driver\ReadPreference::getMode

Returns the ReadPreference's "mode" option

说明

final public int MongoDB\Driver\ReadPreference::getMode ( void )

参数

此函数没有参数。

返回值

Returns the ReadPreference's "mode" option.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\ReadPreference::getMode example

<?php

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
var_dump($rp->getMode());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY_PREFERRED);
var_dump($rp->getMode());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY);
var_dump($rp->getMode());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY_PREFERRED);
var_dump($rp->getMode());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_NEAREST);
var_dump($rp->getMode());

?>

以上例程会输出:

int(1)
int(5)
int(2)
int(6)
int(10)

参见

MongoDB\Driver\ReadPreference::getModeString

Returns the ReadPreference's "mode" option as a string

说明

final public string MongoDB\Driver\ReadPreference::getModeString ( void )

参数

此函数没有参数。

返回值

Returns the ReadPreference's "mode" option as a string.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\ReadPreference::getModeString example

<?php

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::PRIMARY);
var_dump($rp->getModeString());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::PRIMARY_PREFERRED);
var_dump($rp->getModeString());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::SECONDARY);
var_dump($rp->getModeString());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::SECONDARY_PREFERRED);
var_dump($rp->getModeString());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::NEAREST);
var_dump($rp->getModeString());

?>

以上例程会输出:

string(7) "primary"
string(16) "primaryPreferred"
string(9) "secondary"
string(18) "secondaryPreferred"
string(7) "nearest"

参见

MongoDB\Driver\ReadPreference::getTagSets

Returns the ReadPreference's "tagSets" option

说明

final public array MongoDB\Driver\ReadPreference::getTagSets ( void )

参数

此函数没有参数。

返回值

Returns the ReadPreference's "tagSets" option.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\ReadPreference::getTagSets example

<?php

$mode = MongoDB\Driver\ReadPreference::RP_SECONDARY_PREFERRED;

/* Null and an empty array both denote no tag set preference. */
$rp = new MongoDB\Driver\ReadPreference($mode, null);
var_dump($rp->getTagSets());

$rp = new MongoDB\Driver\ReadPreference($mode, []);
var_dump($rp->getTagSets());

/* Prefer a node in New York, but fall back to any available node. */
$rp = new MongoDB\Driver\ReadPreference($mode, [['dc' => 'ny']]);
var_dump($rp->getTagSets());

/* Prefer a node in the New York, followed by a node in San Francisco that is
   labeled for reporting usage, and finally fall back to any available node. */
$rp = new MongoDB\Driver\ReadPreference($mode, [
  ['dc' => 'ny'],
  ['dc' => 'sf', 'use' => 'reporting'],
  [],
]);
var_dump($rp->getTagSets());

?>

以上例程会输出:

array(0) {
}
array(0) {
}
array(2) {
  [0]=>
  array(1) {
    ["dc"]=>
    string(2) "ny"
  }
  [1]=>
  array(0) {
  }
}
array(3) {
  [0]=>
  array(1) {
    ["dc"]=>
    string(2) "ny"
  }
  [1]=>
  array(2) {
    ["dc"]=>
    string(2) "sf"
    ["use"]=>
    string(9) "reporting"
  }
  [2]=>
  array(0) {
  }
}

参见

MongoDB\Driver\ReadPreference::serialize

Serialize a ReadPreference

说明

final public string MongoDB\Driver\ReadPreference::serialize ( void )

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\Driver\ReadPreference.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

MongoDB\Driver\ReadPreference::unserialize

Unserialize a ReadPreference

说明

final public void MongoDB\Driver\ReadPreference::unserialize ( string $serialized )

参数

serialized
The serialized MongoDB\Driver\ReadPreference.

返回值

Returns the unserialized MongoDB\Driver\ReadPreference.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

参见

简介

MongoDB\Driver\ReadConcern controls the level of isolation for read operations for replica sets and replica set shards. This option requires MongoDB 3.2 or later.

类摘要

MongoDB\Driver\ReadConcern

final class MongoDB\Driver\ReadConcern implements MongoDB\BSON\Serializable , Serializable {

/* Constants */

const string MongoDB\Driver\ReadConcern::AVAILABLE = "available" ;

const string MongoDB\Driver\ReadConcern::LINEARIZABLE = "linearizable" ;

const string MongoDB\Driver\ReadConcern::LOCAL = "local" ;

const string MongoDB\Driver\ReadConcern::MAJORITY = "majority" ;

/* 方法 */

final public object bsonSerialize ( void )

final public __construct ([ string $level ] )

final public string|null getLevel ( void )

final public bool isDefault ( void )

final public string serialize ( void )

final public void unserialize ( string $serialized )

}

预定义常量

MongoDB\Driver\ReadConcern::AVAILABLE
Default for reads against secondaries when afterClusterTimeand level are unspecified.

The query returns the instance's most recent data. Provides no guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back).

For unsharded collections (including collections in a standalone deployment or a replica set deployment), "local" and "available" read concerns behave identically.

For a sharded cluster, "available" read concern provides greater tolerance for partitions since it does not wait to ensure consistency guarantees. However, a query with "available" read concern may return orphan documents if the shard is undergoing chunk migrations since the "available" read concern, unlike "local" read concern, does not contact the shard's primary nor the config servers for updated metadata.

MongoDB\Driver\ReadConcern::LINEARIZABLE
The query returns data that reflects all successful writes issued with a write concern of "majority" and acknowledged prior to the start of the read operation. For replica sets that run with writeConcernMajorityJournalDefault set to TRUE, linearizable read concern returns data that will never be rolled back.

With writeConcernMajorityJournalDefault set to FALSE, MongoDB will not wait for w: "majority" writes to be durable before acknowledging the writes. As such, "majority" write operations could possibly roll back in the event of a loss of a replica set member.

You can specify linearizable read concern for read operations on the primary only.

Linearizable read concern guarantees only apply if read operations specify a query filter that uniquely identifies a single document.

小贴士 Always use maxTimeMS with linearizable read concern in case a majority of data bearing members are unavailable. maxTimeMS ensures that the operation does not block indefinitely and instead ensures that the operation returns an error if the read concern cannot be fulfilled.

Linearizable read concern requires MongoDB 3.4.

MongoDB\Driver\ReadConcern::LOCAL
Default for reads against primary if level is unspecified and for reads against secondaries if level is unspecified but afterClusterTime is specified.

The query returns the instance's most recent data. Provides no guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back).

MongoDB\Driver\ReadConcern::MAJORITY
The query returns the instance's most recent data acknowledged as having been written to a majority of members in the replica set.

To use read concern level of "majority", replica sets must use WiredTiger storage engine and election protocol version 1.

更新日志

版本 说明
1.7.0 Implements Serializable.
1.4.0

Added the MongoDB\Driver\ReadConcern::AVAILABLE constant.

1.2.0

Added the MongoDB\Driver\ReadConcern::LINEARIZABLE constant.

Implements MongoDB\BSON\Serializable.

参见

MongoDB\Driver\ReadConcern::bsonSerialize

Returns an object for BSON serialization

说明

final public object MongoDB\Driver\ReadConcern::bsonSerialize ( void )

参数

此函数没有参数。

返回值

Returns an object for serializing the ReadConcern as BSON.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\ReadConcern::bsonSerialize with empty read concern

<?php

$rc = new MongoDB\Driver\ReadConcern;
var_dump($rc->bsonSerialize());

echo "\n", MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($rc));

?>

以上例程的输出类似于:

object(stdClass)#2 (0) {
}

{ }

示例 #2 MongoDB\Driver\ReadConcern::bsonSerialize with local read concern

<?php

$rc = new MongoDB\Driver\ReadConcern(MongoDB\Driver\ReadConcern::LOCAL);
var_dump($rc->bsonSerialize());

echo "\n", MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($rc));

?>

以上例程的输出类似于:

object(stdClass)#2 (1) {
  ["level"]=>
  string(5) "local"
}

{ "level" : "local" }

参见

MongoDB\Driver\ReadConcern::__construct

Create a new ReadConcern

说明

final public MongoDB\Driver\ReadConcern::__construct ([ string $level ] )

Constructs a new MongoDB\Driver\ReadConcern, which is an immutable value object.

参数

level
The » read concern level. You may use, but are not limited to, one of the class constants.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\ReadConcern::__construct example

<?php

/* Unspecified read isolation level (uses the server's default behavior) */
$rc = new MongoDB\Driver\ReadConcern();

/* Request read isolation from a single replica set node */
$rc = new MongoDB\Driver\ReadConcern(MongoDB\Driver\ReadConcern::LOCAL);

/* Request read isolation from a majority of the replica set nodes */
$rc = new MongoDB\Driver\ReadConcern(MongoDB\Driver\ReadConcern::MAJORITY);

?>

参见

MongoDB\Driver\ReadConcern::getLevel

Returns the ReadConcern's "level" option

说明

final public string|null MongoDB\Driver\ReadConcern::getLevel ( void )

参数

此函数没有参数。

返回值

Returns the ReadConcern's "level" option.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\ReadConcern::getLevel example

<?php

$rc = new MongoDB\Driver\ReadConcern();
var_dump($rc->getLevel());

$rc = new MongoDB\Driver\ReadConcern(MongoDB\Driver\ReadConcern::LOCAL);
var_dump($rc->getLevel());

$rc = new MongoDB\Driver\ReadConcern(MongoDB\Driver\ReadConcern::MAJORITY);
var_dump($rc->getLevel());

?>

以上例程会输出:

NULL
string(5) "local"
string(8) "majority"

参见

MongoDB\Driver\ReadConcern::isDefault

Checks if this is the default read concern

说明

final public bool MongoDB\Driver\ReadConcern::isDefault ( void )

Returns whether this is the default read concern (i.e. no options are specified). This method is primarily intended to be used in conjunction with MongoDB\Driver\Manager::getReadConcern to determine whether the Manager has been constructed without any read concern options.

The driver will not include a default read concern in its read operations (e.g. MongoDB\Driver\Manager::executeQuery) in order order to allow the server to apply its own default. Libraries that access the Manager's read concern to include it in their own read commands should use this method to ensure that default read concerns are left unset.

参数

此函数没有参数。

返回值

Returns TRUE if this is the default read concern and FALSE otherwise.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\ReadConcern::isDefault example

<?php

$rc = new MongoDB\Driver\ReadConcern(null);
var_dump($rc->isDefault());

$rc = new MongoDB\Driver\ReadConcern(MongoDB\Driver\ReadConcern::MAJORITY);
var_dump($rc->isDefault());

$manager = new MongoDB\Driver\Manager('mongodb://127.0.0.1/?readConcernLevel=majority');
$rc = $manager->getReadConcern();
var_dump($rc->isDefault());

$manager = new MongoDB\Driver\Manager('mongodb://127.0.0.1/');
$rc = $manager->getReadConcern();
var_dump($rc->isDefault());

?>

以上例程会输出:

bool(true)
bool(false)
bool(false)
bool(true)

参见

MongoDB\Driver\ReadConcern::serialize

Serialize a ReadConcern

说明

final public string MongoDB\Driver\ReadConcern::serialize ( void )

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\Driver\ReadConcern.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

MongoDB\Driver\ReadConcern::unserialize

Unserialize a ReadConcern

说明

final public void MongoDB\Driver\ReadConcern::unserialize ( string $serialized )

参数

serialized
The serialized MongoDB\Driver\ReadConcern.

返回值

Returns the unserialized MongoDB\Driver\ReadConcern.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

参见

简介

The MongoDB\Driver\Cursor class encapsulates the results of a MongoDB command or query and may be returned by MongoDB\Driver\Manager::executeCommand or MongoDB\Driver\Manager::executeQuery, respectively.

类摘要

MongoDB\Driver\Cursor

final class MongoDB\Driver\Cursor implements MongoDB\Driver\CursorInterface {

/* 方法 */

final private __construct ( void )

final public MongoDB\Driver\CursorId getId ( void )

final public MongoDB\Driver\Server getServer ( void )

final public bool isDead ( void )

final public void setTypeMap ( array $typemap )

final public array toArray ( void )

}

更新日志

版本说明
1.6.0Implements MongoDB\Driver\CursorInterface, which extends Traversable.

范例

示例 #1 Reading a result set

MongoDB\Driver\Manager::executeCommand and MongoDB\Driver\Manager::executeQuery both return their result(s) as a MongoDB\Driver\Cursor object. This object can be used to iterate over the result set of the command or query.

Because MongoDB\Driver\Cursor implements the Traversable interface, you can simply iterate over the result set with foreach.

<?php

$manager = new MongoDB\Driver\Manager();

/* Insert some documents so that our query returns information */
$bulkWrite = new MongoDB\Driver\BulkWrite;
$bulkWrite->insert(['name' => 'Ceres', 'size' => 946, 'distance' => 2.766]);
$bulkWrite->insert(['name' => 'Vesta', 'size' => 525, 'distance' => 2.362]);
$manager->executeBulkWrite("test.asteroids", $bulkWrite);

/* Query for all the items in the collection */
$query = new MongoDB\Driver\Query( [] );

/* Query the "asteroids" collection of the "test" database */
$cursor = $manager->executeQuery("test.asteroids", $query);

/* $cursor now contains an object that wraps around the result set. Use
 * foreach() to iterate over all the result */
foreach($cursor as $document) {
    print_r($document);
}

?>

以上例程的输出类似于:

stdClass Object
(
    [_id] => MongoDB\BSON\ObjectId Object
        (
            [oid] => 5a4cff2f122d3321565d8cc2
        )

    [name] => Ceres
    [size] => 946
    [distance] => 2.766
)
stdClass Object
(
    [_id] => MongoDB\BSON\ObjectId Object
        (
            [oid] => 5a4cff2f122d3321565d8cc3
        )

    [name] => Vesta
    [size] => 525
    [distance] => 2.362
}

示例 #2 Reading a result set for a tailable cursor

» 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 » Capped Collections and » 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. Similar to result objects in other database drivers, cursors in MongoDB only support forward iteration, which means they cannot be rewound.

In order to continuously read from a tailable cursor, the Cursor object must be wrapped with an IteratorIterator. This allows the application to directly control the cursor's iteration, avoid inadvertently rewinding the cursor, and decide when to wait for new results or stop iteration entirely.

In order to demonstrate a tailable cursor in action, two scripts will be used: a "producer" and a "consumer". The producer script will create a new capped collection using the » create command and proceed to insert a new document into that collection each second.

<?php

$manager = new MongoDB\Driver\Manager;

$manager->executeCommand('test', new MongoDB\Driver\Command([
    'create' => 'asteroids',
    'capped' => true,
    'size' => 1048576,
]));

while (true) {
    $bulkWrite = new MongoDB\Driver\BulkWrite;
    $bulkWrite->insert(['createdAt' => new MongoDB\BSON\UTCDateTime]);
    $manager->executeBulkWrite('test.asteroids', $bulkWrite);

    sleep(1);
}

?>

With the producer script still running, a second consumer script may be executed to read the inserted documents using a tailable cursor, indicated by the tailable and awaitData options to MongoDB\Driver\Query::__construct.

<?php

$manager = new MongoDB\Driver\Manager;

$query = new MongoDB\Driver\Query([], [
    'tailable' => true,
    'awaitData' => true,
]);

$cursor = $manager->executeQuery('test.asteroids', $query);

$iterator = new IteratorIterator($cursor);

$iterator->rewind();

while (true) {
    if ($iterator->valid()) {
        $document = $iterator->current();
        printf("Consumed document created at: %s\n", $document->createdAt);
    }

    $iterator->next();
}

?>

The consumer script will start by quickly printing all available documents in the capped collection (as if foreach had been used); however, it will not terminate upon reaching the end of the initial result set. Since the cursor is tailable, calling IteratorIterator::next will block and wait for additional results. IteratorIterator::valid is also used to check if there is actually data available to read at each step.

Note: This example uses the awaitData query option to instruct the server to block for a short period (e.g. one second) at the end of the result set before returning a response to the driver. This is used to prevent the driver from aggressively polling the server when there are no results available. The maxAwaitTimeMS option may be used in conjunction with tailable and awaitData to specify the amount of time that the server should block when it reaches the end of the result set.

错误/异常

When iterating over the cursor object, BSON data is converted into PHP variables. This iteration can cause the following Exceptions:

  • Throws MongoDB\Driver\Exception\InvalidArgumentException if a class in the type map cannot be instantiated or does not implement MongoDB\BSON\Unserializable.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the input did not contain exactly one BSON document. Possible reasons include, but are not limited to, invalid BSON, extra data (after reading one BSON document), or an unexpected » libbson error.

MongoDB\Driver\Cursor::__construct

Create a new Cursor (not used)

说明

final private MongoDB\Driver\Cursor::__construct ( void )

MongoDB\Driver\Cursor objects are returned as the result of an executed command or query and cannot be constructed directly.

参数

此函数没有参数。

参见

  • MongoDB\Driver\Manager::executeCommand
  • MongoDB\Driver\Manager::executeQuery
  • MongoDB\Driver\Server::executeCommand
  • MongoDB\Driver\Server::executeQuery

MongoDB\Driver\Cursor::getId

Returns the ID for this cursor

说明

final public MongoDB\Driver\CursorId MongoDB\Driver\Cursor::getId ( void )

Returns the MongoDB\Driver\CursorId associated with this cursor. A cursor ID uniquely identifies the cursor on the server.

参数

此函数没有参数。

返回值

Returns the MongoDB\Driver\CursorId for this cursor.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\Cursor::getId example

<?php

/* In this example, we insert several documents into the collection and specify
 * a smaller batchSize to ensure that the first batch contains only a subset of
 * our results and the cursor remains open on the server. */
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$query = new MongoDB\Driver\Query([], ['batchSize' => 2]);

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->insert(['x' => 2]);
$bulk->insert(['x' => 3]);
$manager->executeBulkWrite('db.collection', $bulk);

$cursor = $manager->executeQuery('db.collection', $query);
var_dump($cursor->getId());

?>

以上例程的输出类似于:

object(MongoDB\Driver\CursorId)#5 (1) {
  ["id"]=>
  int(94810124093)
}

参见

  • MongoDB\Driver\CursorId
  • MongoDB\Driver\CursorId::__toString

MongoDB\Driver\Cursor::getServer

Returns the server associated with this cursor

说明

final public MongoDB\Driver\Server MongoDB\Driver\Cursor::getServer ( void )

Returns the MongoDB\Driver\Server associated with this cursor. This is the server that executed the MongoDB\Driver\Query or MongoDB\Driver\Command.

参数

此函数没有参数。

返回值

Returns the MongoDB\Driver\Server associated with this cursor.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\Cursor::getServer example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$query = new MongoDB\Driver\Query([]);

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$manager->executeBulkWrite('db.collection', $bulk);

$cursor = $manager->executeQuery('db.collection', $query);
var_dump($cursor->getServer());

?>

以上例程的输出类似于:

object(MongoDB\Driver\Server)#5 (10) {
  ["host"]=>
  string(9) "localhost"
  ["port"]=>
  int(27017)
  ["type"]=>
  int(1)
  ["is_primary"]=>
  bool(false)
  ["is_secondary"]=>
  bool(false)
  ["is_arbiter"]=>
  bool(false)
  ["is_hidden"]=>
  bool(false)
  ["is_passive"]=>
  bool(false)
  ["last_is_master"]=>
  array(8) {
    ["ismaster"]=>
    bool(true)
    ["maxBsonObjectSize"]=>
    int(16777216)
    ["maxMessageSizeBytes"]=>
    int(48000000)
    ["maxWriteBatchSize"]=>
    int(1000)
    ["localTime"]=>
    object(MongoDB\BSON\UTCDateTime)#6 (1) {
      ["milliseconds"]=>
      int(1446505367907)
    }
    ["maxWireVersion"]=>
    int(3)
    ["minWireVersion"]=>
    int(0)
    ["ok"]=>
    float(1)
  }
  ["round_trip_time"]=>
  int(584)
}

参见

  • MongoDB\Driver\Server

MongoDB\Driver\Cursor::isDead

Checks if the cursor is exhausted or may have additional results

说明

final public bool MongoDB\Driver\Cursor::isDead ( void )

Checks whether there are definitely no additional results available on the cursor. This method is similar to the » cursor.isExhausted() method in the MongoDB shell and is primarily useful when iterating » tailable cursors.

A cursor has no additional results and is considered "dead" when one of the following is true:

  • The current batch has been fully iterated and the cursor ID is zero (i.e. a » getMore cannot be issued).
  • An error was encountered while iterating the cursor.
  • The cursor reached its configured limit.

By design, it is not possible to always determine whether a cursor has additional results. The cases where a cursor may have more data available is as follows:

  • There are additional documents in the current batch, which are buffered on the client side. Iterating will fetch a document from the local buffer.
  • There are no additional documents in the current batch (i.e. local buffer), but the cursor ID is non-zero. Iterating will request more documents from the server via a » getMore operation, which may or may not return additional results and/or indicate that the cursor has been closed on the server by returning zero for its ID.

参数

此函数没有参数。

返回值

Returns TRUE if there are definitely no additional results available on the cursor, and FALSE otherwise.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\Cursor::isDead example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$query = new MongoDB\Driver\Query([]);

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->insert(['x' => 2]);
$bulk->insert(['x' => 3]);
$manager->executeBulkWrite('db.collection', $bulk);

$cursor = $manager->executeQuery('db.collection', $query);

$iterator = new IteratorIterator($cursor);

$iterator->rewind();
var_dump($cursor->isDead());

$iterator->next();
var_dump($cursor->isDead());

$iterator->next();
var_dump($cursor->isDead());

$iterator->next();
var_dump($cursor->isDead());

?>

以上例程会输出:

bool(false)
bool(false)
bool(false)
bool(true)

参见

MongoDB\Driver\Cursor::setTypeMap

Sets a type map to use for BSON unserialization

说明

final public void MongoDB\Driver\Cursor::setTypeMap ( array $typemap )

Sets the type map configuration to use when unserializing the BSON results into PHP values.

参数

typeMap (array)
Type map configuration.

返回值

没有返回值。

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

When iterating over the cursor, the following exceptions can also be thrown due to an incorrect type map configuration:

  • Throws MongoDB\Driver\Exception\InvalidArgumentException if a class in the type map cannot be instantiated or does not implement MongoDB\BSON\Unserializable.

范例

示例 #1 MongoDB\Driver\Cursor::setTypeMap example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

$bulk = new MongoDB\Driver\BulkWrite;
$id = $bulk->insert(['x' => 1]);
$manager->executeBulkWrite('db.collection', $bulk);

$query = new MongoDB\Driver\Query(['_id' => $id]);
$cursor = $manager->executeQuery('db.collection', $query);
$cursor->setTypeMap(['root' => 'array']);

foreach ($cursor as $document) {
    var_dump($document);
}

?>

以上例程的输出类似于:

array(2) {
  ["_id"]=>
  object(MongoDB\BSON\ObjectId)#6 (1) {
    ["oid"]=>
    string(24) "56424fb76118fd3267180741"
  }
  ["x"]=>
  int(1)
}

参见

MongoDB\Driver\Cursor::toArray

Returns an array containing all results for this cursor

说明

final public array MongoDB\Driver\Cursor::toArray ( void )

Iterates the cursor and returns its results in an array. MongoDB\Driver\Cursor::setTypeMap may be used to control how documents are unserialized into PHP values.

参数

此函数没有参数。

返回值

Returns an array containing all results for this cursor.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\Cursor::toArray example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->insert(['x' => 2]);
$bulk->insert(['x' => 3]);
$manager->executeBulkWrite('db.collection', $bulk);

$query = new MongoDB\Driver\Query([]);
$cursor = $manager->executeQuery('db.collection', $query);

var_dump($cursor->toArray());

?>

以上例程的输出类似于:

array(3) {
  [0]=>
  object(stdClass)#6 (2) {
    ["_id"]=>
    object(MongoDB\BSON\ObjectId)#5 (1) {
      ["oid"]=>
      string(24) "564259a96118fd40b41bcf61"
    }
    ["x"]=>
    int(1)
  }
  [1]=>
  object(stdClass)#8 (2) {
    ["_id"]=>
    object(MongoDB\BSON\ObjectId)#7 (1) {
      ["oid"]=>
      string(24) "564259a96118fd40b41bcf62"
    }
    ["x"]=>
    int(2)
  }
  [2]=>
  object(stdClass)#10 (2) {
    ["_id"]=>
    object(MongoDB\BSON\ObjectId)#9 (1) {
      ["oid"]=>
      string(24) "564259a96118fd40b41bcf63"
    }
    ["x"]=>
    int(3)
  }
}

参见

  • MongoDB\Driver\Cursor::setTypeMap

简介

The MongoDB\Driver\CursorID class is a value object that represents a cursor ID. Instances of this class are returned by MongoDB\Driver\Cursor::getId.

类摘要

MongoDB\Driver\CursorId

final class MongoDB\Driver\CursorId implements Serializable {

/* 方法 */

final private __construct ( void )

final public string serialize ( void )

final public string __toString ( void )

final public void unserialize ( string $serialized )

}

更新日志

版本说明
1.7.0Implements Serializable.

MongoDB\Driver\CursorId::__construct

Create a new CursorId (not used)

说明

final private MongoDB\Driver\CursorId::__construct ( void )

MongoDB\Driver\CursorId objects are returned from MongoDB\Driver\Cursor::getId and cannot be constructed directly.

参数

此函数没有参数。

参见

  • MongoDB\Driver\Cursor::getId

MongoDB\Driver\CursorId::serialize

Serialize a CursorId

说明

final public string MongoDB\Driver\CursorId::serialize ( void )

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\Driver\CursorId.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

MongoDB\Driver\CursorId::__toString

String representation of the cursor ID

说明

final public string MongoDB\Driver\CursorId::__toString ( void )

Returns the string representation of the cursor ID.

参数

此函数没有参数。

返回值

Returns the string representation of the cursor ID.

范例

示例 #1 MongoDB\Driver\CursorId::__toString example

<?php

/* In this example, we insert several documents into the collection and specify
 * a smaller batchSize to ensure that the first batch contains only a subset of
 * our results and the cursor remains open on the server. */
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$query = new MongoDB\Driver\Query([], ['batchSize' => 2]);

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->insert(['x' => 2]);
$bulk->insert(['x' => 3]);
$manager->executeBulkWrite('db.collection', $bulk);

$cursor = $manager->executeQuery('db.collection', $query);
var_dump((string) $cursor->getId());

?>

以上例程的输出类似于:

string(11) "98061641158"

参见

  • MongoDB\Driver\Cursor::getId

MongoDB\Driver\CursorId::unserialize

Unserialize a CursorId

说明

final public void MongoDB\Driver\CursorId::unserialize ( string $serialized )

参数

serialized
The serialized MongoDB\Driver\CursorId.

返回值

Returns the unserialized MongoDB\Driver\CursorId.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

参见

简介

类摘要

MongoDB\Driver\Server

final class MongoDB\Driver\Server {

/* Constants */

const integer MongoDB\Driver\Server::TYPE_UNKNOWN = 0 ;

const integer MongoDB\Driver\Server::TYPE_STANDALONE = 1 ;

const integer MongoDB\Driver\Server::TYPE_MONGOS = 2 ;

const integer MongoDB\Driver\Server::TYPE_POSSIBLE_PRIMARY = 3 ;

const integer MongoDB\Driver\Server::TYPE_RS_PRIMARY = 4 ;

const integer MongoDB\Driver\Server::TYPE_RS_SECONDARY = 5 ;

const integer MongoDB\Driver\Server::TYPE_RS_ARBITER = 6 ;

const integer MongoDB\Driver\Server::TYPE_RS_OTHER = 7 ;

const integer MongoDB\Driver\Server::TYPE_RS_GHOST = 8 ;

/* 方法 */

final private __construct ( void )

final public MongoDB\Driver\WriteResult executeBulkWrite ( string $namespace , MongoDB\Driver\BulkWrite $bulk [, array $options = array() ] )

final public MongoDB\Driver\Cursor executeCommand ( string $db , MongoDB\Driver\Command $command [, array $options = array() ] )

final public MongoDB\Driver\Cursor executeQuery ( string $namespace , MongoDB\Driver\Query $query [, array $options = array() ] )

final public MongoDB\Driver\Cursor executeReadCommand ( string $db , MongoDB\Driver\Command $command [, array $options = array() ] )

final public MongoDB\Driver\Cursor executeReadWriteCommand ( string $db , MongoDB\Driver\Command $command [, array $options = array() ] )

final public MongoDB\Driver\Cursor executeWriteCommand ( string $db , MongoDB\Driver\Command $command [, array $options = array() ] )

final public string getHost ( void )

final public array getInfo ( void )

final public string getLatency ( void )

final public int getPort ( void )

final public array getTags ( void )

final public int getType ( void )

final public bool isArbiter ( void )

final public bool isHidden ( void )

final public bool isPassive ( void )

final public bool isPrimary ( void )

final public bool isSecondary ( void )

}

预定义常量

MongoDB\Driver\Server::TYPE_UNKNOWN
Unknown server type, returned by MongoDB\Driver\Server::getType.

MongoDB\Driver\Server::TYPE_STANDALONE
Standalone server type, returned by MongoDB\Driver\Server::getType.

MongoDB\Driver\Server::TYPE_MONGOS
Mongos server type, returned by MongoDB\Driver\Server::getType.

MongoDB\Driver\Server::TYPE_POSSIBLE_PRIMARY
Replica set possible primary server type, returned by MongoDB\Driver\Server::getType.

A server may be identified as a possible primary if it has not yet been checked but another memory of the replica set thinks it is the primary.

MongoDB\Driver\Server::TYPE_RS_PRIMARY
Replica set primary server type, returned by MongoDB\Driver\Server::getType.

MongoDB\Driver\Server::TYPE_RS_SECONDARY
Replica set secondary server type, returned by MongoDB\Driver\Server::getType.

MongoDB\Driver\Server::TYPE_RS_ARBITER
Replica set arbiter server type, returned by MongoDB\Driver\Server::getType.

MongoDB\Driver\Server::TYPE_RS_OTHER
Replica set other server type, returned by MongoDB\Driver\Server::getType.

Such servers may be hidden, starting up, or recovering. They cannot be queried, but their hosts lists are useful for discovering the current replica set configuration.

MongoDB\Driver\Server::TYPE_RS_GHOST
Replica set ghost server type, returned by MongoDB\Driver\Server::getType.

Servers may be identified as such in at least three situations: briefly during server startup; in an uninitialized replica set; or when the server is shunned (i.e. removed from the replica set config). They cannot be queried, nor can their host list be used to discover the current replica set configuration; however, the client may monitor this server in hope that it transitions to a more useful state.

MongoDB\Driver\Server::__construct

Create a new Server (not used)

说明

final private MongoDB\Driver\Server::__construct ( void )

MongoDB\Driver\Server objects are created internally by MongoDB\Driver\Manager when a database connection is established and may be returned by MongoDB\Driver\Manager::getServers and MongoDB\Driver\Manager::selectServer.

参数

此函数没有参数。

参见

  • MongoDB\Driver\Manager::getServers
  • MongoDB\Driver\Manager::selectServer

MongoDB\Driver\Server::executeBulkWrite

Execute one or more write operations on this server

说明

final public MongoDB\Driver\WriteResult MongoDB\Driver\Server::executeBulkWrite ( string $namespace , MongoDB\Driver\BulkWrite $bulk [, array $options = array() ] )

Executes one or more write operations on this server.

A MongoDB\Driver\BulkWrite can be constructed with one or more write operations of varying types (e.g. updates, deletes, and inserts). The driver will attempt to send operations of the same type to the server in as few requests as possible to optimize round trips.

参数

namespace (string)
A fully qualified namespace (e.g. "databaseName.collectionName").

bulk (MongoDB\Driver\BulkWrite)
The write(s) to execute.

options
| Option | Type | Description | |--------------|--------------------------------------------------------------|--------------------------------------------| | session | MongoDB\Driver\Session | A session to associate with the operation. | | writeConcern | MongoDB\Driver\WriteConcern | A write concern to apply to the operation. |

返回值

Returns MongoDB\Driver\WriteResult on success.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException if bulk does not contain any write operations.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if bulk has already been executed. MongoDB\Driver\BulkWrite objects may not be executed multiple times.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used in combination with an unacknowledged write concern.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\BulkWriteException on any write failure (e.g. write error, failure to apply a write concern)
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors.

更新日志

版本说明
1.4.4MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the "session" option is used in combination with an unacknowledged write concern.
1.4.0The third parameter is now an options array. For backwards compatibility, this paramater will still accept a MongoDB\Driver\WriteConcern object.
1.3.0MongoDB\Driver\Exception\InvalidArgumentException is now thrown if bulk does not contain any write operations. Previously, a MongoDB\Driver\Exception\BulkWriteException was thrown.

注释

Note: It is the caller's responsibility to ensure that the server is capable of executing the write operation. For example, executing a write operation on a secondary (excluding its "local" database) will fail.

参见

  • MongoDB\Driver\BulkWrite
  • MongoDB\Driver\WriteResult
  • MongoDB\Driver\WriteConcern
  • MongoDB\Driver\Manager::executeBulkWrite

MongoDB\Driver\Server::executeCommand

Execute a database command on this server

说明

final public MongoDB\Driver\Cursor MongoDB\Driver\Server::executeCommand ( string $db , MongoDB\Driver\Command $command [, array $options = array() ] )

Executes the command on this server.

This method applies no special logic to the command. Although this method accepts "readConcern" and "writeConcern" options, which will be incorporated into the command document, those options will not default to corresponding values from the MongoDB Connection URI nor will the MongoDB server version be taken into account. Users are therefore encouraged to use specific read and/or write command methods if possible.

Note: The "readPreference" option does not control the server to which the driver issues the operation; it will always be executed on this server object. Instead, it may be used when issuing the operation to a secondary (from a replica set connection, not standalone) or mongos node to ensure that the driver sets the wire protocol accordingly or adds the read preference to the operation, respectively.

参数

db (string)
The name of the database on which to execute the command.

command (MongoDB\Driver\Command)
The command to execute.

options

options
Option Type Description
readConcern MongoDB\Driver\ReadConcern

A read concern to apply to the operation.

This option is available in MongoDB 3.2+ and will result in an exception at execution time if specified for an older server version.

readPreference MongoDB\Driver\ReadPreference

A read preference to use for selecting a server for the operation.

session MongoDB\Driver\Session

A session to associate with the operation.

writeConcern MongoDB\Driver\WriteConcern

A write concern to apply to the operation.

Warning If you are using a "session" which has a transaction in progress, you cannot specify a "readConcern" or "writeConcern" option. This will result in an MongoDB\Driver\Exception\InvalidArgumentException being thrown. Instead, you should set these two options when you create the transaction with MongoDB\Driver\Session::startTransaction.

返回值

Returns MongoDB\Driver\Cursor on success.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used with an associated transaction in combination with a "readConcern" or "writeConcern" option.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used in combination with an unacknowledged write concern.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command, issuing a write command to a secondary).

更新日志

版本说明
1.4.4MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the "session" option is used in combination with an unacknowledged write concern.
1.4.0The third parameter is now an options array. For backwards compatibility, this paramater will still accept a MongoDB\Driver\ReadPreference object.

注释

Note: It is the caller's responsibility to ensure that the server is capable of executing the write operation. For example, executing a write operation on a secondary (excluding its "local" database) will fail.

参见

  • MongoDB\Driver\Command
  • MongoDB\Driver\Cursor
  • MongoDB\Driver\Server::executeReadCommand
  • MongoDB\Driver\Server::executeReadWriteCommand
  • MongoDB\Driver\Server::executeWriteCommand
  • MongoDB\Driver\Manager::executeCommand

MongoDB\Driver\Server::executeQuery

Execute a database query on this server

说明

final public MongoDB\Driver\Cursor MongoDB\Driver\Server::executeQuery ( string $namespace , MongoDB\Driver\Query $query [, array $options = array() ] )

Executes the query on this server.

Note: The "readPreference" option does not control the server to which the driver issues the operation; it will always be executed on this server object. Instead, it may be used when issuing the operation to a secondary (from a replica set connection, not standalone) or mongos node to ensure that the driver sets the wire protocol accordingly or adds the read preference to the operation, respectively.

参数

namespace (string)
A fully qualified namespace (e.g. "databaseName.collectionName").

query (MongoDB\Driver\Query)
The query to execute.

options
| Option | Type | Description | |----------------|----------------------------------------------------------------|--------------------------------------------------------------------| | readPreference | MongoDB\Driver\ReadPreference | A read preference to use for selecting a server for the operation. | | session | MongoDB\Driver\Session | A session to associate with the operation. |

返回值

Returns MongoDB\Driver\Cursor on success.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid query operators).

更新日志

版本说明
1.4.0The third parameter is now an options array. For backwards compatibility, this paramater will still accept a MongoDB\Driver\ReadPreference object.

参见

  • MongoDB\Driver\Cursor
  • MongoDB\Driver\Query
  • MongoDB\Driver\ReadPreference
  • MongoDB\Driver\Manager::executeQuery

MongoDB\Driver\Server::executeReadCommand

Execute a database command that reads on this server

说明

final public MongoDB\Driver\Cursor MongoDB\Driver\Server::executeReadCommand ( string $db , MongoDB\Driver\Command $command [, array $options = array() ] )

Executes the command on this server.

This method will apply logic that is specific to commands that read (e.g. » count) and take the MongoDB server version into account. The "readConcern" option will default to the corresponding value from the MongoDB Connection URI.

Note: The "readPreference" option does not control the server to which the driver issues the operation; it will always be executed on this server object. Instead, it may be used when issuing the operation to a secondary (from a replica set connection, not standalone) or mongos node to ensure that the driver sets the wire protocol accordingly or adds the read preference to the operation, respectively.

参数

db (string)
The name of the database on which to execute the command.

command (MongoDB\Driver\Command)
The command to execute.

options

options
Option Type Description
readConcern MongoDB\Driver\ReadConcern

A read concern to apply to the operation.

This option is available in MongoDB 3.2+ and will result in an exception at execution time if specified for an older server version.

readPreference MongoDB\Driver\ReadPreference

A read preference to use for selecting a server for the operation.

session MongoDB\Driver\Session

A session to associate with the operation.

Warning If you are using a "session" which has a transaction in progress, you cannot specify a "readConcern" or "writeConcern" option. This will result in an MongoDB\Driver\Exception\InvalidArgumentException being thrown. Instead, you should set these two options when you create the transaction with MongoDB\Driver\Session::startTransaction.

返回值

Returns MongoDB\Driver\Cursor on success.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used with an associated transaction in combination with a "readConcern" or "writeConcern" option.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command).

参见

  • MongoDB\Driver\Command
  • MongoDB\Driver\Cursor
  • MongoDB\Driver\Server::executeCommand
  • MongoDB\Driver\Server::executeReadWriteCommand
  • MongoDB\Driver\Server::executeWriteCommand
  • MongoDB\Driver\Manager::executeReadCommand

MongoDB\Driver\Server::executeReadWriteCommand

Execute a database command that reads and writes on this server

说明

final public MongoDB\Driver\Cursor MongoDB\Driver\Server::executeReadWriteCommand ( string $db , MongoDB\Driver\Command $command [, array $options = array() ] )

Executes the command on this server.

This method will apply logic that is specific to commands that read and write (e.g. » findAndModify) and take the MongoDB server version into account. The "readConcern" and "writeConcern" options will default to the corresponding values from the MongoDB Connection URI.

参数

db (string)
The name of the database on which to execute the command.

command (MongoDB\Driver\Command)
The command to execute.

options

options
Option Type Description
readConcern MongoDB\Driver\ReadConcern

A read concern to apply to the operation.

This option is available in MongoDB 3.2+ and will result in an exception at execution time if specified for an older server version.

session MongoDB\Driver\Session

A session to associate with the operation.

writeConcern MongoDB\Driver\WriteConcern

A write concern to apply to the operation.

Warning If you are using a "session" which has a transaction in progress, you cannot specify a "readConcern" or "writeConcern" option. This will result in an MongoDB\Driver\Exception\InvalidArgumentException being thrown. Instead, you should set these two options when you create the transaction with MongoDB\Driver\Session::startTransaction.

返回值

Returns MongoDB\Driver\Cursor on success.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used with an associated transaction in combination with a "readConcern" or "writeConcern" option.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used in combination with an unacknowledged write concern.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command).

更新日志

版本说明
1.4.4MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the "session" option is used in combination with an unacknowledged write concern.

注释

Note: It is the caller's responsibility to ensure that the server is capable of executing the write operation. For example, executing a write operation on a secondary (excluding its "local" database) will fail.

参见

  • MongoDB\Driver\Command
  • MongoDB\Driver\Cursor
  • MongoDB\Driver\Server::executeCommand
  • MongoDB\Driver\Server::executeReadCommand
  • MongoDB\Driver\Server::executeWriteCommand
  • MongoDB\Driver\Manager::executeReadWriteCommand

MongoDB\Driver\Server::executeWriteCommand

Execute a database command that writes on this server

说明

final public MongoDB\Driver\Cursor MongoDB\Driver\Server::executeWriteCommand ( string $db , MongoDB\Driver\Command $command [, array $options = array() ] )

Executes the command on this server.

This method will apply logic that is specific to commands that write (e.g. » drop) and take the MongoDB server version into account. The "writeConcern" option will default to the corresponding value from the MongoDB Connection URI.

Note: This method is not intended to be used to execute » insert, » update, or » delete commands. Users are encouraged to use class="function">MongoDB\Driver\Server::executeBulkWrite for those commands.

参数

db (string)
The name of the database on which to execute the command.

command (MongoDB\Driver\Command)
The command to execute.

options
| Option | Type | Description | |--------------|--------------------------------------------------------------|--------------------------------------------| | session | MongoDB\Driver\Session | A session to associate with the operation. | | writeConcern | MongoDB\Driver\WriteConcern | A write concern to apply to the operation. |

Warning If you are using a "session" which has a transaction in progress, you cannot specify a "readConcern" or "writeConcern" option. This will result in an MongoDB\Driver\Exception\InvalidArgumentException being thrown. Instead, you should set these two options when you create the transaction with MongoDB\Driver\Session::startTransaction.

返回值

Returns MongoDB\Driver\Cursor on success.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used with an associated transaction in combination with a "readConcern" or "writeConcern" option.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used in combination with an unacknowledged write concern.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command).

更新日志

版本说明
1.4.4MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the "session" option is used in combination with an unacknowledged write concern.

注释

Note: It is the caller's responsibility to ensure that the server is capable of executing the write operation. For example, executing a write operation on a secondary (excluding its "local" database) will fail.

参见

  • MongoDB\Driver\Command
  • MongoDB\Driver\Cursor
  • MongoDB\Driver\Server::executeCommand
  • MongoDB\Driver\Server::executeReadCommand
  • MongoDB\Driver\Server::executeReadWriteCommand
  • MongoDB\Driver\Manager::executeWriteCommand

MongoDB\Driver\Server::getHost

Returns the hostname of this server

说明

final public string MongoDB\Driver\Server::getHost ( void )

Returns the hostname of this server.

参数

此函数没有参数。

返回值

Returns the hostname of this server.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\Server::getHost example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017/");

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
$server = $manager->selectServer($rp);

var_dump($server->getHost());

?>

以上例程会输出:

string(9) "localhost"

参见

  • MongoDB\Driver\Server::getInfo

MongoDB\Driver\Server::getInfo

Returns an array of information about this server

说明

final public array MongoDB\Driver\Server::getInfo ( void )

Returns an array of information about this server.

参数

此函数没有参数。

返回值

Returns an array of information about this server.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\Server::getInfo example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017/");

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
$server = $manager->selectServer($rp);

var_dump($server->getInfo());

?>

以上例程的输出类似于:

array(8) {
  ["ismaster"]=>
  bool(true)
  ["maxBsonObjectSize"]=>
  int(16777216)
  ["maxMessageSizeBytes"]=>
  int(48000000)
  ["maxWriteBatchSize"]=>
  int(1000)
  ["localTime"]=>
  object(MongoDB\BSON\UTCDateTime)#4 (1) {
    ["milliseconds"]=>
    int(1447276242774)
  }
  ["maxWireVersion"]=>
  int(3)
  ["minWireVersion"]=>
  int(0)
  ["ok"]=>
  float(1)
}

MongoDB\Driver\Server::getLatency

Returns the latency of this server

说明

final public string MongoDB\Driver\Server::getLatency ( void )

Returns the latency of this server (i.e. the client's measured » round trip time of an ismaster command).

参数

此函数没有参数。

返回值

Returns the latency of this server.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\Server::getLatency example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017/");

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
$server = $manager->selectServer($rp);

var_dump($server->getLatency());

?>

以上例程的输出类似于:

int(592)

参见

MongoDB\Driver\Server::getPort

Returns the port on which this server is listening

说明

final public int MongoDB\Driver\Server::getPort ( void )

Returns the port on which this server is listening.

参数

此函数没有参数。

返回值

Returns the port on which this server is listening.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\Server::getPort example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017/");

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
$server = $manager->selectServer($rp);

var_dump($server->getPort());

?>

以上例程会输出:

int(27017)

参见

  • MongoDB\Driver\Server::getInfo

MongoDB\Driver\Server::getTags

Returns an array of tags describing this server in a replica set

说明

final public array MongoDB\Driver\Server::getTags ( void )

Returns an array of » tags used to describe this server in a replica set. The array will contain zero or more string key and value pairs.

参数

此函数没有参数。

返回值

Returns an array of tags used to describe this server in a replica set.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Server::getInfo

MongoDB\Driver\Server::getType

Returns an integer denoting the type of this server

说明

final public int MongoDB\Driver\Server::getType ( void )

Returns an integer denoting the type of this server. The value will correlate with a MongoDB\Driver\Server constant.

参数

此函数没有参数。

返回值

Returns an integer denoting the type of this server.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Server::getInfo

MongoDB\Driver\Server::isArbiter

Checks if this server is an arbiter member of a replica set

说明

final public bool MongoDB\Driver\Server::isArbiter ( void )

Returns whether this server is an » arbiter member of a replica set.

参数

此函数没有参数。

返回值

Returns TRUE if this server is an arbiter member of a replica set, and FALSE otherwise.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Server::getInfo

MongoDB\Driver\Server::isHidden

Checks if this server is a hidden member of a replica set

说明

final public bool MongoDB\Driver\Server::isHidden ( void )

Returns whether this server is a » hidden member of a replica set.

参数

此函数没有参数。

返回值

Returns TRUE if this server is a hidden member of a replica set, and FALSE otherwise.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Server::getInfo

MongoDB\Driver\Server::isPassive

Checks if this server is a passive member of a replica set

说明

final public bool MongoDB\Driver\Server::isPassive ( void )

Returns whether this server is a » passive member of a replica set (i.e. its priority is 0).

参数

此函数没有参数。

返回值

Returns TRUE if this server is a passive member of a replica set, and FALSE otherwise.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Server::getInfo

MongoDB\Driver\Server::isPrimary

Checks if this server is a primary member of a replica set

说明

final public bool MongoDB\Driver\Server::isPrimary ( void )

Returns whether this server is a » primary member of a replica set.

参数

此函数没有参数。

返回值

Returns TRUE if this server is a primary member of a replica set, and FALSE otherwise.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Server::getInfo

MongoDB\Driver\Server::isSecondary

Checks if this server is a secondary member of a replica set

说明

final public bool MongoDB\Driver\Server::isSecondary ( void )

Returns whether this server is a » secondary member of a replica set.

参数

此函数没有参数。

返回值

Returns TRUE if this server is a secondary member of a replica set, and FALSE otherwise.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Server::getInfo

简介

The MongoDB\Driver\WriteConcernError class encapsulates information about a write concern error and may be returned by MongoDB\Driver\WriteResult::getWriteConcernError.

类摘要

MongoDB\Driver\WriteConcernError

final class MongoDB\Driver\WriteConcernError {

/* 方法 */

final public int getCode ( void )

final public mixed getInfo ( void )

final public string getMessage ( void )

}

MongoDB\Driver\WriteConcernError::getCode

Returns the WriteConcernError's error code

说明

final public int MongoDB\Driver\WriteConcernError::getCode ( void )

参数

此函数没有参数。

返回值

Returns the WriteConcernError's error code.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\WriteConcernError::getCode example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet");

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);

$writeConcern = new MongoDB\Driver\WriteConcern(2, 1);

try {
    $manager->executeBulkWrite('db.collection', $bulk, $writeConcern);
} catch(MongoDB\Driver\Exception\BulkWriteException $e) {
    var_dump($e->getWriteResult()->getWriteConcernError()->getCode());
}

?>

以上例程的输出类似于:

int(64)

参见

MongoDB\Driver\WriteConcernError::getInfo

Returns additional metadata for the WriteConcernError

说明

final public mixed MongoDB\Driver\WriteConcernError::getInfo ( void )

参数

此函数没有参数。

返回值

Returns additional metadata for the WriteConcernError, or NULL if no metadata is available.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\WriteConcernError::getInfo example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet");

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);

$writeConcern = new MongoDB\Driver\WriteConcern(2, 1);

try {
    $manager->executeBulkWrite('db.collection', $bulk, $writeConcern);
} catch(MongoDB\Driver\Exception\BulkWriteException $e) {
    var_dump($e->getWriteResult()->getWriteConcernError()->getInfo());
}

?>

以上例程的输出类似于:

object(stdClass)#1 (1) {
  ["wtimeout"]=>
  bool(true)
}

参见

MongoDB\Driver\WriteConcernError::getMessage

Returns the WriteConcernError's error message

说明

final public string MongoDB\Driver\WriteConcernError::getMessage ( void )

参数

此函数没有参数。

返回值

Returns the WriteConcernError's error message.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\WriteConcernError::getMessage example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet");

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);

$writeConcern = new MongoDB\Driver\WriteConcern(2, 1);

try {
    $manager->executeBulkWrite('db.collection', $bulk, $writeConcern);
} catch(MongoDB\Driver\Exception\BulkWriteException $e) {
    var_dump($e->getWriteResult()->getWriteConcernError()->getMessage());
}

?>

以上例程的输出类似于:

string(33) "waiting for replication timed out"

参见

简介

The MongoDB\Driver\WriteError class encapsulates information about a write error and may be returned as an array element from MongoDB\Driver\WriteResult::getWriteErrors.

类摘要

MongoDB\Driver\WriteError

final class MongoDB\Driver\WriteError {

/* 方法 */

final public int getCode ( void )

final public int getIndex ( void )

final public mixed getInfo ( void )

final public string getMessage ( void )

}

MongoDB\Driver\WriteError::getCode

Returns the WriteError's error code

说明

final public int MongoDB\Driver\WriteError::getCode ( void )

参数

此函数没有参数。

返回值

Returns the WriteError's error code.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\WriteError::getCode example

<?php

$manager = new MongoDB\Driver\Manager;

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 1]);

try {
    $manager->executeBulkWrite('db.collection', $bulk);
} catch(MongoDB\Driver\Exception\BulkWriteException $e) {
    var_dump($e->getWriteResult()->getWriteErrors()[0]->getCode());
}

?>

以上例程的输出类似于:

int(11000)

MongoDB\Driver\WriteError::getIndex

Returns the index of the write operation corresponding to this WriteError

说明

final public int MongoDB\Driver\WriteError::getIndex ( void )

参数

此函数没有参数。

返回值

Returns the index of the write operation (from MongoDB\Driver\BulkWrite) corresponding to this WriteError.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\WriteError::getIndex example

<?php

$manager = new MongoDB\Driver\Manager;

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 1]);

try {
    $manager->executeBulkWrite('db.collection', $bulk);
} catch(MongoDB\Driver\Exception\BulkWriteException $e) {
    var_dump($e->getWriteResult()->getWriteErrors()[0]->getIndex());
}

?>

以上例程的输出类似于:

int(1)

参见

  • MongoDB\Driver\BulkWrite

MongoDB\Driver\WriteError::getInfo

Returns additional metadata for the WriteError

说明

final public mixed MongoDB\Driver\WriteError::getInfo ( void )

参数

此函数没有参数。

返回值

Returns additional metadata for the WriteError, or NULL if no metadata is available.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

MongoDB\Driver\WriteError::getMessage

Returns the WriteError's error message

说明

final public string MongoDB\Driver\WriteError::getMessage ( void )

参数

此函数没有参数。

返回值

Returns the WriteError's error message.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\WriteError::getMessage example

<?php

$manager = new MongoDB\Driver\Manager;

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 1]);

try {
    $manager->executeBulkWrite('db.collection', $bulk);
} catch(MongoDB\Driver\Exception\BulkWriteException $e) {
    var_dump($e->getWriteResult()->getWriteErrors()[0]->getMessage());
}

?>

以上例程的输出类似于:

string(70) "E11000 duplicate key error index: db.collection.$_id_ dup key: { : 1 }"

简介

The MongoDB\Driver\WriteResult class encapsulates information about an executed MongoDB\Driver\BulkWrite and may be returned by MongoDB\Driver\Manager::executeBulkWrite.

类摘要

MongoDB\Driver\WriteResult

final class MongoDB\Driver\WriteResult {

/* 方法 */

final public integer|null getDeletedCount ( void )

final public integer|null getInsertedCount ( void )

final public integer|null getMatchedCount ( void )

final public integer|null getModifiedCount ( void )

final public MongoDB\Driver\Server getServer ( void )

final public integer|null getUpsertedCount ( void )

final public array getUpsertedIds ( void )

final public MongoDB\Driver\WriteConcernError|null getWriteConcernError ( void )

final public array getWriteErrors ( void )

final public bool isAcknowledged ( void )

}

MongoDB\Driver\WriteResult::getDeletedCount

Returns the number of documents deleted

说明

final public integer|null MongoDB\Driver\WriteResult::getDeletedCount ( void )

参数

此函数没有参数。

返回值

Returns the number of documents deleted, or NULL if the write was not acknowledged.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\WriteResult::getDeletedCount example

<?php

$manager = new MongoDB\Driver\Manager;

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->update(['x' => 1], ['$set' => ['y' => 3]]);
$bulk->update(['x' => 2], ['$set' => ['y' => 1]], ['upsert' => true]);
$bulk->update(['x' => 3], ['$set' => ['y' => 2]], ['upsert' => true]);
$bulk->delete(['x' => 1]);

$result = $manager->executeBulkWrite('db.collection', $bulk);

var_dump($result->getDeletedCount());

?>

以上例程会输出:

int(1)

参见

  • MongoDB\Driver\WriteResult::isAcknowledged

MongoDB\Driver\WriteResult::getInsertedCount

Returns the number of documents inserted (excluding upserts)

说明

final public integer|null MongoDB\Driver\WriteResult::getInsertedCount ( void )

参数

此函数没有参数。

返回值

Returns the number of documents inserted (excluding upserts), or NULL if the write was not acknowledged.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\WriteResult::getInsertedCount example

<?php

$manager = new MongoDB\Driver\Manager;

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->update(['x' => 1], ['$set' => ['y' => 3]]);
$bulk->update(['x' => 2], ['$set' => ['y' => 1]], ['upsert' => true]);
$bulk->update(['x' => 3], ['$set' => ['y' => 2]], ['upsert' => true]);
$bulk->delete(['x' => 1]);

$result = $manager->executeBulkWrite('db.collection', $bulk);

var_dump($result->getInsertedCount());

?>

以上例程会输出:

int(1)

参见

  • MongoDB\Driver\WriteResult::isAcknowledged

MongoDB\Driver\WriteResult::getMatchedCount

Returns the number of documents selected for update

说明

final public integer|null MongoDB\Driver\WriteResult::getMatchedCount ( void )

If the update 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 MongoDB\Driver\WriteResult::getModifiedCount.

参数

此函数没有参数。

返回值

Returns the number of documents selected for update, or NULL if the write was not acknowledged.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\WriteResult::getMatchedCount example

<?php

$manager = new MongoDB\Driver\Manager;

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->update(['x' => 1], ['$set' => ['y' => 3]]);
$bulk->update(['x' => 2], ['$set' => ['y' => 1]], ['upsert' => true]);
$bulk->update(['x' => 3], ['$set' => ['y' => 2]], ['upsert' => true]);
$bulk->delete(['x' => 1]);

$result = $manager->executeBulkWrite('db.collection', $bulk);

var_dump($result->getMatchedCount());

?>

以上例程会输出:

int(1)

参见

  • MongoDB\Driver\WriteResult::getModifiedCount
  • MongoDB\Driver\WriteResult::isAcknowledged

MongoDB\Driver\WriteResult::getModifiedCount

Returns the number of existing documents updated

说明

final public integer|null MongoDB\Driver\WriteResult::getModifiedCount ( void )

If the update 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 MongoDB\Driver\WriteResult::getMatchedCount.

参数

此函数没有参数。

返回值

Returns the number of existing documents updated, or NULL if the write was not acknowledged.

The modified count is not available on versions of MongoDB before 2.6, which used the legacy wire protocol version (i.e. OP_UPDATE). If this is the case, the modified count will also be NULL.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\WriteResult::getModifiedCount example

<?php

$manager = new MongoDB\Driver\Manager;

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->update(['x' => 1], ['$set' => ['y' => 3]]);
$bulk->update(['x' => 2], ['$set' => ['y' => 1]], ['upsert' => true]);
$bulk->update(['x' => 3], ['$set' => ['y' => 2]], ['upsert' => true]);
$bulk->delete(['x' => 1]);

$result = $manager->executeBulkWrite('db.collection', $bulk);

var_dump($result->getModifiedCount());

?>

以上例程会输出:

int(1)

参见

  • MongoDB\Driver\WriteResult::getMatchedCount
  • MongoDB\Driver\WriteResult::isAcknowledged

MongoDB\Driver\WriteResult::getServer

Returns the server associated with this write result

说明

final public MongoDB\Driver\Server MongoDB\Driver\WriteResult::getServer ( void )

Returns the MongoDB\Driver\Server associated with this write result. This is the server that executed the MongoDB\Driver\BulkWrite.

参数

此函数没有参数。

返回值

Returns the MongoDB\Driver\Server associated with this write result.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\WriteResult::getServer example

<?php

$manager = new MongoDB\Driver\Manager;
$server = $manager->selectServer(new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY));

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);

$result = $server->executeBulkWrite('db.collection', $bulk);

var_dump($result->getServer() == $server);

?>

以上例程会输出:

bool(true)

参见

  • MongoDB\Driver\Server

MongoDB\Driver\WriteResult::getUpsertedCount

Returns the number of documents inserted by an upsert

说明

final public integer|null MongoDB\Driver\WriteResult::getUpsertedCount ( void )

参数

此函数没有参数。

返回值

Returns the number of documents inserted by an upsert.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\WriteResult::getUpsertedCount example

<?php

$manager = new MongoDB\Driver\Manager;

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->update(['x' => 1], ['$set' => ['y' => 3]]);
$bulk->update(['x' => 2], ['$set' => ['y' => 1]], ['upsert' => true]);
$bulk->update(['x' => 3], ['$set' => ['y' => 2]], ['upsert' => true]);
$bulk->delete(['x' => 1]);

$result = $manager->executeBulkWrite('db.collection', $bulk);

var_dump($result->getUpsertedCount());

?>

以上例程会输出:

int(2)

参见

  • MongoDB\Driver\WriteResult::getUpsertedIds
  • MongoDB\Driver\WriteResult::isAcknowledged

MongoDB\Driver\WriteResult::getUpsertedIds

Returns an array of identifiers for upserted documents

说明

final public array MongoDB\Driver\WriteResult::getUpsertedIds ( void )

参数

此函数没有参数。

返回值

Returns an array of identifiers (i.e. "_id" field values) for upserted documents. The array keys will correspond to the index of the write operation (from MongoDB\Driver\BulkWrite) responsible for the upsert.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\WriteResult::getUpsertedIds example

<?php

$manager = new MongoDB\Driver\Manager;

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->update(['x' => 1], ['$set' => ['y' => 3]]);
$bulk->update(['x' => 2], ['$set' => ['y' => 1]], ['upsert' => true]);
$bulk->update(['x' => 3], ['$set' => ['y' => 2]], ['upsert' => true]);
$bulk->delete(['x' => 1]);

$result = $manager->executeBulkWrite('db.collection', $bulk);

var_dump($result->getUpsertedIds());

?>

以上例程的输出类似于:

array(2) {
  [2]=>
  object(MongoDB\BSON\ObjectId)#4 (1) {
    ["oid"]=>
    string(24) "580e62a224f2302f191b880b"
  }
  [3]=>
  object(MongoDB\BSON\ObjectId)#5 (1) {
    ["oid"]=>
    string(24) "580e62a224f2302f191b880c"
  }
}

参见

  • MongoDB\Driver\WriteResult::getUpsertedCount
  • MongoDB\Driver\WriteResult::isAcknowledged

MongoDB\Driver\WriteResult::getWriteConcernError

Returns any write concern error that occurred

说明

final public MongoDB\Driver\WriteConcernError|null MongoDB\Driver\WriteResult::getWriteConcernError ( void )

参数

此函数没有参数。

返回值

Returns a MongoDB\Driver\WriteConcernError if a write concern error was encountered during the write operation, and NULL otherwise.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\WriteResult::getWriteConcernError example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet");

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);

$writeConcern = new MongoDB\Driver\WriteConcern(2, 1);

try {
    $manager->executeBulkWrite('db.collection', $bulk, $writeConcern);
} catch(MongoDB\Driver\Exception\BulkWriteException $e) {
    var_dump($e->getWriteResult()->getWriteConcernError());
}

?>

以上例程的输出类似于:

object(MongoDB\Driver\WriteConcernError)#6 (3) {
  ["message"]=>
  string(33) "waiting for replication timed out"
  ["code"]=>
  int(64)
  ["info"]=>
  object(stdClass)#7 (1) {
    ["wtimeout"]=>
    bool(true)
  }
}

参见

MongoDB\Driver\WriteResult::getWriteErrors

Returns any write errors that occurred

说明

final public array MongoDB\Driver\WriteResult::getWriteErrors ( void )

参数

此函数没有参数。

返回值

Returns an array of MongoDB\Driver\WriteError objects for any write errors encountered during the write operation. The array will be empty if no write errors occurred.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\WriteResult::getWriteErrors with a single error

<?php

$manager = new MongoDB\Driver\Manager;

/* By default, bulk write operations are executed serially in order and
 * execution will stop after the first error.
 */
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 2]);
$bulk->insert(['_id' => 2]);
$bulk->insert(['_id' => 3]);
$bulk->insert(['_id' => 4]);
$bulk->insert(['_id' => 4]);

try {
    $result = $manager->executeBulkWrite('db.collection', $bulk);
} catch (MongoDB\Driver\Exception\BulkWriteException $e) {
    var_dump($e->getWriteResult()->getWriteErrors());
}

?>

以上例程的输出类似于:

array(1) {
  [0]=>
  object(MongoDB\Driver\WriteError)#5 (4) {
    ["message"]=>
    string(81) "E11000 duplicate key error collection: db.collection index: _id_ dup key: { : 2 }"
    ["code"]=>
    int(11000)
    ["index"]=>
    int(2)
    ["info"]=>
    NULL
  }
}

示例 #2 MongoDB\Driver\WriteResult::getWriteErrors with multiple errors

<?php

$manager = new MongoDB\Driver\Manager;

/* The "ordered" option may be used to allow bulk write operations to continue
 * executing after the first error is encountered.
 */
$bulk = new MongoDB\Driver\BulkWrite(['ordered' => false]);
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 2]);
$bulk->insert(['_id' => 2]);
$bulk->insert(['_id' => 3]);
$bulk->insert(['_id' => 4]);
$bulk->insert(['_id' => 4]);

try {
    $result = $manager->executeBulkWrite('db.collection', $bulk);
} catch (MongoDB\Driver\Exception\BulkWriteException $e) {
    var_dump($e->getWriteResult()->getWriteErrors());
}

?>

以上例程的输出类似于:

array(2) {
  [0]=>
  object(MongoDB\Driver\WriteError)#5 (4) {
    ["message"]=>
    string(81) "E11000 duplicate key error collection: db.collection index: _id_ dup key: { : 2 }"
    ["code"]=>
    int(11000)
    ["index"]=>
    int(2)
    ["info"]=>
    NULL
  }
  [1]=>
  object(MongoDB\Driver\WriteError)#6 (4) {
    ["message"]=>
    string(81) "E11000 duplicate key error collection: db.collection index: _id_ dup key: { : 4 }"
    ["code"]=>
    int(11000)
    ["index"]=>
    int(5)
    ["info"]=>
    NULL
  }
}

参见

  • MongoDB\Driver\WriteError

MongoDB\Driver\WriteResult::isAcknowledged

Returns whether the write was acknowledged

说明

final public bool MongoDB\Driver\WriteResult::isAcknowledged ( void )

If the write is acknowledged, other count fields will be available on the MongoDB\Driver\WriteResult object.

参数

此函数没有参数。

返回值

Returns TRUE if the write was acknowledged, and FALSE otherwise.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\Driver\WriteResult::isAcknowledged with acknowledged write concern

<?php

$manager = new MongoDB\Driver\Manager;

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);

$result = $manager->executeBulkWrite('db.collection', $bulk);

var_dump($result->isAcknowledged());

?>

以上例程会输出:

bool(true)

示例 #2 MongoDB\Driver\WriteResult::isAcknowledged with unacknowledged write concern

<?php

$manager = new MongoDB\Driver\Manager;

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);

$result = $manager->executeBulkWrite('db.collection', $bulk, new MongoDB\Driver\WriteConcern(0));

var_dump($result->isAcknowledged());

?>

以上例程会输出:

bool(false)

参见

BSON type classes and serialization functions

目录

MongoDB\BSON\fromJSON

Returns the BSON representation of a JSON value

说明

string MongoDB\BSON\fromJSON ( string $json )

Converts an » extended JSON string to its BSON representation.

参数

json (string)
JSON value to be converted.

返回值

The serialized BSON document as a binary string.

错误/异常

  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the JSON value cannot be converted to BSON (e.g. due to a syntax error).

范例

示例 #1 MongoDB\BSON\fromJSON example

<?php

$json = '{ "_id": { "$oid": "563143b280d2387c91807965" } }';
$bson = MongoDB\BSON\fromJSON($json);
$value = MongoDB\BSON\toPHP($bson);
var_dump($value);

?>

以上例程会输出:

object(stdClass)#2 (1) {
  ["_id"]=>
  object(MongoDB\BSON\ObjectId)#1 (1) {
    ["oid"]=>
    string(24) "563143b280d2387c91807965"
  }
}

参见

MongoDB\BSON\fromPHP

Returns the BSON representation of a PHP value

说明

string MongoDB\BSON\fromPHP ( array|object $value )

Serializes a PHP array or object (e.g. document) to its » BSON representation. The returned binary string will describe a BSON document.

参数

value (array|object)
PHP value to be serialized.

返回值

The serialized BSON document as a binary string.

错误/异常

  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the PHP value cannot be converted to BSON. Possible reasons include, but are not limited to, encountering an unexpected MongoDB\BSON\Type instance or MongoDB\BSON\Serializable::bsonSerialize failing to return an array or stdClass.

范例

示例 #1 MongoDB\BSON\fromPHP example

<?php

$bson = MongoDB\BSON\fromPHP(['foo' => 1]);
echo bin2hex($bson), "\n";

?>

以上例程会输出:

0e00000010666f6f000100000000cat 

参见

MongoDB\BSON\toCanonicalExtendedJSON

Returns the Canonical Extended JSON representation of a BSON value

说明

string MongoDB\BSON\toCanonicalExtendedJSON ( string $bson )

Converts a BSON string to its » Canonical Extended JSON representation. The canonical format prefers type fidelity at the expense of concise output and is most suited for producing output that can be converted back to BSON without any loss of type information (e.g. numeric types will remain differentiated).

参数

bson (string)
BSON value to be converted.

返回值

The converted JSON value.

错误/异常

  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the input did not contain exactly one BSON document. Possible reasons include, but are not limited to, invalid BSON, extra data (after reading one BSON document), or an unexpected » libbson error.

范例

示例 #1 MongoDB\BSON\toCanonicalExtendedJSON example

<?php

$documents = [
    [ 'null' => null ],
    [ 'boolean' => true ],
    [ 'string' => 'foo' ],
    [ 'int32' => 123 ],
    [ 'int64' => 4294967295 ],
    [ 'double' => 1.0, ],
    [ 'nan' => NAN ],
    [ 'pos_inf' => INF ],
    [ 'neg_inf' => -INF ],
    [ 'array' => [ 'foo', 'bar' ]],
    [ 'document' => [ 'foo' => 'bar' ]],
    [ 'oid' => new MongoDB\BSON\ObjectId('56315a7c6118fd1b920270b1') ],
    [ 'dec128' => new MongoDB\BSON\Decimal128('1234.5678') ],
    [ 'binary' => new MongoDB\BSON\Binary('foo', MongoDB\BSON\Binary::TYPE_GENERIC) ],
    [ 'date' => new MongoDB\BSON\UTCDateTime(1445990400000) ],
    [ 'timestamp' => new MongoDB\BSON\Timestamp(1234, 5678) ],
    [ 'regex' => new MongoDB\BSON\Regex('pattern', 'i') ],
    [ 'code' => new MongoDB\BSON\Javascript('function() { return 1; }') ],
    [ 'code_ws' => new MongoDB\BSON\Javascript('function() { return a; }', ['a' => 1]) ],
    [ 'minkey' => new MongoDB\BSON\MinKey ],
    [ 'maxkey' => new MongoDB\BSON\MaxKey ],
];

foreach ($documents as $document) {
    $bson = MongoDB\BSON\fromPHP($document);
    echo MongoDB\BSON\toCanonicalExtendedJSON($bson), "\n";
}

?>

以上例程会输出:

{ "null" : null }
{ "boolean" : true }
{ "string" : "foo" }
{ "int32" : { "$numberInt" : "123" } }
{ "int64" : { "$numberLong" : "4294967295"} }
{ "double" : { "$numberDouble" : "1.0" } }
{ "nan" : { "$numberDouble" : "NaN" } }
{ "pos_inf" : { "$numberDouble" : "Infinity" } }
{ "neg_inf" : { "$numberDouble" : "-Infinity" } }
{ "array" : [ "foo", "bar" ] }
{ "document" : { "foo" : "bar" } }
{ "oid" : { "$oid" : "56315a7c6118fd1b920270b1" } }
{ "dec128" : { "$numberDecimal" : "1234.5678" } }
{ "binary" : { "$binary" : { "base64": "Zm9v", "subType" : "00" } } }
{ "date" : { "$date" : { "$numberLong" : "1445990400000" } } }
{ "timestamp" : { "$timestamp" : { "t" : 5678, "i" : 1234 } } }
{ "regex" : { "$regularExpression" : { "pattern" : "pattern", "options" : "i" } } }
{ "code" : { "$code" : "function() { return 1; }" } }
{ "code_ws" : { "$code" : "function() { return a; }", "$scope" : { "a" : { "$numberInt" : "1" } } } }
{ "minkey" : { "$minKey" : 1 } }
{ "maxkey" : { "$maxKey" : 1 } }

参见

MongoDB\BSON\toJSON

Returns the Legacy Extended JSON representation of a BSON value

说明

string MongoDB\BSON\toJSON ( string $bson )

Converts a BSON string to its » Legacy Extended JSON representation.

Note: There exist several JSON formats for representing BSON. This function implements the "strict mode" defined in » MongoDB Extended JSON, which has been superseded by the canonical and relaxed formats defined in the » Extended JSON Specification and implemented by class="function">MongoDB\BSON\toCanonicalExtendedJSON and MongoDB\BSON\toRelaxedExtendedJSON, respectively.

Warning

» JSON does not support NAN and INF and MongoDB's Legacy Extended JSON format does not define an alternative representation for these values (» libbson will output nan and inf literals, which may not be parsed as valid JSON). If you are working with BSON that may contain non-finite numbers, please use MongoDB\BSON\toCanonicalExtendedJSON or MongoDB\BSON\toRelaxedExtendedJSON.

参数

bson (string)
BSON value to be converted.

返回值

The converted JSON value.

错误/异常

  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the input did not contain exactly one BSON document. Possible reasons include, but are not limited to, invalid BSON, extra data (after reading one BSON document), or an unexpected » libbson error.

范例

示例 #1 MongoDB\BSON\toJSON example

<?php

$documents = [
    [ 'null' => null ],
    [ 'boolean' => true ],
    [ 'string' => 'foo' ],
    [ 'int32' => 123 ],
    [ 'int64' => 4294967295 ],
    [ 'double' => 1.0, ],
    [ 'nan' => NAN ],
    [ 'pos_inf' => INF ],
    [ 'neg_inf' => -INF ],
    [ 'array' => [ 'foo', 'bar' ]],
    [ 'document' => [ 'foo' => 'bar' ]],
    [ 'oid' => new MongoDB\BSON\ObjectId('56315a7c6118fd1b920270b1') ],
    [ 'dec128' => new MongoDB\BSON\Decimal128('1234.5678') ],
    [ 'binary' => new MongoDB\BSON\Binary('foo', MongoDB\BSON\Binary::TYPE_GENERIC) ],
    [ 'date' => new MongoDB\BSON\UTCDateTime(1445990400000) ],
    [ 'timestamp' => new MongoDB\BSON\Timestamp(1234, 5678) ],
    [ 'regex' => new MongoDB\BSON\Regex('pattern', 'i') ],
    [ 'code' => new MongoDB\BSON\Javascript('function() { return 1; }') ],
    [ 'code_ws' => new MongoDB\BSON\Javascript('function() { return a; }', ['a' => 1]) ],
    [ 'minkey' => new MongoDB\BSON\MinKey ],
    [ 'maxkey' => new MongoDB\BSON\MaxKey ],
];

foreach ($documents as $document) {
    $bson = MongoDB\BSON\fromPHP($document);
    echo MongoDB\BSON\toJSON($bson), "\n";
}

?>

以上例程会输出:

{ "null" : null }
{ "boolean" : true }
{ "string" : "foo" }
{ "int32" : 123 }
{ "int64" : 4294967295 }
{ "double" : 1.0 }
{ "nan" : nan }
{ "pos_inf" : inf }
{ "neg_inf" : -inf }
{ "array" : [ "foo", "bar" ] }
{ "document" : { "foo" : "bar" } }
{ "oid" : { "$oid" : "56315a7c6118fd1b920270b1" } }
{ "dec128" : { "$numberDecimal" : "1234.5678" } }
{ "binary" : { "$binary" : "Zm9v", "$type" : "00" } }
{ "date" : { "$date" : 1445990400000 } }
{ "timestamp" : { "$timestamp" : { "t" : 5678, "i" : 1234 } } }
{ "regex" : { "$regex" : "pattern", "$options" : "i" } }
{ "code" : { "$code" : "function() { return 1; }" } }
{ "code_ws" : { "$code" : "function() { return a; }", "$scope" : { "a" : 1 } } }
{ "minkey" : { "$minKey" : 1 } }
{ "maxkey" : { "$maxKey" : 1 } }

参见

MongoDB\BSON\toPHP

Returns the PHP representation of a BSON value

说明

array|object MongoDB\BSON\toPHP ( string $bson [, array $typeMap = array() ] )

Unserializes a BSON document (i.e. binary string) to its PHP representation. The typeMap paramater may be used to control the PHP types used for converting BSON arrays and documents (both root and embedded).

Warning

Fields containing deprecated BSON types (i.e. undefined, symbol, DBPointer) are represented only by bare-bones objects of the classes MongoDB\BSON\Undefined, MongoDB\BSON\Symbol, and MongoDB\BSON\DBPointer, when converting BSON to PHP. These objects are created from BSON data and used for storing these types back into the database, but can not be instantiated as they have a private constructor.

参数

bson (string)
BSON value to be unserialized.

typeMap (array)
Type map configuration.

返回值

The unserialized PHP value.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException if a class in the type map cannot be instantiated or does not implement MongoDB\BSON\Unserializable.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the input did not contain exactly one BSON document. Possible reasons include, but are not limited to, invalid BSON, extra data (after reading one BSON document), or an unexpected » libbson error.

更新日志

版本说明
1.4.0If the input contains an unsupported, deprecated BSON type, the driver will now no longer log a warning to the debug log, but instead will create an object representing this type.
1.3.2MongoDB\Driver\Exception\UnexpectedValueException is no longer thrown if the input contains an unsupported, deprecated BSON type. Such types will be ignored (as they were in versions before 1.3.0), although the driver will now log a warning to the debug log (see: mongodb.debug).
1.3.0MongoDB\Driver\Exception\UnexpectedValueException is thrown if the input contains an unsupported, deprecated BSON type. Previously, such types were ignored.

范例

示例 #1 MongoDB\BSON\toPHP example

<?php

$bson = hex2bin('0e00000010666f6f000100000000');
$value = MongoDB\BSON\toPHP($bson);
var_dump($value);

?>

以上例程会输出:

object(stdClass)#1 (1) {
  ["foo"]=>
  int(1)
}

参见

MongoDB\BSON\toRelaxedExtendedJSON

Returns the Relaxed Extended JSON representation of a BSON value

说明

string MongoDB\BSON\toRelaxedExtendedJSON ( string $bson )

Converts a BSON string to its » Relaxed Extended JSON representation. The relaxed format prefers use of JSON type primitives at the expense of type fidelity and is most suited for producing output that can be easily consumed by web APIs and humans.

参数

bson (string)
BSON value to be converted.

返回值

The converted JSON value.

错误/异常

  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the input did not contain exactly one BSON document. Possible reasons include, but are not limited to, invalid BSON, extra data (after reading one BSON document), or an unexpected » libbson error.

范例

示例 #1 MongoDB\BSON\toRelaxedExtendedJSON example

<?php

$documents = [
    [ 'null' => null ],
    [ 'boolean' => true ],
    [ 'string' => 'foo' ],
    [ 'int32' => 123 ],
    [ 'int64' => 4294967295 ],
    [ 'double' => 1.0, ],
    [ 'nan' => NAN ],
    [ 'pos_inf' => INF ],
    [ 'neg_inf' => -INF ],
    [ 'array' => [ 'foo', 'bar' ]],
    [ 'document' => [ 'foo' => 'bar' ]],
    [ 'oid' => new MongoDB\BSON\ObjectId('56315a7c6118fd1b920270b1') ],
    [ 'dec128' => new MongoDB\BSON\Decimal128('1234.5678') ],
    [ 'binary' => new MongoDB\BSON\Binary('foo', MongoDB\BSON\Binary::TYPE_GENERIC) ],
    [ 'date' => new MongoDB\BSON\UTCDateTime(1445990400000) ],
    [ 'timestamp' => new MongoDB\BSON\Timestamp(1234, 5678) ],
    [ 'regex' => new MongoDB\BSON\Regex('pattern', 'i') ],
    [ 'code' => new MongoDB\BSON\Javascript('function() { return 1; }') ],
    [ 'code_ws' => new MongoDB\BSON\Javascript('function() { return a; }', ['a' => 1]) ],
    [ 'minkey' => new MongoDB\BSON\MinKey ],
    [ 'maxkey' => new MongoDB\BSON\MaxKey ],
];

foreach ($documents as $document) {
    $bson = MongoDB\BSON\fromPHP($document);
    echo MongoDB\BSON\toRelaxedExtendedJSON($bson), "\n";
}

?>

以上例程会输出:

{ "null" : null }
{ "boolean" : true }
{ "string" : "foo" }
{ "int32" : 123 }
{ "int64" : 4294967295 }
{ "double" : 1.0 }
{ "nan" : { "$numberDouble" : "NaN" } }
{ "pos_inf" : { "$numberDouble" : "Infinity" } }
{ "neg_inf" : { "$numberDouble" : "-Infinity" } }
{ "array" : [ "foo", "bar" ] }
{ "document" : { "foo" : "bar" } }
{ "oid" : { "$oid" : "56315a7c6118fd1b920270b1" } }
{ "dec128" : { "$numberDecimal" : "1234.5678" } }
{ "binary" : { "$binary" : { "base64": "Zm9v", "subType" : "00" } } }
{ "date" : { "$date" : "2015-10-28T00:00:00Z" } }
{ "timestamp" : { "$timestamp" : { "t" : 5678, "i" : 1234 } } }
{ "regex" : { "$regularExpression" : { "pattern" : "pattern", "options" : "i" } } }
{ "code" : { "$code" : "function() { return 1; }" } }
{ "code_ws" : { "$code" : "function() { return a; }", "$scope" : { "a" : 1 } } }
{ "minkey" : { "$minKey" : 1 } }
{ "maxkey" : { "$maxKey" : 1 } }

参见

目录

简介

BSON type for binary data (i.e. array of bytes). Binary values also have a subtype, which is used to indicate what kind of data is in the byte array. Subtypes from zero to 127 are predefined or reserved. Subtypes from 128-255 are user-defined.

类摘要

MongoDB\BSON\Binary

final class MongoDB\BSON\Binary implements MongoDB\BSON\BinaryInterface , MongoDB\BSON\Type , Serializable , JsonSerializable {

/* Constants */

const integer MongoDB\BSON\Binary::TYPE_GENERIC = 0 ;

const integer MongoDB\BSON\Binary::TYPE_FUNCTION = 1 ;

const integer MongoDB\BSON\Binary::TYPE_OLD_BINARY = 2 ;

const integer MongoDB\BSON\Binary::TYPE_OLD_UUID = 3 ;

const integer MongoDB\BSON\Binary::TYPE_UUID = 4 ;

const integer MongoDB\BSON\Binary::TYPE_MD5 = 5 ;

const integer MongoDB\BSON\Binary::TYPE_ENCRYPTED = 6 ;

const integer MongoDB\BSON\Binary::TYPE_USER_DEFINED = 128 ;

/* 方法 */

final public __construct ( string $data , int $type )

final public string getData ( void )

final public int getType ( void )

final public mixed jsonSerialize ( void )

final public string serialize ( void )

final public string __toString ( void )

final public void unserialize ( string $serialized )

}

预定义常量

MongoDB\BSON\Binary::TYPE_GENERIC
Generic binary data.

MongoDB\BSON\Binary::TYPE_FUNCTION
Function.

MongoDB\BSON\Binary::TYPE_OLD_BINARY
Generic binary data (deprecated in favor of MongoDB\BSON\Binary::TYPE_GENERIC).

MongoDB\BSON\Binary::TYPE_OLD_UUID
Universally unique identifier (deprecated in favor of MongoDB\BSON\Binary::TYPE_UUID). When using this type, the Binary's data should be 16 bytes in length.

Historically, other drivers encoded values with this type based on their language conventions (e.g. varying endianness), which makes it non-portable. The PHP driver applies no special handling for encoding or decoding data with this type.

MongoDB\BSON\Binary::TYPE_UUID
Universally unique identifier. When using this type, the Binary's data should be 16 bytes in length and encoded according to » RFC 4122.

MongoDB\BSON\Binary::TYPE_MD5
MD5 hash. When using this type, the Binary's data should be 16 bytes in length.

MongoDB\BSON\Binary::TYPE_ENCRYPTED
Encrypted value. This subtype is used for client-side encryption.

MongoDB\BSON\Binary::TYPE_USER_DEFINED
User-defined type. While types between 0 and 127 are predefined or reserved, types between 128 and 255 are user-defined and may be used for anything.

更新日志

版本说明
1.3.0Implements MongoDB\BSON\BinaryInterface.
1.2.0Implements Serializable and JsonSerializable.

MongoDB\BSON\Binary::__construct

Construct a new Binary

说明

final public MongoDB\BSON\Binary::__construct ( string $data , int $type )

参数

data (string)
Binary data.

type (integer)
Unsigned 8-bit integer denoting the data's type.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if type is not an unsigned 8-bit integer.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if type is MongoDB\BSON\Binary::TYPE_UUID or MongoDB\BSON\Binary::TYPE_OLD_UUID and data is not exactly 16 bytes in length.

更新日志

版本说明
1.3.0MongoDB\Driver\Exception\InvalidArgumentException is thrown if type is MongoDB\BSON\Binary::TYPE_UUID or MongoDB\BSON\Binary::TYPE_OLD_UUID and data is not exactly 16 bytes in length.
1.1.3MongoDB\Driver\Exception\InvalidArgumentException is thrown if type is not an unsigned 8-bit integer.

范例

示例 #1 MongoDB\BSON\Binary::__construct example

<?php

$binary = new MongoDB\BSON\Binary('foo', MongoDB\BSON\Binary::TYPE_GENERIC);
var_dump($binary);

?>

以上例程会输出:

object(MongoDB\BSON\Binary)#1 (2) {
  ["data"]=>
  string(3) "foo"
  ["type"]=>
  int(0)
}

参见

MongoDB\BSON\Binary::getData

Returns the Binary's data

说明

final public string MongoDB\BSON\Binary::getData ( void )

参数

此函数没有参数。

返回值

Returns the Binary's data.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\BSON\Binary::getData example

<?php

$binary = new MongoDB\BSON\Binary('foo', MongoDB\BSON\Binary::TYPE_GENERIC);
var_dump($binary->getData());

?>

以上例程会输出:

string(3) "foo"

参见

MongoDB\BSON\Binary::getType

Returns the Binary's type

说明

final public int MongoDB\BSON\Binary::getType ( void )

参数

此函数没有参数。

返回值

Returns the Binary's type.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\BSON\Binary::getType example

<?php

$binary = new MongoDB\BSON\Binary('foo', MongoDB\BSON\Binary::TYPE_GENERIC);
var_dump($binary->getType());

?>

以上例程会输出:

int(0)

参见

MongoDB\BSON\Binary::jsonSerialize

Returns a representation that can be converted to JSON

说明

final public mixed MongoDB\BSON\Binary::jsonSerialize ( void )

参数

此函数没有参数。

返回值

Returns data which can be serialized by json_encode to produce an extended JSON representation of the MongoDB\BSON\Binary.

Note: The output is consistent with the MongoDB\BSON\toJSON function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by class="function">MongoDB\BSON\toRelaxedExtendedJSON and class="function">MongoDB\BSON\toCanonicalExtendedJSON, respectively.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • JsonSerializable::jsonSerialize
  • json_encode
  • MongoDB\BSON\toCanonicalExtendedJSON
  • MongoDB\BSON\toRelaxedExtendedJSON
  • » MongoDB Extended JSON

MongoDB\BSON\Binary::serialize

Serialize a Binary

说明

final public string MongoDB\BSON\Binary::serialize ( void )

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\BSON\Binary.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

MongoDB\BSON\Binary::__toString

Returns the Binary's data

说明

final public string MongoDB\BSON\Binary::__toString ( void )

此方法是该方法的别名: MongoDB\BSON\Binary::getData.

参数

此函数没有参数。

返回值

Returns the Binary's data.

范例

示例 #1 MongoDB\BSON\Binary::__toString example

<?php

var_dump((string) new MongoDB\BSON\Binary('foo', MongoDB\BSON\Binary::TYPE_GENERIC));

?>

以上例程会输出:

string(3) "foo"

参见

MongoDB\BSON\Binary::unserialize

Unserialize a Binary

说明

final public void MongoDB\BSON\Binary::unserialize ( string $serialized )

参数

serialized
The serialized MongoDB\BSON\Binary.

返回值

Returns the unserialized MongoDB\BSON\Binary.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

参见

简介

BSON type for the » Decimal128 floating-point format, which supports numbers with up to 34 decimal digits (i.e. significant digits) and an exponent range of −6143 to +6144.

Unlike the double BSON type (i.e. float in PHP), which only stores an approximation of the decimal values, the decimal data type stores the exact value. For example, MongoDB\BSON\Decimal128('9.99') has a precise value of 9.99 where as a double 9.99 would have an approximate value of 9.9900000000000002131628….

Note: class="classname">MongoDB\BSON\Decimal128 is only compatible with MongoDB 3.4+. Attempting to use the BSON type with an earlier version of MongoDB will result in an error.

类摘要

MongoDB\BSON\Decimal128

final class MongoDB\BSON\Decimal128 implements MongoDB\BSON\Decimal128Interface , MongoDB\BSON\Type , Serializable , JsonSerializable {

/* 方法 */

final public __construct ([ string $value ] )

final public mixed jsonSerialize ( void )

final public string serialize ( void )

final public string __toString ( void )

final public void unserialize ( string $serialized )

}

更新日志

版本说明
1.3.0Implements MongoDB\BSON\Decimal128Interface.
1.2.0Implements Serializable and JsonSerializable.

MongoDB\BSON\Decimal128::__construct

Construct a new Decimal128

说明

final public MongoDB\BSON\Decimal128::__construct ([ string $value ] )

Note: class="classname">MongoDB\BSON\Decimal128 is only compatible with MongoDB 3.4+. Attempting to use the BSON type with an earlier version of MongoDB will result in an error.

参数

value (string)
A decimal string.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if value is not a valid decimal string.

范例

示例 #1 MongoDB\BSON\Decimal128::__construct example

<?php

var_dump(new MongoDB\BSON\Decimal128(1234.5678));
var_dump(new MongoDB\BSON\Decimal128(NAN));
var_dump(new MongoDB\BSON\Decimal128(INF));

?>

以上例程的输出类似于:

object(MongoDB\BSON\Decimal128)#1 (1) {
  ["dec"]=>
  string(9) "1234.5678"
}
object(MongoDB\BSON\Decimal128)#1 (1) {
  ["dec"]=>
  string(3) "NaN"
}
object(MongoDB\BSON\Decimal128)#1 (1) {
  ["dec"]=>
  string(8) "Infinity"
}

参见

MongoDB\BSON\Decimal128::jsonSerialize

Returns a representation that can be converted to JSON

说明

final public mixed MongoDB\BSON\Decimal128::jsonSerialize ( void )

参数

此函数没有参数。

返回值

Returns data which can be serialized by json_encode to produce an extended JSON representation of the MongoDB\BSON\Decimal128.

Note: The output is consistent with the MongoDB\BSON\toJSON function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by class="function">MongoDB\BSON\toRelaxedExtendedJSON and class="function">MongoDB\BSON\toCanonicalExtendedJSON, respectively.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • JsonSerializable::jsonSerialize
  • json_encode
  • MongoDB\BSON\toCanonicalExtendedJSON
  • MongoDB\BSON\toRelaxedExtendedJSON
  • » MongoDB Extended JSON

MongoDB\BSON\Decimal128::serialize

Serialize a Decimal128

说明

final public string MongoDB\BSON\Decimal128::serialize ( void )

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\BSON\Decimal128.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

MongoDB\BSON\Decimal128::__toString

Returns the string representation of this Decimal128

说明

final public string MongoDB\BSON\Decimal128::__toString ( void )

参数

此函数没有参数。

返回值

Returns the string representation of this Decimal128.

范例

示例 #1 MongoDB\BSON\Decimal128::__toString example

<?php

var_dump((string) new MongoDB\BSON\Decimal128(1234.5678));
var_dump((string) new MongoDB\BSON\Decimal128(NAN));
var_dump((string) new MongoDB\BSON\Decimal128(INF));

?>

以上例程的输出类似于:

string(9) "1234.5678"
string(3) "NaN"
string(8) "Infinity"

参见

MongoDB\BSON\Decimal128::unserialize

Unserialize a Decimal128

说明

final public void MongoDB\BSON\Decimal128::unserialize ( string $serialized )

参数

serialized
The serialized MongoDB\BSON\Decimal128.

返回值

Returns the unserialized MongoDB\BSON\Decimal128.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

参见

简介

BSON type for Javascript code. An optional scope document may be specified that maps identifiers to values and defines the scope in which the code should be evaluated by the server.

Note: This BSON type is mainly used when executing database commands that take a Javascript function as a parameter, such as » mapReduce.

类摘要

MongoDB\BSON\Javascript

final class MongoDB\BSON\Javascript implements MongoDB\BSON\JavascriptInterface , MongoDB\BSON\Type , Serializable , JsonSerializable {

/* 方法 */

final public __construct ( string $code [, array|object $scope ] )

final public string getCode ( void )

final public object|null getScope ( void )

final public mixed jsonSerialize ( void )

final public string serialize ( void )

final public string __toString ( void )

final public void unserialize ( string $serialized )

}

更新日志

版本说明
1.3.0Implements MongoDB\BSON\JavascriptInterface.
1.2.0Implements Serializable and JsonSerializable.

MongoDB\BSON\Javascript::__construct

Construct a new Javascript

说明

final public MongoDB\BSON\Javascript::__construct ( string $code [, array|object $scope ] )

参数

code (string)
Javascript code.

scope (array|object)
Javascript scope.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if code contains null bytes.

更新日志

版本说明
1.2.0MongoDB\Driver\Exception\InvalidArgumentException is thrown if code contains null bytes. Previously, values would be truncated at the first null byte.

范例

示例 #1 MongoDB\BSON\Javascript::__construct example

<?php

$code = new MongoDB\BSON\Javascript('function() { return 1; }');
var_dump($code);

$codews = new MongoDB\BSON\Javascript('function() { return foo; }', ['foo' => 'bar']);
var_dump($codews);

?>

以上例程会输出:

object(MongoDB\BSON\Javascript)#1 (2) {
  ["javascript"]=>
  string(24) "function() { return 1; }"
  ["scope"]=>
  object(stdClass)#2 (0) {
  }
}
object(MongoDB\BSON\Javascript)#2 (2) {
  ["javascript"]=>
  string(26) "function() { return foo; }"
  ["scope"]=>
  object(stdClass)#1 (1) {
    ["foo"]=>
    string(3) "bar"
  }
}

参见

MongoDB\BSON\Javascript::getCode

Returns the Javascript's code

说明

final public string MongoDB\BSON\Javascript::getCode ( void )

参数

此函数没有参数。

返回值

Returns the Javascript's code.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\BSON\Javascript::getCode example

<?php

$js = new MongoDB\BSON\Javascript('function foo(bar) { return bar; }');
var_dump($js->getCode());

?>

以上例程会输出:

string(33) "function foo(bar) { return bar; }"

参见

MongoDB\BSON\Javascript::getScope

Returns the Javascript's scope document

说明

final public object|null MongoDB\BSON\Javascript::getScope ( void )

参数

此函数没有参数。

返回值

Returns the Javascript's scope document.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\BSON\Javascript::getScope example

<?php

$js = new MongoDB\BSON\Javascript('function foo(bar) { return bar; }');
var_dump($js->getScope());

$js = new MongoDB\BSON\Javascript('function foo() { return foo; }', ['foo' => 42]);
var_dump($js->getScope());

?>

以上例程会输出:

NULL
object(stdClass)#1 (1) {
  ["foo"]=>
  int(42)
}

参见

MongoDB\BSON\Javascript::jsonSerialize

Returns a representation that can be converted to JSON

说明

final public mixed MongoDB\BSON\Javascript::jsonSerialize ( void )

参数

此函数没有参数。

返回值

Returns data which can be serialized by json_encode to produce an extended JSON representation of the MongoDB\BSON\Javascript.

Note: The output is consistent with the MongoDB\BSON\toJSON function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by class="function">MongoDB\BSON\toRelaxedExtendedJSON and class="function">MongoDB\BSON\toCanonicalExtendedJSON, respectively.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • JsonSerializable::jsonSerialize
  • json_encode
  • MongoDB\BSON\toCanonicalExtendedJSON
  • MongoDB\BSON\toRelaxedExtendedJSON
  • » MongoDB Extended JSON

MongoDB\BSON\Javascript::serialize

Serialize a Javascript

说明

final public string MongoDB\BSON\Javascript::serialize ( void )

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\BSON\Javascript.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

MongoDB\BSON\Javascript::__toString

Returns the Javascript's code

说明

final public string MongoDB\BSON\Javascript::__toString ( void )

此方法是该方法的别名: MongoDB\BSON\Javascript::getCode.

参数

此函数没有参数。

返回值

Returns the Javascript's code.

范例

示例 #1 MongoDB\BSON\Javascript::__toString example

<?php

var_dump((string) new MongoDB\BSON\Javascript('function foo(bar) { return bar; }'));

?>

以上例程会输出:

string(33) "function foo(bar) { return bar; }"

参见

MongoDB\BSON\Javascript::unserialize

Unserialize a Javascript

说明

final public void MongoDB\BSON\Javascript::unserialize ( string $serialized )

参数

serialized
The serialized MongoDB\BSON\Javascript.

返回值

Returns the unserialized MongoDB\BSON\Javascript.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

参见

简介

Special BSON type which compares higher than all other possible BSON element values.

Note: This is an internal MongoDB type used for indexing and sharding.

类摘要

MongoDB\BSON\MaxKey

final class MongoDB\BSON\MaxKey implements MongoDB\BSON\MaxKeyInterface , MongoDB\BSON\Type , Serializable , JsonSerializable {

/* 方法 */

final public __construct ( void )

final public mixed jsonSerialize ( void )

final public string serialize ( void )

final public void unserialize ( string $serialized )

}

更新日志

版本说明
1.3.0Implements MongoDB\BSON\MaxKeyInterface.
1.2.0Implements Serializable and JsonSerializable.

MongoDB\BSON\MaxKey::__construct

Construct a new MaxKey

说明

final public MongoDB\BSON\MaxKey::__construct ( void )

参数

此函数没有参数。

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\BSON\MaxKey::__construct example

<?php

var_dump(new MongoDB\BSON\MaxKey());

?>

以上例程会输出:

object(MongoDB\BSON\MaxKey)#1 (0) {
}

参见

MongoDB\BSON\MaxKey::jsonSerialize

Returns a representation that can be converted to JSON

说明

final public mixed MongoDB\BSON\MaxKey::jsonSerialize ( void )

参数

此函数没有参数。

返回值

Returns data which can be serialized by json_encode to produce an extended JSON representation of the MongoDB\BSON\MaxKey.

Note: The output is consistent with the MongoDB\BSON\toJSON function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by class="function">MongoDB\BSON\toRelaxedExtendedJSON and class="function">MongoDB\BSON\toCanonicalExtendedJSON, respectively.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • JsonSerializable::jsonSerialize
  • json_encode
  • MongoDB\BSON\toCanonicalExtendedJSON
  • MongoDB\BSON\toRelaxedExtendedJSON
  • » MongoDB Extended JSON

MongoDB\BSON\MaxKey::serialize

Serialize a MaxKey

说明

final public string MongoDB\BSON\MaxKey::serialize ( void )

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\BSON\MaxKey.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

MongoDB\BSON\MaxKey::unserialize

Unserialize a MaxKey

说明

final public void MongoDB\BSON\MaxKey::unserialize ( string $serialized )

参数

serialized
The serialized MongoDB\BSON\MaxKey.

返回值

Returns the unserialized MongoDB\BSON\MaxKey.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

简介

Special BSON type which compares lower than all other possible BSON element values.

Note: This is an internal MongoDB type used for indexing and sharding.

类摘要

MongoDB\BSON\MinKey

final class MongoDB\BSON\MinKey implements MongoDB\BSON\MinKeyInterface , MongoDB\BSON\Type , Serializable , JsonSerializable {

/* 方法 */

final public __construct ( void )

final public mixed jsonSerialize ( void )

final public string serialize ( void )

final public void unserialize ( string $serialized )

}

更新日志

版本说明
1.3.0Implements MongoDB\BSON\MinKeyInterface.
1.2.0Implements Serializable and JsonSerializable.

MongoDB\BSON\MinKey::__construct

Construct a new MinKey

说明

final public MongoDB\BSON\MinKey::__construct ( void )

参数

此函数没有参数。

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\BSON\MinKey::__construct example

<?php

var_dump(new MongoDB\BSON\MinKey());

?>

以上例程会输出:

object(MongoDB\BSON\MinKey)#1 (0) {
}

参见

MongoDB\BSON\MinKey::jsonSerialize

Returns a representation that can be converted to JSON

说明

final public mixed MongoDB\BSON\MinKey::jsonSerialize ( void )

参数

此函数没有参数。

返回值

Returns data which can be serialized by json_encode to produce an extended JSON representation of the MongoDB\BSON\MinKey.

Note: The output is consistent with the MongoDB\BSON\toJSON function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by class="function">MongoDB\BSON\toRelaxedExtendedJSON and class="function">MongoDB\BSON\toCanonicalExtendedJSON, respectively.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • JsonSerializable::jsonSerialize
  • json_encode
  • MongoDB\BSON\toCanonicalExtendedJSON
  • MongoDB\BSON\toRelaxedExtendedJSON
  • » MongoDB Extended JSON

MongoDB\BSON\MinKey::serialize

Serialize a MinKey

说明

final public string MongoDB\BSON\MinKey::serialize ( void )

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\BSON\MinKey.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

MongoDB\BSON\MinKey::unserialize

Unserialize a MinKey

说明

final public void MongoDB\BSON\MinKey::unserialize ( string $serialized )

参数

serialized
The serialized MongoDB\BSON\MinKey.

返回值

Returns the unserialized MongoDB\BSON\MinKey.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

简介

BSON type for an » ObjectId. The value consists of 12 bytes, where the first four bytes are a timestamp that reflect the ObjectId's creation. Specifically, the value consists of:

  • a 4-byte value representing the seconds since the Unix epoch,
  • a 5-byte random number unique to a machine and process, and
  • a 3-byte counter, starting with a random value.

In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the driver automatically generates an ObjectId for the _id field.

Using ObjectIds for the _id field provides the following additional benefits:

  • The creation time of the ObjectId may be accessed using the MongoDB\BSON\ObjectId::getTimestamp method.
  • Sorting on an _id field that stores ObjectId values is roughly equivalent to sorting by creation time.

类摘要

MongoDB\BSON\ObjectId

final class MongoDB\BSON\ObjectId implements MongoDB\BSON\ObjectIdInterface , MongoDB\BSON\Type , Serializable , JsonSerializable {

/* 方法 */

final public __construct ([ string $id ] )

final public int getTimestamp ( void )

final public mixed jsonSerialize ( void )

final public string serialize ( void )

final public string __toString ( void )

final public void unserialize ( string $serialized )

}

更新日志

版本 说明
1.3.0

Renamed from MongoDB\BSON\ObjectID to MongoDB\BSON\ObjectId.

Implements MongoDB\BSON\ObjectIdInterface.

1.2.0 Implements Serializable and JsonSerializable.

MongoDB\BSON\ObjectId::__construct

Construct a new ObjectId

说明

final public MongoDB\BSON\ObjectId::__construct ([ string $id ] )

参数

id (string)
A 24-character hexadecimal string. If not provided, the driver will generate an ObjectId.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if id is not a 24-character hexadecimal string.

范例

示例 #1 MongoDB\BSON\ObjectId::__construct example

<?php

var_dump(new MongoDB\BSON\ObjectId());

var_dump(new MongoDB\BSON\ObjectId('000000000000000000000001'));

?>

以上例程的输出类似于:

object(MongoDB\BSON\ObjectId)#1 (1) {
  ["oid"]=>
  string(24) "56732d3dda14d81214634921"
}
object(MongoDB\BSON\ObjectId)#1 (1) {
  ["oid"]=>
  string(24) "000000000000000000000001"
}

参见

MongoDB\BSON\ObjectId::getTimestamp

Returns the timestamp component of this ObjectId

说明

final public int MongoDB\BSON\ObjectId::getTimestamp ( void )

The timestamp component of an ObjectId is its most significant 32 bits, which denotes the number of seconds since the Unix epoch. This value is read as an unsigned 32-bit integer with big-endian byte order.

Note: Because PHP's integer type is signed, some values returned by this method may appear as negative integers on 32-bit platforms. The "%u" formatter of class="function">sprintf may be used to obtain a string representation of the unsigned decimal value.

参数

此函数没有参数。

返回值

Returns the timestamp component of this ObjectId.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\BSON\ObjectId::getTimestamp example

<?php

var_dump((new MongoDB\BSON\ObjectId())->getTimestamp());

var_dump((new MongoDB\BSON\ObjectId('0000002a0000000000000000'))->getTimestamp());

?>

以上例程的输出类似于:

integer(1484854719)
integer(42)

参见

MongoDB\BSON\ObjectId::jsonSerialize

Returns a representation that can be converted to JSON

说明

final public mixed MongoDB\BSON\ObjectId::jsonSerialize ( void )

参数

此函数没有参数。

返回值

Returns data which can be serialized by json_encode to produce an extended JSON representation of the MongoDB\BSON\ObjectId.

Note: The output is consistent with the MongoDB\BSON\toJSON function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by class="function">MongoDB\BSON\toRelaxedExtendedJSON and class="function">MongoDB\BSON\toCanonicalExtendedJSON, respectively.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • JsonSerializable::jsonSerialize
  • json_encode
  • MongoDB\BSON\toCanonicalExtendedJSON
  • MongoDB\BSON\toRelaxedExtendedJSON
  • » MongoDB Extended JSON

MongoDB\BSON\ObjectId::serialize

Serialize an ObjectId

说明

final public string MongoDB\BSON\ObjectId::serialize ( void )

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\BSON\ObjectId.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

MongoDB\BSON\ObjectId::__toString

Returns the hexidecimal representation of this ObjectId

说明

final public string MongoDB\BSON\ObjectId::__toString ( void )

参数

此函数没有参数。

返回值

Returns the hexidecimal representation of this ObjectId.

范例

示例 #1 MongoDB\BSON\ObjectId::__toString example

<?php

var_dump((string) new MongoDB\BSON\ObjectId());
var_dump((string) new MongoDB\BSON\ObjectId('000000000000000000000001'));

?>

以上例程的输出类似于:

string(24) "56731b49da14d8747d701211"
string(24) "000000000000000000000001"

参见

MongoDB\BSON\ObjectId::unserialize

Unserialize an ObjectId

说明

final public void MongoDB\BSON\ObjectId::unserialize ( string $serialized )

参数

serialized
The serialized MongoDB\BSON\ObjectId.

返回值

Returns the unserialized MongoDB\BSON\ObjectId.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

参见

简介

BSON type for a regular expression pattern and optional » flags.

Note: This BSON type is mainly used when querying the database. Alternatively, the » $regex query operator may be used.

类摘要

MongoDB\BSON\Regex

final class MongoDB\BSON\Regex implements MongoDB\BSON\RegexInterface , MongoDB\BSON\Type , Serializable , JsonSerializable {

/* 方法 */

final public __construct ( string $pattern [, string $flags = "" ] )

final public string getFlags ( void )

final public string getPattern ( void )

final public mixed jsonSerialize ( void )

final public string serialize ( void )

final public string __toString ( void )

final public void unserialize ( string $serialized )

}

更新日志

版本说明
1.3.0Implements MongoDB\BSON\RegexInterface.
1.2.0Implements Serializable and JsonSerializable.

MongoDB\BSON\Regex::__construct

Construct a new Regex

说明

final public MongoDB\BSON\Regex::__construct ( string $pattern [, string $flags = "" ] )

参数

pattern (string)
The regular expression pattern.

Note: The pattern should not be wrapped with delimiter characters.

flags (string)
The » regular expression flags. Characters in this argument will be sorted alphabetically.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if pattern or flags contain null bytes.

更新日志

版本 说明
1.2.0

The flags argument is optional and defaults to an empty string.

Characters in the flags argument will be sorted alphabetically when a Regex is constructed. Previously, the characters were stored in the order provided.

MongoDB\Driver\Exception\InvalidArgumentException is thrown if pattern or flags contain null bytes. Previously, values would be truncated at the first null byte.

范例

示例 #1 MongoDB\BSON\Regex::__construct example

<?php

$regex = new MongoDB\BSON\Regex('^foo', 'i');
var_dump($regex);

?>

以上例程会输出:

object(MongoDB\BSON\Regex)#1 (2) {
  ["pattern"]=>
  string(4) "^foo"
  ["flags"]=>
  string(1) "i"
}

参见

MongoDB\BSON\Regex::getFlags

Returns the Regex's flags

说明

final public string MongoDB\BSON\Regex::getFlags ( void )

参数

此函数没有参数。

返回值

Returns the Regex's flags.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\BSON\Regex::getFlags example

<?php

$regex = new MongoDB\BSON\Regex('regex', 'i');
var_dump($regex->getFlags());

?>

以上例程的输出类似于:

string(1) "i"

参见

MongoDB\BSON\Regex::getPattern

Returns the Regex's pattern

说明

final public string MongoDB\BSON\Regex::getPattern ( void )

参数

此函数没有参数。

返回值

Returns the Regex's pattern.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\BSON\Regex::getPattern example

<?php

$regex = new MongoDB\BSON\Regex('regex', 'i');
var_dump($regex->getPattern());

?>

以上例程的输出类似于:

string(5) "regex"

参见

MongoDB\BSON\Regex::jsonSerialize

Returns a representation that can be converted to JSON

说明

final public mixed MongoDB\BSON\Regex::jsonSerialize ( void )

参数

此函数没有参数。

返回值

Returns data which can be serialized by json_encode to produce an extended JSON representation of the MongoDB\BSON\Regex.

Note: The output is consistent with the MongoDB\BSON\toJSON function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by class="function">MongoDB\BSON\toRelaxedExtendedJSON and class="function">MongoDB\BSON\toCanonicalExtendedJSON, respectively.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • JsonSerializable::jsonSerialize
  • json_encode
  • MongoDB\BSON\toCanonicalExtendedJSON
  • MongoDB\BSON\toRelaxedExtendedJSON
  • » MongoDB Extended JSON

MongoDB\BSON\Regex::serialize

Serialize a Regex

说明

final public string MongoDB\BSON\Regex::serialize ( void )

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\BSON\Regex.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

MongoDB\BSON\Regex::__toString

Returns the string representation of this Regex

说明

final public string MongoDB\BSON\Regex::__toString ( void )

参数

此函数没有参数。

返回值

Returns the string representation of this Regex.

范例

示例 #1 MongoDB\BSON\Regex::__toString example

<?php

$regex = new MongoDB\BSON\Regex('regex', 'i');
var_dump((string) $regex);

?>

以上例程会输出:

string(8) "/regex/i"

参见

MongoDB\BSON\Regex::unserialize

Unserialize a Regex

说明

final public void MongoDB\BSON\Regex::unserialize ( string $serialized )

参数

serialized
The serialized MongoDB\BSON\Regex.

返回值

Returns the unserialized MongoDB\BSON\Regex.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

参见

简介

Represents a » BSON timestamp, The value consists of a 4-byte timestamp (i.e. seconds since the epoch) and a 4-byte increment.

Note: This is an internal MongoDB type used for replication and sharding. It is not intended for general date storage (MongoDB\BSON\UTCDateTime should be used instead).

类摘要

MongoDB\BSON\Timestamp

final class MongoDB\BSON\Timestamp implements MongoDB\BSON\TimestampInterface , MongoDB\BSON\Type , Serializable , JsonSerializable {

/* 方法 */

final public __construct ( int $increment , int $timestamp )

final public int getIncrement ( void )

final public int getTimestamp ( void )

final public mixed jsonSerialize ( void )

final public string serialize ( void )

final public string __toString ( void )

final public void unserialize ( string $serialized )

}

更新日志

版本说明
1.3.0Implements MongoDB\BSON\TimestampInterface.
1.2.0Implements Serializable and JsonSerializable.

MongoDB\BSON\Timestamp::__construct

Construct a new Timestamp

说明

final public MongoDB\BSON\Timestamp::__construct ( int $increment , int $timestamp )

参数

increment (integer)
32-bit integer denoting the incrementing ordinal for operations within a given second.

timestamp (integer)
32-bit integer denoting seconds since the Unix epoch.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\BSON\Timestamp::__construct example

<?php

$timestamp = new MongoDB\BSON\Timestamp(1234, 5678);

?>

以上例程会输出:

object(MongoDB\BSON\Timestamp)#1 (2) {
  ["increment"]=>
  int(1234)
  ["timestamp"]=>
  int(5678)
}

参见

MongoDB\BSON\Timestamp::getIncrement

Returns the increment component of this Timestamp

说明

final public int MongoDB\BSON\Timestamp::getIncrement ( void )

The increment component of a Timestamp is its least significant 32 bits, whichs denotes the incrementing ordinal for operations within a given second. This value is read as an unsigned 32-bit integer with big-endian byte order.

Note: Because PHP's integer type is signed, some values returned by this method may appear as negative integers on 32-bit platforms. The "%u" formatter of class="function">sprintf may be used to obtain a string representation of the unsigned decimal value.

参数

此函数没有参数。

返回值

Returns the increment component of this Timestamp.

Warning

On 32-bit systems this method may return a negative number. Although the increment and timestamp parts of the BSON timestamp type consists of two unsigned 32-bit values, PHP can not represent these on 32-bit platforms.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

MongoDB\BSON\Timestamp::getTimestamp

Returns the timestamp component of this Timestamp

说明

final public int MongoDB\BSON\Timestamp::getTimestamp ( void )

The timestamp component of a Timestamp is its most significant 32 bits, which denotes the number of seconds since the Unix epoch. This value is read as an unsigned 32-bit integer with big-endian byte order.

Note: Because PHP's integer type is signed, some values returned by this method may appear as negative integers on 32-bit platforms. The "%u" formatter of class="function">sprintf may be used to obtain a string representation of the unsigned decimal value.

参数

此函数没有参数。

返回值

Returns the timestamp component of this Timestamp.

Warning

On 32-bit systems this method may return a negative number. Although the increment and timestamp parts of the BSON timestamp type consists of two unsigned 32-bit values, PHP can not represent these on 32-bit platforms.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

MongoDB\BSON\Timestamp::jsonSerialize

Returns a representation that can be converted to JSON

说明

final public mixed MongoDB\BSON\Timestamp::jsonSerialize ( void )

参数

此函数没有参数。

返回值

Returns data which can be serialized by json_encode to produce an extended JSON representation of the MongoDB\BSON\Timestamp.

Note: The output is consistent with the MongoDB\BSON\toJSON function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by class="function">MongoDB\BSON\toRelaxedExtendedJSON and class="function">MongoDB\BSON\toCanonicalExtendedJSON, respectively.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • JsonSerializable::jsonSerialize
  • json_encode
  • MongoDB\BSON\toCanonicalExtendedJSON
  • MongoDB\BSON\toRelaxedExtendedJSON
  • » MongoDB Extended JSON

MongoDB\BSON\Timestamp::serialize

Serialize a Timestamp

说明

final public string MongoDB\BSON\Timestamp::serialize ( void )

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\BSON\Timestamp.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

MongoDB\BSON\Timestamp::__toString

Returns the string representation of this Timestamp

说明

final public string MongoDB\BSON\Timestamp::__toString ( void )

参数

此函数没有参数。

返回值

Returns the string representation of this Timestamp.

范例

示例 #1 MongoDB\BSON\Timestamp::__toString example

<?php

$timestamp = new MongoDB\BSON\Timestamp(1234, 5678);
var_dump((string) $timestamp);

?>

以上例程的输出类似于:

string(11) "[1234:5678]"

参见

MongoDB\BSON\Timestamp::unserialize

Unserialize a Timestamp

说明

final public void MongoDB\BSON\Timestamp::unserialize ( string $serialized )

参数

serialized
The serialized MongoDB\BSON\Timestamp.

返回值

Returns the unserialized MongoDB\BSON\Timestamp.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

参见

简介

Represents a » BSON date. The value is a 64-bit integer that represents the number of milliseconds since the Unix epoch (Jan 1, 1970). Negative values represent dates before 1970.

类摘要

MongoDB\BSON\UTCDateTime

final class MongoDB\BSON\UTCDateTime implements MongoDB\BSON\UTCDateTimeInterface , MongoDB\BSON\Type , Serializable , JsonSerializable {

/* 方法 */

final public __construct ([ integer|float|string|DateTimeInterface $milliseconds = NULL ] )

final public mixed jsonSerialize ( void )

final public string serialize ( void )

final public DateTime toDateTime ( void )

final public string __toString ( void )

final public void unserialize ( string $serialized )

}

更新日志

版本说明
1.3.0Implements MongoDB\BSON\UTCDateTimeInterface.
1.2.0Implements Serializable and JsonSerializable.

MongoDB\BSON\UTCDateTime::__construct

Construct a new UTCDateTime

说明

final public MongoDB\BSON\UTCDateTime::__construct ([ integer|float|string|DateTimeInterface $milliseconds = NULL ] )

参数

milliseconds (integer|float|string|DateTimeInterface)
Number of milliseconds since the Unix epoch (Jan 1, 1970). Negative values represent dates before 1970. This value may be provided as a 64-bit integer. For compatibility on 32-bit systems, this parameter may also be provided as a float or string.

If the argument is a DateTimeInterface, the number of milliseconds since the Unix epoch will be derived from that value. Note that in versions of PHP versions before 7.1.0, DateTime and DateTimeImmutable objects constructed from the current time did not incorporate sub-second precision.

If this argument is NULL, the current time will be used by default.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

更新日志

版本说明
1.2.0The milliseconds argument is optional and defaults to NULL (i.e. current time). The argument also accepts a DateTimeInterface, which may be used to derive the number of milliseconds since the Unix epoch. Previously, only integer, float, and string types were accepted.

范例

示例 #1 MongoDB\BSON\UTCDateTime::__construct example

<?php

var_dump(new MongoDB\BSON\UTCDateTime);

var_dump(new MongoDB\BSON\UTCDateTime(new DateTime));

var_dump(new MongoDB\BSON\UTCDateTime(1416445411987));

?>

以上例程的输出类似于:

object(MongoDB\BSON\UTCDateTime)#1 (1) {
  ["milliseconds"]=>
  string(13) "1484852905560"
}
object(MongoDB\BSON\UTCDateTime)#1 (1) {
  ["milliseconds"]=>
  string(13) "1484852905560"
}
object(MongoDB\BSON\UTCDateTime)#1 (1) {
  ["milliseconds"]=>
  string(13) "1416445411987"
}

参见

MongoDB\BSON\UTCDateTime::jsonSerialize

Returns a representation that can be converted to JSON

说明

final public mixed MongoDB\BSON\UTCDateTime::jsonSerialize ( void )

参数

此函数没有参数。

返回值

Returns data which can be serialized by json_encode to produce an extended JSON representation of the MongoDB\BSON\UTCDateTime.

Note: The output is consistent with the MongoDB\BSON\toJSON function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by class="function">MongoDB\BSON\toRelaxedExtendedJSON and class="function">MongoDB\BSON\toCanonicalExtendedJSON, respectively.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • JsonSerializable::jsonSerialize
  • json_encode
  • MongoDB\BSON\toCanonicalExtendedJSON
  • MongoDB\BSON\toRelaxedExtendedJSON
  • » MongoDB Extended JSON

MongoDB\BSON\UTCDateTime::serialize

Serialize a UTCDateTime

说明

final public string MongoDB\BSON\UTCDateTime::serialize ( void )

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\BSON\UTCDateTime.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

MongoDB\BSON\UTCDateTime::toDateTime

Returns the DateTime representation of this UTCDateTime

说明

final public DateTime MongoDB\BSON\UTCDateTime::toDateTime ( void )

参数

此函数没有参数。

返回值

Returns the DateTime representation of this UTCDateTime. The returned DateTime will use the UTC time zone.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

范例

示例 #1 MongoDB\BSON\UTCDatetime::toDateTime example

<?php

$utcdatetime = new MongoDB\BSON\UTCDateTime(1416445411987);
$datetime = $utcdatetime->toDateTime();
var_dump($datetime->format('r'));
var_dump($datetime->format('U.u'));
var_dump($datetime->getTimezone());

?>

以上例程的输出类似于:

string(31) "Thu, 20 Nov 2014 01:03:31 +0000"
string(17) "1416445411.987000"
object(DateTimeZone)#3 (2) {
  ["timezone_type"]=>
  int(1)
  ["timezone"]=>
  string(6) "+00:00"
}

参见

MongoDB\BSON\UTCDateTime::__toString

Returns the string representation of this UTCDateTime

说明

final public string MongoDB\BSON\UTCDateTime::__toString ( void )

参数

此函数没有参数。

返回值

Returns the string representation of this UTCDateTime.

范例

示例 #1 MongoDB\BSON\UTCDateTime::__toString example

<?php

$utcdatetime = new MongoDB\BSON\UTCDateTime(1416445411987);
var_dump((string) $utcdatetime);

?>

以上例程会输出:

string(13) "1416445411987"

参见

MongoDB\BSON\UTCDateTime::unserialize

Unserialize a UTCDateTime

说明

final public void MongoDB\BSON\UTCDateTime::unserialize ( string $serialized )

参数

serialized
The serialized MongoDB\BSON\UTCDateTime.

返回值

Returns the unserialized MongoDB\BSON\UTCDateTime.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

参见

简介

Abstract base interface that should not be implemented directly.

接口摘要

MongoDB\BSON\Type

class MongoDB\BSON\Type {

}

This interface has no methods. Its only purpose is to be the base interface for all BSON type classes.

简介

Classes may implement this interface to take advantage of automatic ODM (object document mapping) behavior in the driver. During serialization, the driver will inject a __pclass property containing the PHP class name into the data returned by MongoDB\BSON\Serializable::bsonSerialize. During unserialization, the same __pclass property will then be used to infer the PHP class (independent of any type map configuration) to be constructed before MongoDB\BSON\Unserializable::bsonUnserialize is invoked. See for additional information.

Note: Even if class="function">MongoDB\BSON\Serializable::bsonSerialize would return a sequential array, injection of the class="property">__pclass property will cause the object to be serialized as a BSON document.

接口摘要

MongoDB\BSON\Persistable

class MongoDB\BSON\Persistable implements MongoDB\BSON\Unserializable , MongoDB\BSON\Serializable {

/* 继承的方法 */

abstract public array|object MongoDB\BSON\Serializable::bsonSerialize ( void )

abstract public void MongoDB\BSON\Unserializable::bsonUnserialize ( array $data )

}

简介

Classes that implement this interface may return data to be serialized as a BSON array or document in lieu of the object's public properties.

接口摘要

MongoDB\BSON\Serializable

class MongoDB\BSON\Serializable implements MongoDB\BSON\Type {

/* 方法 */

abstract public array|object bsonSerialize ( void )

}

MongoDB\BSON\Serializable::bsonSerialize

Provides an array or document to serialize as BSON

说明

abstract public array|object MongoDB\BSON\Serializable::bsonSerialize ( void )

Called during serialization of the object to BSON. The method must return an array or stdClass.

Root documents (e.g. a MongoDB\BSON\Serializable passed to MongoDB\BSON\fromPHP) will always be serialized as a BSON document. For field values, associative arrays and stdClass instances will be serialized as a BSON document and sequential arrays (i.e. sequential, numeric indexes starting at 0) will be serialized as a BSON array.

Users are encouraged to include an _id property (e.g. a MongoDB\BSON\ObjectId initialized in your constructor) when returning data for a BSON root document; otherwise, the driver or database will need to generate a MongoDB\BSON\ObjectId when inserting or upserting the document, respectively.

参数

此函数没有参数。

返回值

An array or stdClass to be serialized as a BSON array or document.

范例

示例 #1 MongoDB\BSON\Serializable::bsonSerialize returning an associative array for root document

<?php

class MyDocument implements MongoDB\BSON\Serializable
{
    private $id;

    function __construct()
    {
        $this->id = new MongoDB\BSON\ObjectId;
    }

    function bsonSerialize()
    {
        return ['_id' => $this->id, 'foo' => 'bar'];
    }
}

$bson = MongoDB\BSON\fromPHP(new MyDocument);
echo MongoDB\BSON\toJSON($bson), "\n";

?>

以上例程的输出类似于:

{ "_id" : { "$oid" : "56cccdcada14d8755a58c591" }, "foo" : "bar" }

示例 #2 MongoDB\BSON\Serializable::bsonSerialize returning a sequential array for root document

<?php

class MyArray implements MongoDB\BSON\Serializable
{
    function bsonSerialize()
    {
        return [1, 2, 3];
    }
}

$bson = MongoDB\BSON\fromPHP(new MyArray);
echo MongoDB\BSON\toJSON($bson), "\n";

?>

以上例程会输出:

{ "0" : 1, "1" : 2, "2" : 3 }

示例 #3 MongoDB\BSON\Serializable::bsonSerialize returning an associative array for document field

<?php

class MyDocument implements MongoDB\BSON\Serializable
{
    function bsonSerialize()
    {
        return ['foo' => 'bar'];
    }
}

$value = ['document' => new MyDocument];
$bson = MongoDB\BSON\fromPHP($value);
echo MongoDB\BSON\toJSON($bson), "\n";

?>

以上例程会输出:

{ "document" : { "foo" : "bar" } }

示例 #4 MongoDB\BSON\Serializable::bsonSerialize returning a sequential array for document field

<?php

class MyArray implements MongoDB\BSON\Serializable
{
    function bsonSerialize()
    {
        return [1, 2, 3];
    }
}

$value = ['array' => new MyArray];
$bson = MongoDB\BSON\fromPHP($value);
echo MongoDB\BSON\toJSON($bson), "\n";

?>

以上例程会输出:

{ "array" : [ 1, 2, 3 ] }

参见

  • MongoDB\BSON\Unserializable::bsonUnserialize
  • MongoDB\BSON\Persistable

简介

Classes that implement this interface may be specified in a type map for unserializing BSON arrays and documents (both root and embedded).

接口摘要

MongoDB\BSON\Unserializable

class MongoDB\BSON\Unserializable {

/* 方法 */

abstract public void bsonUnserialize ( array $data )

}

MongoDB\BSON\Unserializable::bsonUnserialize

Constructs the object from a BSON array or document

说明

abstract public void MongoDB\BSON\Unserializable::bsonUnserialize ( array $data )

Called during unserialization of the object from BSON. The properties of the BSON array or document will be passed to the method as an array.

Remember to check for an _id property when handling data from a BSON document.

Note: This method acts as the constructor of the object. The __construct() method will not be called after this method.

参数

data (array)
Properties within the BSON array or document.

返回值

The return value from this method is ignored.

范例

示例 #1 MongoDB\BSON\Unserializable::bsonUnserialize example

<?php

class MyDocument implements MongoDB\BSON\Unserializable
{
    private $data = [];

    function bsonUnserialize(array $data)
    {
        $this->data = $data;
    }
}

$bson = MongoDB\BSON\fromJSON('{ "foo": "bar" }');
$value = MongoDB\BSON\toPHP($bson, ['root' => 'MyDocument']);
var_dump($value);

?>

以上例程会输出:

object(MyDocument)#1 (1) {
  ["data":"MyDocument":private]=>
  array(1) {
    ["foo"]=>
    string(3) "bar"
  }
}

参见

  • MongoDB\BSON\Serializable::bsonSerialize
  • MongoDB\BSON\Persistable

简介

This interface is implemented by MongoDB\BSON\Binary but may also be used for type-hinting and userland classes.

类摘要

MongoDB\BSON\BinaryInterface

class MongoDB\BSON\BinaryInterface {

/* 方法 */

abstract public string getData ( void )

abstract public int getType ( void )

abstract public string __toString ( void )

}

MongoDB\BSON\BinaryInterface::getData

Returns the BinaryInterface's data

说明

abstract public string MongoDB\BSON\BinaryInterface::getData ( void )

参数

此函数没有参数。

返回值

Returns the BinaryInterface's data.

参见

  • MongoDB\BSON\Binary::getData

MongoDB\BSON\BinaryInterface::getType

Returns the BinaryInterface's type

说明

abstract public int MongoDB\BSON\BinaryInterface::getType ( void )

参数

此函数没有参数。

返回值

Returns the BinaryInterface's type.

参见

  • MongoDB\BSON\Binary::getType

MongoDB\BSON\BinaryInterface::__toString

Returns the BinaryInterface's data

说明

abstract public string MongoDB\BSON\BinaryInterface::__toString ( void )

此方法是该方法的别名: MongoDB\BSON\BinaryInterface::getData.

参数

此函数没有参数。

返回值

Returns the BinaryInterface's data.

参见

  • MongoDB\BSON\BinaryInterface::getData
  • MongoDB\BSON\Binary::__toString

简介

This interface is implemented by MongoDB\BSON\Decimal128 but may also be used for type-hinting and userland classes.

类摘要

MongoDB\BSON\Decimal128Interface

class MongoDB\BSON\Decimal128Interface {

/* 方法 */

abstract public string __toString ( void )

}

MongoDB\BSON\Decimal128Interface::__toString

Returns the string representation of this Decimal128Interface

说明

abstract public string MongoDB\BSON\Decimal128Interface::__toString ( void )

参数

此函数没有参数。

返回值

Returns the string representation of this Decimal128Interface.

参见

  • MongoDB\BSON\Decimal128::__toString

简介

This interface is implemented by MongoDB\BSON\Javascript but may also be used for type-hinting and userland classes.

类摘要

MongoDB\BSON\JavascriptInterface

class MongoDB\BSON\JavascriptInterface {

/* 方法 */

abstract public string getCode ( void )

abstract public object|null getScope ( void )

abstract public string __toString ( void )

}

MongoDB\BSON\JavascriptInterface::getCode

Returns the JavascriptInterface's code

说明

abstract public string MongoDB\BSON\JavascriptInterface::getCode ( void )

参数

此函数没有参数。

返回值

Returns the JavascriptInterface's code.

参见

  • MongoDB\BSON\Javascript::getCode

MongoDB\BSON\JavascriptInterface::getScope

Returns the JavascriptInterface's scope document

说明

abstract public object|null MongoDB\BSON\JavascriptInterface::getScope ( void )

参数

此函数没有参数。

返回值

Returns the JavascriptInterface's scope document.

参见

  • MongoDB\BSON\Javascript::getScope

MongoDB\BSON\JavascriptInterface::__toString

Returns the JavascriptInterface's code

说明

abstract public string MongoDB\BSON\JavascriptInterface::__toString ( void )

此方法是该方法的别名: MongoDB\BSON\JavascriptInterface::getCode.

参数

此函数没有参数。

返回值

Returns the JavascriptInterface's code.

参见

  • MongoDB\BSON\JavascriptInterface::getCode
  • MongoDB\BSON\Javascript::__toString

简介

This interface is implemented by MongoDB\BSON\MaxKey but may also be used for type-hinting and userland classes.

类摘要

MongoDB\BSON\MaxKeyInterface

class MongoDB\BSON\MaxKeyInterface {

}

This interface has no methods.

简介

This interface is implemented by MongoDB\BSON\MinKey but may also be used for type-hinting and userland classes.

类摘要

MongoDB\BSON\MinKeyInterface

class MongoDB\BSON\MinKeyInterface {

}

This interface has no methods.

简介

This interface is implemented by MongoDB\BSON\ObjectId but may also be used for type-hinting and userland classes.

类摘要

MongoDB\BSON\ObjectIdInterface

class MongoDB\BSON\ObjectIdInterface {

/* 方法 */

abstract public int getTimestamp ( void )

abstract public string __toString ( void )

}

MongoDB\BSON\ObjectIdInterface::getTimestamp

Returns the timestamp component of this ObjectIdInterface

说明

abstract public int MongoDB\BSON\ObjectIdInterface::getTimestamp ( void )

参数

此函数没有参数。

返回值

Returns the timestamp component of this ObjectIdInterface.

参见

  • MongoDB\BSON\ObjectId::getTimestamp

MongoDB\BSON\ObjectIdInterface::__toString

Returns the hexidecimal representation of this ObjectIdInterface

说明

abstract public string MongoDB\BSON\ObjectIdInterface::__toString ( void )

参数

此函数没有参数。

返回值

Returns the hexidecimal representation of this ObjectIdInterface.

参见

  • MongoDB\BSON\ObjectId::__toString

简介

This interface is implemented by MongoDB\BSON\Regex but may also be used for type-hinting and userland classes.

类摘要

MongoDB\BSON\RegexInterface

class MongoDB\BSON\RegexInterface {

/* 方法 */

abstract public string getFlags ( void )

abstract public string getPattern ( void )

abstract public string __toString ( void )

}

MongoDB\BSON\RegexInterface::getFlags

Returns the RegexInterface's flags

说明

abstract public string MongoDB\BSON\RegexInterface::getFlags ( void )

参数

此函数没有参数。

返回值

Returns the RegexInterface's flags.

参见

  • MongoDB\BSON\Regex::getFlags

MongoDB\BSON\RegexInterface::getPattern

Returns the RegexInterface's pattern

说明

abstract public string MongoDB\BSON\RegexInterface::getPattern ( void )

参数

此函数没有参数。

返回值

Returns the RegexInterface's pattern.

参见

  • MongoDB\BSON\Regex::getPattern

MongoDB\BSON\RegexInterface::__toString

Returns the string representation of this RegexInterface

说明

abstract public string MongoDB\BSON\RegexInterface::__toString ( void )

参数

此函数没有参数。

返回值

Returns the string representation of this RegexInterface.

参见

  • MongoDB\BSON\Regex::__toString

简介

This interface is implemented by MongoDB\BSON\Timestamp but may also be used for type-hinting and userland classes.

类摘要

MongoDB\BSON\TimestampInterface

class MongoDB\BSON\TimestampInterface {

/* 方法 */

abstract public int getIncrement ( void )

abstract public int getTimestamp ( void )

abstract public string __toString ( void )

}

MongoDB\BSON\TimestampInterface::getIncrement

Returns the increment component of this TimestampInterface

说明

abstract public int MongoDB\BSON\TimestampInterface::getIncrement ( void )

参数

此函数没有参数。

返回值

Returns the increment component of this TimestampInterface.

Warning

On 32-bit systems this method may return a negative number. Although the increment and timestamp parts of the BSON timestamp type consists of two unsigned 32-bit values, PHP can not represent these on 32-bit platforms.

参见

  • MongoDB\BSON\Timestamp::getIncrement

MongoDB\BSON\TimestampInterface::getTimestamp

Returns the timestamp component of this TimestampInterface

说明

abstract public int MongoDB\BSON\TimestampInterface::getTimestamp ( void )

参数

此函数没有参数。

返回值

Returns the timestamp component of this TimestampInterface.

Warning

On 32-bit systems this method may return a negative number. Although the increment and timestamp parts of the BSON timestamp type consists of two unsigned 32-bit values, PHP can not represent these on 32-bit platforms.

参见

  • MongoDB\BSON\Timestamp::getTimestamp

MongoDB\BSON\TimestampInterface::__toString

Returns the string representation of this TimestampInterface

说明

abstract public string MongoDB\BSON\TimestampInterface::__toString ( void )

参数

此函数没有参数。

返回值

Returns the string representation of this TimestampInterface.

参见

  • MongoDB\BSON\Timestamp::__toString

简介

This interface is implemented by MongoDB\BSON\UTCDateTime but may also be used for type-hinting and userland classes.

类摘要

MongoDB\BSON\UTCDateTimeInterface

class MongoDB\BSON\UTCDateTimeInterface {

/* 方法 */

abstract public DateTime toDateTime ( void )

abstract public string __toString ( void )

}

MongoDB\BSON\UTCDateTimeInterface::toDateTime

Returns the DateTime representation of this UTCDateTimeInterface

说明

abstract public DateTime MongoDB\BSON\UTCDateTimeInterface::toDateTime ( void )

参数

此函数没有参数。

返回值

Returns the DateTime representation of this UTCDateTimeInterface. The returned DateTime should use the UTC time zone.

参见

  • MongoDB\BSON\UTCDateTime::toDateTime

MongoDB\BSON\UTCDateTimeInterface::__toString

Returns the string representation of this UTCDateTimeInterface

说明

abstract public string MongoDB\BSON\UTCDateTimeInterface::__toString ( void )

参数

此函数没有参数。

返回值

Returns the string representation of this UTCDateTimeInterface.

参见

  • MongoDB\BSON\UTCDateTime::__toString

简介

BSON type for the "DBPointer" type. This BSON type is deprecated, and this class can not be instantiated. It will be created from a BSON DBPointer type while converting BSON to PHP, and can also be converted back into BSON while storing documents in the database.

类摘要

MongoDB\BSON\DBPointer

final class MongoDB\BSON\DBPointer implements MongoDB\BSON\Type , Serializable , JsonSerializable {

/* 方法 */

final private __construct ( void )

final public mixed jsonSerialize ( void )

final public string serialize ( void )

final public string __toString ( void )

final public void unserialize ( string $serialized )

}

MongoDB\BSON\DBPointer::__construct

Construct a new DBPointer (unused)

说明

final private MongoDB\BSON\DBPointer::__construct ( void )

MongoDB\BSON\DBPointer objects are created through conversion from a deprecated BSON type and cannot be constructed directly.

参数

此函数没有参数。

参见

MongoDB\BSON\DBPointer::jsonSerialize

Returns a representation that can be converted to JSON

说明

final public mixed MongoDB\BSON\DBPointer::jsonSerialize ( void )

参数

此函数没有参数。

返回值

Returns data which can be serialized by json_encode to produce an extended JSON representation of the MongoDB\BSON\DBPointer.

Note: The output is consistent with the MongoDB\BSON\toJSON function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by class="function">MongoDB\BSON\toRelaxedExtendedJSON and class="function">MongoDB\BSON\toCanonicalExtendedJSON, respectively.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • JsonSerializable::jsonSerialize
  • json_encode
  • MongoDB\BSON\toCanonicalExtendedJSON
  • MongoDB\BSON\toRelaxedExtendedJSON
  • » MongoDB Extended JSON

MongoDB\BSON\DBPointer::serialize

Serialize a DBPointer

说明

final public string MongoDB\BSON\DBPointer::serialize ( void )

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\BSON\DBPointer.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

MongoDB\BSON\DBPointer::__toString

Returns an empty string

说明

final public string MongoDB\BSON\DBPointer::__toString ( void )

参数

此函数没有参数。

返回值

Returns an empty string.

参见

MongoDB\BSON\DBPointer::unserialize

Unserialize a DBPointer

说明

final public void MongoDB\BSON\DBPointer::unserialize ( string $serialized )

参数

serialized
The serialized MongoDB\BSON\DBPointer.

返回值

Returns the unserialized MongoDB\BSON\DBPointer.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

简介

BSON type for a 64-bit integer. This class cannot be instantiated and is only created during BSON decoding when a 64-bit integer cannot be represented as a PHP integer on a 32-bit platform. Versions of the driver before 1.5.0 would throw an exception when attempting to decode a 64-bit integer on a 32-bit platform.

During BSON encoding, objects of this class will convert back to a 64-bit integer type. This allows 64-bit integers to be roundtripped through a 32-bit PHP environment without any loss of precision. The __toString() method allows the 64-bit integer value to be accessed as a string.

Note: This class exists purely for 32-bit platforms. Applications on 64-bit platforms (i.e. PHP_INT_SIZE is 8) should never encounter this class during normal operation.

类摘要

MongoDB\BSON\Int64

final class MongoDB\BSON\Int64 implements MongoDB\BSON\Type , Serializable , JsonSerializable {

/* 方法 */

final private __construct ( void )

final public mixed jsonSerialize ( void )

final public string serialize ( void )

final public string __toString ( void )

final public void unserialize ( string $serialized )

}

MongoDB\BSON\Int64::__construct

Construct a new Int64 (unused)

说明

final private MongoDB\BSON\Int64::__construct ( void )

MongoDB\BSON\Int64 objects are created through conversion from a 64-bit integer BSON type on a 32-bit platform and cannot be constructed directly.

参数

此函数没有参数。

参见

MongoDB\BSON\Int64::jsonSerialize

Returns a representation that can be converted to JSON

说明

final public mixed MongoDB\BSON\Int64::jsonSerialize ( void )

参数

此函数没有参数。

返回值

Returns data which can be serialized by json_encode to produce an extended JSON representation of the MongoDB\BSON\Int64.

Note: The output is consistent with the MongoDB\BSON\toCanonicalExtendedJSON function, which uses the » canonical extended JSON format. This differs from other BSON classes, which use the driver-specific legacy extended JSON format (class="function">MongoDB\BSON\toJSON), in order to ensure that the 64-bit integer value is correctly represented on 32-bit platforms.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • JsonSerializable::jsonSerialize
  • json_encode
  • MongoDB\BSON\toCanonicalExtendedJSON
  • MongoDB\BSON\toRelaxedExtendedJSON
  • » MongoDB Extended JSON

MongoDB\BSON\Int64::serialize

Serialize an Int64

说明

final public string MongoDB\BSON\Int64::serialize ( void )

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\BSON\Int64.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

MongoDB\BSON\Int64::__toString

Returns the string representation of this Int64

说明

final public string MongoDB\BSON\Int64::__toString ( void )

参数

此函数没有参数。

返回值

Returns the string representation of this Int64.

范例

示例 #1 MongoDB\BSON\Int64::__toString example

<?php

$int64 = unserialize('C:18:"MongoDB\BSON\Int64":47:{a:1:{s:7:"integer";s:19:"9223372036854775807";}}');

var_dump((string) $int64);

?>

以上例程的输出类似于:

string(19) "9223372036854775807"

参见

MongoDB\BSON\Int64::unserialize

Unserialize an Int64

说明

final public void MongoDB\BSON\Int64::unserialize ( string $serialized )

参数

serialized
The serialized MongoDB\BSON\Int64.

返回值

Returns the unserialized MongoDB\BSON\Int64.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

参见

简介

BSON type for the "Symbol" type. This BSON type is deprecated, and this class can not be instantiated. It will be created from a BSON symbol type while converting BSON to PHP, and can also be converted back into BSON while storing documents in the database.

类摘要

MongoDB\BSON\Symbol

final class MongoDB\BSON\Symbol implements MongoDB\BSON\Type , Serializable , JsonSerializable {

/* 方法 */

final private __construct ( void )

final public mixed jsonSerialize ( void )

final public string serialize ( void )

final public string __toString ( void )

final public void unserialize ( string $serialized )

}

MongoDB\BSON\Symbol::__construct

Construct a new Symbol (unused)

说明

final private MongoDB\BSON\Symbol::__construct ( void )

MongoDB\BSON\Symbol objects are created through conversion from a deprecated BSON type and cannot be constructed directly.

参数

此函数没有参数。

参见

MongoDB\BSON\Symbol::jsonSerialize

Returns a representation that can be converted to JSON

说明

final public mixed MongoDB\BSON\Symbol::jsonSerialize ( void )

参数

此函数没有参数。

返回值

Returns data which can be serialized by json_encode to produce an extended JSON representation of the MongoDB\BSON\Symbol.

Note: The output is consistent with the MongoDB\BSON\toJSON function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by class="function">MongoDB\BSON\toRelaxedExtendedJSON and class="function">MongoDB\BSON\toCanonicalExtendedJSON, respectively.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • JsonSerializable::jsonSerialize
  • json_encode
  • MongoDB\BSON\toCanonicalExtendedJSON
  • MongoDB\BSON\toRelaxedExtendedJSON
  • » MongoDB Extended JSON

MongoDB\BSON\Symbol::serialize

Serialize a Symbol

说明

final public string MongoDB\BSON\Symbol::serialize ( void )

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\BSON\Symbol.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

MongoDB\BSON\Symbol::__toString

Returns the Symbol as a string

说明

final public string MongoDB\BSON\Symbol::__toString ( void )

参数

此函数没有参数。

返回值

Returns the string representation of this Symbol.

参见

MongoDB\BSON\Symbol::unserialize

Unserialize a Symbol

说明

final public void MongoDB\BSON\Symbol::unserialize ( string $serialized )

参数

serialized
The serialized MongoDB\BSON\Symbol.

返回值

Returns the unserialized MongoDB\BSON\Symbol.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

简介

BSON type for the "Undefined" type. This BSON type is deprecated, and this class can not be instantiated. It will be created from a BSON undefined type while converting BSON to PHP, and can also be converted back into BSON while storing documents in the database.

类摘要

MongoDB\BSON\Undefined

final class MongoDB\BSON\Undefined implements MongoDB\BSON\Type , Serializable , JsonSerializable {

/* 方法 */

final private __construct ( void )

final public mixed jsonSerialize ( void )

final public string serialize ( void )

final public string __toString ( void )

final public void unserialize ( string $serialized )

}

MongoDB\BSON\Undefined::__construct

Construct a new Undefined (unused)

说明

final private MongoDB\BSON\Undefined::__construct ( void )

MongoDB\BSON\Undefined objects are created through conversion from a deprecated BSON type and cannot be constructed directly.

参数

此函数没有参数。

参见

MongoDB\BSON\Undefined::jsonSerialize

Returns a representation that can be converted to JSON

说明

final public mixed MongoDB\BSON\Undefined::jsonSerialize ( void )

参数

此函数没有参数。

返回值

Returns data which can be serialized by json_encode to produce an extended JSON representation of the MongoDB\BSON\Undefined.

Note: The output is consistent with the MongoDB\BSON\toJSON function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by class="function">MongoDB\BSON\toRelaxedExtendedJSON and class="function">MongoDB\BSON\toCanonicalExtendedJSON, respectively.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • JsonSerializable::jsonSerialize
  • json_encode
  • MongoDB\BSON\toCanonicalExtendedJSON
  • MongoDB\BSON\toRelaxedExtendedJSON
  • » MongoDB Extended JSON

MongoDB\BSON\Undefined::serialize

Serialize a Undefined

说明

final public string MongoDB\BSON\Undefined::serialize ( void )

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\BSON\Undefined.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

MongoDB\BSON\Undefined::__toString

Returns an empty string

说明

final public string MongoDB\BSON\Undefined::__toString ( void )

参数

此函数没有参数。

返回值

Returns an empty string.

参见

MongoDB\BSON\Undefined::unserialize

Unserialize a Undefined

说明

final public void MongoDB\BSON\Undefined::unserialize ( string $serialized )

参数

serialized
The serialized MongoDB\BSON\Undefined.

返回值

Returns the unserialized MongoDB\BSON\Undefined.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

Monitoring classes and subscriber functions

目录

MongoDB\Driver\Monitoring\addSubscriber

Registers a new monitoring event subscriber

说明

void MongoDB\Driver\Monitoring\addSubscriber ( MongoDB\Driver\Monitoring\Subscriber $subscriber )

Registers a new monitoring event subscriber with the driver. Registered subscribers will be notified of monitoring events through specific methods.

Note: If the object is already registered, this function is a no-op.

参数

subscriber (MongoDB\Driver\Monitoring\Subscriber)
A monitoring event subscriber object to register.

返回值

没有返回值。

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\Subscriber
  • MongoDB\Driver\Monitoring\CommandSubscriber
  • MongoDB\Driver\Monitoring\removeSubscriber

MongoDB\Driver\Monitoring\removeSubscriber

Unregisters an existing monitoring event subscriber

说明

void MongoDB\Driver\Monitoring\removeSubscriber ( MongoDB\Driver\Monitoring\Subscriber $subscriber )

Unregisters an existing monitoring event subscriber from the driver. Unregistered subscribers will no longer be notified of monitoring events.

Note: If the object is not registered, this function is a no-op.

参数

subscriber (MongoDB\Driver\Monitoring\Subscriber)
A monitoring event subscriber object to unregister.

返回值

没有返回值。

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\Subscriber
  • MongoDB\Driver\Monitoring\CommandSubscriber
  • MongoDB\Driver\Monitoring\addSubscriber

目录

简介

The MongoDB\Driver\Monitoring\CommandFailedEvent class encapsulates information about a failed command.

类摘要

MongoDB\Driver\Monitoring\CommandFailedEvent

final class MongoDB\Driver\Monitoring\CommandFailedEvent {

/* 方法 */

final public string getCommandName ( void )

final public int getDurationMicros ( void )

final public Exception getError ( void )

final public string getOperationId ( void )

final public object getReply ( void )

final public string getRequestId ( void )

final public MongoDB\Driver\Server getServer ( void )

}

MongoDB\Driver\Monitoring\CommandFailedEvent::getCommandName

Returns the command name

说明

final public string MongoDB\Driver\Monitoring\CommandFailedEvent::getCommandName ( void )

Returns the command name (e.g. "find", "aggregate").

参数

此函数没有参数。

返回值

Returns the command name.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

MongoDB\Driver\Monitoring\CommandFailedEvent::getDurationMicros

Returns the command's duration in microseconds

说明

final public int MongoDB\Driver\Monitoring\CommandFailedEvent::getDurationMicros ( void )

The command's duration is a calculated value that includes the time to send the message and receive the reply from the server.

参数

此函数没有参数。

返回值

Returns the command's duration in microseconds.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

MongoDB\Driver\Monitoring\CommandFailedEvent::getError

Returns the Exception associated with the failed command

说明

final public Exception MongoDB\Driver\Monitoring\CommandFailedEvent::getError ( void )

参数

此函数没有参数。

返回值

Returns the Exception associated with the failed command.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

MongoDB\Driver\Monitoring\CommandFailedEvent::getOperationId

Returns the command's operation ID

说明

final public string MongoDB\Driver\Monitoring\CommandFailedEvent::getOperationId ( void )

The operation ID is generated by the driver and may be used to link events together such as bulk write operations, which may have been split across several commands at the protocol level.

Note: Since multiple commands may share the same operation ID, it is not reliable to use this value to associate event objects with each other. The request ID returned by class="methodname">MongoDB\Driver\Monitoring\CommandFailedEvent::getRequestId should be used instead.

参数

此函数没有参数。

返回值

Returns the command's operation ID.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\CommandStartedEvent::getOperationId
  • MongoDB\Driver\Monitoring\CommandFailedEvent::getRequestId

MongoDB\Driver\Monitoring\CommandFailedEvent::getReply

Returns the command reply document

说明

final public object MongoDB\Driver\Monitoring\CommandFailedEvent::getReply ( void )

The reply document will be converted from BSON to PHP using the default deserialization rules (e.g. BSON documents will be converted to stdClass).

参数

此函数没有参数。

返回值

Returns the command reply document as a stdClass object.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

MongoDB\Driver\Monitoring\CommandFailedEvent::getRequestId

Returns the command's request ID

说明

final public string MongoDB\Driver\Monitoring\CommandFailedEvent::getRequestId ( void )

The request ID is generated by the driver and may be used to associate this MongoDB\Driver\Monitoring\CommandFailedEvent with a previous MongoDB\Driver\Monitoring\CommandStartedEvent.

参数

此函数没有参数。

返回值

Returns the command's request ID.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId

MongoDB\Driver\Monitoring\CommandFailedEvent::getServer

Returns the Server on which the command was executed

说明

final public MongoDB\Driver\Server MongoDB\Driver\Monitoring\CommandFailedEvent::getServer ( void )

Returns the MongoDB\Driver\Server on which the command was executed.

参数

此函数没有参数。

返回值

Returns the MongoDB\Driver\Server on which the command was executed.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\CommandStartedEvent::getServer

简介

The MongoDB\Driver\Monitoring\CommandStartedEvent class encapsulates information about a started command.

类摘要

MongoDB\Driver\Monitoring\CommandStartedEvent

final class MongoDB\Driver\Monitoring\CommandStartedEvent {

/* 方法 */

final public object getCommand ( void )

final public string getCommandName ( void )

final public string getDatabaseName ( void )

final public string getOperationId ( void )

final public string getRequestId ( void )

final public MongoDB\Driver\Server getServer ( void )

}

MongoDB\Driver\Monitoring\CommandStartedEvent::getCommand

Returns the command document

说明

final public object MongoDB\Driver\Monitoring\CommandStartedEvent::getCommand ( void )

The reply document will be converted from BSON to PHP using the default deserialization rules (e.g. BSON documents will be converted to stdClass).

参数

此函数没有参数。

返回值

Returns the command document as a stdClass object.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

MongoDB\Driver\Monitoring\CommandStartedEvent::getCommandName

Returns the command name

说明

final public string MongoDB\Driver\Monitoring\CommandStartedEvent::getCommandName ( void )

Returns the command name (e.g. "find", "aggregate").

参数

此函数没有参数。

返回值

Returns the command name.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

MongoDB\Driver\Monitoring\CommandStartedEvent::getDatabaseName

Returns the database on which the command was executed

说明

final public string MongoDB\Driver\Monitoring\CommandStartedEvent::getDatabaseName ( void )

参数

此函数没有参数。

返回值

Returns the database on which the command was executed.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

MongoDB\Driver\Monitoring\CommandStartedEvent::getOperationId

Returns the command's operation ID

说明

final public string MongoDB\Driver\Monitoring\CommandStartedEvent::getOperationId ( void )

The operation ID is generated by the driver and may be used to link events together such as bulk write operations, which may have been split across several commands at the protocol level.

Note: Since multiple commands may share the same operation ID, it is not reliable to use this value to associate event objects with each other. The request ID returned by class="methodname">MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId should be used instead.

参数

此函数没有参数。

返回值

Returns the command's operation ID.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\CommandFailedEvent::getOperationId
  • MongoDB\Driver\Monitoring\CommandSucceededEvent::getOperationId
  • MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId

MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId

Returns the command's request ID

说明

final public string MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId ( void )

The request ID is generated by the driver and may be used to associate this MongoDB\Driver\Monitoring\CommandStartedEvent with a later MongoDB\Driver\Monitoring\CommandFailedEvent or MongoDB\Driver\Monitoring\CommandSucceededEvent.

参数

此函数没有参数。

返回值

Returns the command's request ID.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\CommandFailedEvent::getRequestId
  • MongoDB\Driver\Monitoring\CommandSucceededEvent::getRequestId

MongoDB\Driver\Monitoring\CommandStartedEvent::getServer

Returns the Server on which the command was executed

说明

final public MongoDB\Driver\Server MongoDB\Driver\Monitoring\CommandStartedEvent::getServer ( void )

Returns the MongoDB\Driver\Server on which the command was executed.

参数

此函数没有参数。

返回值

Returns the MongoDB\Driver\Server on which the command was executed.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\CommandFailedEvent::getServer
  • MongoDB\Driver\Monitoring\CommandSucceededEvent::getServer

简介

The MongoDB\Driver\Monitoring\CommandSucceededEvent class encapsulates information about a successful command.

类摘要

MongoDB\Driver\Monitoring\CommandSucceededEvent

final class MongoDB\Driver\Monitoring\CommandSucceededEvent {

/* 方法 */

final public string getCommandName ( void )

final public int getDurationMicros ( void )

final public string getOperationId ( void )

final public object getReply ( void )

final public string getRequestId ( void )

final public MongoDB\Driver\Server getServer ( void )

}

MongoDB\Driver\Monitoring\CommandSucceededEvent::getCommandName

Returns the command name

说明

final public string MongoDB\Driver\Monitoring\CommandSucceededEvent::getCommandName ( void )

Returns the command name (e.g. "find", "aggregate").

参数

此函数没有参数。

返回值

Returns the command name.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

MongoDB\Driver\Monitoring\CommandSucceededEvent::getDurationMicros

Returns the command's duration in microseconds

说明

final public int MongoDB\Driver\Monitoring\CommandSucceededEvent::getDurationMicros ( void )

The command's duration is a calculated value that includes the time to send the message and receive the reply from the server.

参数

此函数没有参数。

返回值

Returns the command's duration in microseconds.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

MongoDB\Driver\Monitoring\CommandSucceededEvent::getOperationId

Returns the command's operation ID

说明

final public string MongoDB\Driver\Monitoring\CommandSucceededEvent::getOperationId ( void )

The operation ID is generated by the driver and may be used to link events together such as bulk write operations, which may have been split across several commands at the protocol level.

Note: Since multiple commands may share the same operation ID, it is not reliable to use this value to associate event objects with each other. The request ID returned by class="methodname">MongoDB\Driver\Monitoring\CommandSucceededEvent::getRequestId should be used instead.

参数

此函数没有参数。

返回值

Returns the command's operation ID.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\CommandStartedEvent::getOperationId
  • MongoDB\Driver\Monitoring\CommandSucceededEvent::getRequestId

MongoDB\Driver\Monitoring\CommandSucceededEvent::getReply

Returns the command reply document

说明

final public object MongoDB\Driver\Monitoring\CommandSucceededEvent::getReply ( void )

The reply document will be converted from BSON to PHP using the default deserialization rules (e.g. BSON documents will be converted to stdClass).

参数

此函数没有参数。

返回值

Returns the command reply document as a stdClass object.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

MongoDB\Driver\Monitoring\CommandSucceededEvent::getRequestId

Returns the command's request ID

说明

final public string MongoDB\Driver\Monitoring\CommandSucceededEvent::getRequestId ( void )

The request ID is generated by the driver and may be used to associate this MongoDB\Driver\Monitoring\CommandSucceededEvent with a previous MongoDB\Driver\Monitoring\CommandStartedEvent.

参数

此函数没有参数。

返回值

Returns the command's request ID.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId

MongoDB\Driver\Monitoring\CommandSucceededEvent::getServer

Returns the Server on which the command was executed

说明

final public MongoDB\Driver\Server MongoDB\Driver\Monitoring\CommandSucceededEvent::getServer ( void )

Returns the MongoDB\Driver\Server on which the command was executed.

参数

此函数没有参数。

返回值

Returns the MongoDB\Driver\Server on which the command was executed.

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\CommandStartedEvent::getServer
  • MongoDB\Driver\Cursor::getServer
  • MongoDB\Driver\WriteResult::getServer

简介

Classes may implement this interface to register an event subscriber that is notified for each started, successful, and failed command event. See for additional information.

接口摘要

MongoDB\Driver\Monitoring\CommandSubscriber

class MongoDB\Driver\Monitoring\CommandSubscriber implements MongoDB\Driver\Monitoring\Subscriber {

/* 方法 */

abstract public void commandFailed ( MongoDB\Driver\Monitoring\CommandFailedEvent $event )

abstract public void commandStarted ( MongoDB\Driver\Monitoring\CommandStartedEvent $event )

abstract public void commandSucceeded ( MongoDB\Driver\Monitoring\CommandSucceededEvent $event )

}

MongoDB\Driver\Monitoring\CommandSubscriber::commandFailed

Notification method for a failed command

说明

abstract public void MongoDB\Driver\Monitoring\CommandSubscriber::commandFailed ( MongoDB\Driver\Monitoring\CommandFailedEvent $event )

If the subscriber has been registered with MongoDB\Driver\Monitoring\addSubscriber, the driver will call this method when a command has failed.

参数

event (MongoDB\Driver\Monitoring\CommandFailedEvent)
An event object encapsulating information about the failed command.

返回值

没有返回值。

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\CommandFailedEvent
  • MongoDB\Driver\Monitoring\addSubscriber

MongoDB\Driver\Monitoring\CommandSubscriber::commandStarted

Notification method for a started command

说明

abstract public void MongoDB\Driver\Monitoring\CommandSubscriber::commandStarted ( MongoDB\Driver\Monitoring\CommandStartedEvent $event )

If the subscriber has been registered with MongoDB\Driver\Monitoring\addSubscriber, the driver will call this method when a command has started.

参数

event (MongoDB\Driver\Monitoring\CommandStartedEvent)
An event object encapsulating information about the started command.

返回值

没有返回值。

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\CommandStartedEvent
  • MongoDB\Driver\Monitoring\addSubscriber

MongoDB\Driver\Monitoring\CommandSubscriber::commandSucceeded

Notification method for a successful command

说明

abstract public void MongoDB\Driver\Monitoring\CommandSubscriber::commandSucceeded ( MongoDB\Driver\Monitoring\CommandSucceededEvent $event )

If the subscriber has been registered with MongoDB\Driver\Monitoring\addSubscriber, the driver will call this method when a command has succeeded.

参数

event (MongoDB\Driver\Monitoring\CommandSucceededEvent)
An event object encapsulating information about the successful command.

返回值

没有返回值。

错误/异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\CommandSucceededEvent
  • MongoDB\Driver\Monitoring\addSubscriber

简介

Base interface for event subscribers. This is used for type-hinting MongoDB\Driver\Monitoring\addSubscriber and MongoDB\Driver\Monitoring\removeSubscriber and should not be implemented directly.

接口摘要

MongoDB\Driver\Monitoring\Subscriber

class MongoDB\Driver\Monitoring\Subscriber {

}

This interface has no methods. Its only purpose is to be the base interface for all event subscribers.

Exception 类

目录

简介

Thrown when the driver fails to authenticate with the server.

类摘要

MongoDB\Driver\Exception\AuthenticationException

class MongoDB\Driver\Exception\AuthenticationException extends MongoDB\Driver\Exception\ConnectionException implements MongoDB\Driver\Exception\Exception {

/* 继承的属性 */

protected bool $errorLabels ;

protected string $message ;

protected int $code ;

protected string $file ;

protected int $line ;

/* 继承的方法 */

final public bool MongoDB\Driver\Exception\RuntimeException::hasErrorLabel ( string $errorLabel )

final public string Exception::getMessage ( void )

final public Throwable Exception::getPrevious ( void )

final public int Exception::getCode ( void )

final public string Exception::getFile ( void )

final public int Exception::getLine ( void )

final public array Exception::getTrace ( void )

final public string Exception::getTraceAsString ( void )

public string Exception::__toString ( void )

final private void Exception::__clone ( void )

}

简介

Thrown when a bulk write operation fails.

类摘要

MongoDB\Driver\Exception\BulkWriteException

class MongoDB\Driver\Exception\BulkWriteException extends MongoDB\Driver\Exception\WriteException implements MongoDB\Driver\Exception\Exception {

/* 继承的属性 */

protected MongoDB\Driver\WriteResult $writeResult ;

protected bool $errorLabels ;

protected string $message ;

protected int $code ;

protected string $file ;

protected int $line ;

/* 继承的方法 */

final public MongoDB\Driver\WriteResult MongoDB\Driver\Exception\WriteException::getWriteResult ( void )

final public bool MongoDB\Driver\Exception\RuntimeException::hasErrorLabel ( string $errorLabel )

final public string Exception::getMessage ( void )

final public Throwable Exception::getPrevious ( void )

final public int Exception::getCode ( void )

final public string Exception::getFile ( void )

final public int Exception::getLine ( void )

final public array Exception::getTrace ( void )

final public string Exception::getTraceAsString ( void )

public string Exception::__toString ( void )

final private void Exception::__clone ( void )

}

简介

Base class for exceptions thrown when the driver fails to establish a database connection.

类摘要

MongoDB\Driver\Exception\ConnectionException

class MongoDB\Driver\Exception\ConnectionException extends MongoDB\Driver\Exception\RuntimeException implements MongoDB\Driver\Exception\Exception {

/* 继承的属性 */

protected bool $errorLabels ;

protected string $message ;

protected int $code ;

protected string $file ;

protected int $line ;

/* 继承的方法 */

final public bool MongoDB\Driver\Exception\RuntimeException::hasErrorLabel ( string $errorLabel )

final public string Exception::getMessage ( void )

final public Throwable Exception::getPrevious ( void )

final public int Exception::getCode ( void )

final public string Exception::getFile ( void )

final public int Exception::getLine ( void )

final public array Exception::getTrace ( void )

final public string Exception::getTraceAsString ( void )

public str