Set/mongodb-Phpdoc专题
MongoDB driver
目录
- 安装/配置
- Tutorials — Tutorials
- Driver Architecture and
Internals
— Explains the driver architecture, and special features
- Architecture — Architecture Overview
- Connections — Connection handling and persistence
- Persisting Data — Serialization and deserialization of PHP variables into MongoDB
- Security
- MongoDB\Driver — MongoDB 驱动类
- MongoDB\Driver\Manager — The MongoDB\Driver\Manager class
- MongoDB\Driver\Command — The MongoDB\Driver\Command class
- MongoDB\Driver\Query — The MongoDB\Driver\Query class
- MongoDB\Driver\BulkWrite — The MongoDB\Driver\BulkWrite class
- MongoDB\Driver\WriteConcern — The MongoDB\Driver\WriteConcern class
- MongoDB\Driver\ReadPreference — The MongoDB\Driver\ReadPreference class
- MongoDB\Driver\ReadConcern — The MongoDB\Driver\ReadConcern class
- MongoDB\Driver\Cursor — The MongoDB\Driver\Cursor class
- MongoDB\Driver\CursorId — The MongoDB\Driver\CursorId class
- MongoDB\Driver\Server — The MongoDB\Driver\Server class
- MongoDB\Driver\WriteConcernError — The MongoDB\Driver\WriteConcernError class
- MongoDB\Driver\WriteError — The MongoDB\Driver\WriteError class
- MongoDB\Driver\WriteResult — The MongoDB\Driver\WriteResult class
- MongoDB\BSON — BSON type classes
and serialization functions
- 函数
- MongoDB\BSON\Binary — The MongoDB\BSON\Binary class
- MongoDB\BSON\Decimal128 — The MongoDB\BSON\Decimal128 class
- MongoDB\BSON\Javascript — The MongoDB\BSON\Javascript class
- MongoDB\BSON\MaxKey — The MongoDB\BSON\MaxKey class
- MongoDB\BSON\MinKey — The MongoDB\BSON\MinKey class
- MongoDB\BSON\ObjectId — The MongoDB\BSON\ObjectId class
- MongoDB\BSON\Regex — The MongoDB\BSON\Regex class
- MongoDB\BSON\Timestamp — The MongoDB\BSON\Timestamp class
- MongoDB\BSON\UTCDateTime — The MongoDB\BSON\UTCDateTime class
- MongoDB\BSON\Type — The MongoDB\BSON\Type interface
- MongoDB\BSON\Persistable — The MongoDB\BSON\Persistable interface
- MongoDB\BSON\Serializable — The MongoDB\BSON\Serializable interface
- MongoDB\BSON\Unserializable — The MongoDB\BSON\Unserializable interface
- MongoDB\BSON\BinaryInterface — The MongoDB\BSON\BinaryInterface interface
- MongoDB\BSON\Decimal128Interface — The MongoDB\BSON\Decimal128Interface interface
- MongoDB\BSON\JavascriptInterface — The MongoDB\BSON\JavascriptInterface interface
- MongoDB\BSON\MaxKeyInterface — The MongoDB\BSON\MaxKeyInterface interface
- MongoDB\BSON\MinKeyInterface — The MongoDB\BSON\MinKeyInterface interface
- MongoDB\BSON\ObjectIdInterface — The MongoDB\BSON\ObjectIdInterface interface
- MongoDB\BSON\RegexInterface — The MongoDB\BSON\RegexInterface interface
- MongoDB\BSON\TimestampInterface — The MongoDB\BSON\TimestampInterface interface
- MongoDB\BSON\UTCDateTimeInterface — The MongoDB\BSON\UTCDateTimeInterface interface
- MongoDB\BSON\DBPointer — The MongoDB\BSON\DBPointer class (deprecated)
- MongoDB\BSON\Int64 — The MongoDB\BSON\Int64 class
- MongoDB\BSON\Symbol — The MongoDB\BSON\Symbol class (deprecated)
- MongoDB\BSON\Undefined — The MongoDB\BSON\Undefined class (deprecated)
- MongoDB\Driver\Monitoring
— Monitoring classes and subscriber functions
- 函数
- MongoDB\Driver\Monitoring\CommandFailedEvent — The MongoDB\Driver\Monitoring\CommandFailedEvent class
- MongoDB\Driver\Monitoring\CommandStartedEvent — The MongoDB\Driver\Monitoring\CommandStartedEvent class
- MongoDB\Driver\Monitoring\CommandSucceededEvent — The MongoDB\Driver\Monitoring\CommandSucceededEvent class
- MongoDB\Driver\Monitoring\CommandSubscriber — The MongoDB\Driver\Monitoring\CommandSubscriber interface
- MongoDB\Driver\Monitoring\Subscriber — The MongoDB\Driver\Monitoring\Subscriber interface
- MongoDB\Driver\Exception
— Exception 类
- MongoDB\Driver\Exception\AuthenticationException — The MongoDB\Driver\Exception\AuthenticationException class
- MongoDB\Driver\Exception\BulkWriteException — The MongoDB\Driver\Exception\BulkWriteException class
- MongoDB\Driver\Exception\ConnectionException — The MongoDB\Driver\Exception\ConnectionException class
- MongoDB\Driver\Exception\ConnectionTimeoutException — The MongoDB\Driver\Exception\ConnectionTimeoutException class
- MongoDB\Driver\Exception\Exception — The MongoDB\Driver\Exception\Exception interface
- MongoDB\Driver\Exception\ExecutionTimeoutException — The MongoDB\Driver\Exception\ExecutionTimeoutException class
- MongoDB\Driver\Exception\InvalidArgumentException — The MongoDB\Driver\Exception\InvalidArgumentException class
- MongoDB\Driver\Exception\LogicException — The MongoDB\Driver\Exception\LogicException class
- MongoDB\Driver\Exception\RuntimeException — The MongoDB\Driver\Exception\RuntimeException class
- MongoDB\Driver\Exception\SSLConnectionException — The MongoDB\Driver\Exception\SSLConnectionException class (deprecated)
- MongoDB\Driver\Exception\UnexpectedValueException — The MongoDB\Driver\Exception\UnexpectedValueException class
- MongoDB\Driver\Exception\WriteException — The MongoDB\Driver\Exception\WriteException class
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.
安装/配置
目录
需求
As of version 1.8.0, the driver requires PHP 7.0 or higher. Previous versions of the driver allow compatibility with older PHP versions.
The driver requires » libbson and » libmongoc, and will use bundled versions of both libraries by default. System libraries may also be used, as discussed in the manual installation documentation.
The driver, via libmongoc, optionally depends on a TLS library (e.g. OpenSSL) and will use it if available. If the build process fails to find a TLS library, users should check that the appropriate development package (e.g. libssl-dev) and » pkg-config are both installed. The process for detecting and configuring TLS libraries is discussed in more detail in the manual installation documentation.
» Cyrus SASL is an optional dependency to support Kerberos authentication and will be used if available.
Note: 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 <span class="classname">MongoDB\BSON\Int64 instance instead of a PHP integer type.
安装
目录
- Installing the MongoDB PHP Driver with PECL
- Installing the MongoDB PHP Driver on macOS with Homebrew
- Installing the MongoDB PHP Driver on Windows
- Building the MongoDB PHP Driver from source
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 <span class="classname">MongoDB\Driver\Monitoring\CommandSubscriber interface is available.
The <span
class="classname">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 <span
class="classname">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 <span class="methodname">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 — Architecture Overview
- Connections — Connection handling and persistence
- Persisting Data — Serialization and deserialization of PHP variables into MongoDB
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.
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:
| Project | GitHub | JIRA |
|---|---|---|
| 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 <span 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 <span class="methodname">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 <span class="classname">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 <span class="classname">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 <span class="interfacename">MongoDB\BSON\Type, then use the BSON serialization logic for that specific type. <span class="interfacename">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 <span class="classname">MongoDB\Driver\Exception\UnexpectedValueException
If an object is of an unknown class implementing the <span class="interfacename">MongoDB\BSON\Type interface, then throw a <span class="classname">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 <span class="interfacename">MongoDB\BSON\Serializable interface, call <span class="methodname">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:
-
Root documents must be serialized as a BSON document.
-
MongoDB\BSON\Persistable objects must be serialized as a BSON document.
-
If <span class="methodname">MongoDB\BSON\Serializable::bsonSerialize returns a packed array, serialize as a BSON array.
-
If <span class="methodname">MongoDB\BSON\Serializable::bsonSerialize returns a non-packed array or <span class="classname">stdClass, serialize as a BSON document.
-
If <span class="methodname">MongoDB\BSON\Serializable::bsonSerialize did not return an array or stdClass, throw an <span class="classname">MongoDB\Driver\Exception\UnexpectedValueException exception.
If an object is of a class that implements the <span class="interfacename">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 <span class="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 <span class="methodname">MongoDB\BSON\Serializable::bsonSerialize, which means it will overwrite any <span class="property">__pclass key/property in the <span class="methodname">MongoDB\BSON\Serializable::bsonSerialize return value. If you want to avoid this behaviour and set your own <span class="property">__pclass value, you must not implement <span class="interfacename">MongoDB\BSON\Persistable and should instead implement <span class="interfacename">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 <span class="classname">Address class and each "city" field within those embedded address documents to a <span class="classname">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 <span class="type">array.
-
A BSON document (root or embedded) without a <span class="property">__pclass property [1] becomes a PHP stdClass object, with each BSON document key set as a public <span class="classname">stdClass property.
-
A BSON document (root or embedded) with a <span class="property">__pclass property [1] becomes a PHP object of the class name as defined by the <span class="property">__pclass property.
If the named class implements the <span class="interfacename">MongoDB\BSON\Persistable interface, then the properties of the BSON document, including the <span class="property">__pclass property, are sent as an associative array to the <span class="methodname">MongoDB\BSON\Unserializable::bsonUnserialize function to initialise the object's properties.
If the named class does not exist or does not implement the <span class="interfacename">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 <span class="property">__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 <span
class="classname">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 <span
class="property">__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 <span class="interfacename">MongoDB\BSON\Unserializable then an <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException exception is thrown.
If the BSON object has a __pclass property and that class exists and implements <span class="interfacename">MongoDB\BSON\Persistable it will supersede the class provided in the type map.
The properties of the BSON document, including the <span class="property">__pclass property if it exists, will be sent as an associative array to the <span class="methodname">MongoDB\BSON\Unserializable::bsonUnserialize function to initialise the object's properties.
TypeMaps
TypeMaps can be set through the <span class="methodname">MongoDB\Driver\Cursor::setTypeMap method on a MongoDB\Driver\Cursor object, or the $typeMap argument of <span class="function">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 <span
class="interfacename">MongoDB\BSON\Unserializable
OurClass
which implements <span
class="interfacename">MongoDB\BSON\Persistable
TheirClass
which extends OurClass
The <span class="methodname">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]<span class="para footnote"> 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 <span class="classname">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 驱动类
目录
- MongoDB\Driver\Manager
— The MongoDB\Driver\Manager class
- MongoDB\Driver\Manager::__construct — Create new MongoDB Manager
- MongoDB\Driver\Manager::createClientEncryption — Create a new ClientEncryption object
- MongoDB\Driver\Manager::executeBulkWrite — Execute one or more write operations
- MongoDB\Driver\Manager::executeCommand — Execute a database command
- MongoDB\Driver\Manager::executeQuery — Execute a database query
- MongoDB\Driver\Manager::executeReadCommand — Execute a database command that reads
- MongoDB\Driver\Manager::executeReadWriteCommand — Execute a database command that reads and writes
- MongoDB\Driver\Manager::executeWriteCommand — Execute a database command that writes
- MongoDB\Driver\Manager::getReadConcern — Return the ReadConcern for the Manager
- MongoDB\Driver\Manager::getReadPreference — Return the ReadPreference for the Manager
- MongoDB\Driver\Manager::getServers — Return the servers to which this manager is connected
- MongoDB\Driver\Manager::getWriteConcern — Return the WriteConcern for the Manager
- MongoDB\Driver\Manager::selectServer — Select a server matching a read preference
- MongoDB\Driver\Manager::startSession — Start a new client session for use with this client
- MongoDB\Driver\Command
— The MongoDB\Driver\Command class
- MongoDB\Driver\Command::__construct — Create a new Command
- MongoDB\Driver\Query —
The MongoDB\Driver\Query class
- MongoDB\Driver\Query::__construct — Create a new Query
- MongoDB\Driver\BulkWrite
— The MongoDB\Driver\BulkWrite class
- MongoDB\Driver\BulkWrite::__construct — Create a new BulkWrite
- MongoDB\Driver\BulkWrite::count — Count number of write operations in the bulk
- MongoDB\Driver\BulkWrite::delete — Add a delete operation to the bulk
- MongoDB\Driver\BulkWrite::insert — Add an insert operation to the bulk
- MongoDB\Driver\BulkWrite::update — Add an update operation to the bulk
- MongoDB\Driver\WriteConcern
— The MongoDB\Driver\WriteConcern class
- MongoDB\Driver\WriteConcern::bsonSerialize — Returns an object for BSON serialization
- MongoDB\Driver\WriteConcern::__construct — Create a new WriteConcern
- MongoDB\Driver\WriteConcern::getJournal — Returns the WriteConcern's "journal" option
- MongoDB\Driver\WriteConcern::getW — Returns the WriteConcern's "w" option
- MongoDB\Driver\WriteConcern::getWtimeout — Returns the WriteConcern's "wtimeout" option
- MongoDB\Driver\WriteConcern::isDefault — Checks if this is the default write concern
- MongoDB\Driver\WriteConcern::serialize — Serialize a WriteConcern
- MongoDB\Driver\WriteConcern::unserialize — Unserialize a WriteConcern
- MongoDB\Driver\ReadPreference
— The MongoDB\Driver\ReadPreference class
- MongoDB\Driver\ReadPreference::bsonSerialize — Returns an object for BSON serialization
- MongoDB\Driver\ReadPreference::__construct — Create a new ReadPreference
- MongoDB\Driver\ReadPreference::getHedge — Returns the ReadPreference's "hedge" option
- MongoDB\Driver\ReadPreference::getMaxStalenessSeconds — Returns the ReadPreference's "maxStalenessSeconds" option
- MongoDB\Driver\ReadPreference::getMode — Returns the ReadPreference's "mode" option
- MongoDB\Driver\ReadPreference::getModeString — Returns the ReadPreference's "mode" option as a string
- MongoDB\Driver\ReadPreference::getTagSets — Returns the ReadPreference's "tagSets" option
- MongoDB\Driver\ReadPreference::serialize — Serialize a ReadPreference
- MongoDB\Driver\ReadPreference::unserialize — Unserialize a ReadPreference
- MongoDB\Driver\ReadConcern
— The MongoDB\Driver\ReadConcern class
- MongoDB\Driver\ReadConcern::bsonSerialize — Returns an object for BSON serialization
- MongoDB\Driver\ReadConcern::__construct — Create a new ReadConcern
- MongoDB\Driver\ReadConcern::getLevel — Returns the ReadConcern's "level" option
- MongoDB\Driver\ReadConcern::isDefault — Checks if this is the default read concern
- MongoDB\Driver\ReadConcern::serialize — Serialize a ReadConcern
- MongoDB\Driver\ReadConcern::unserialize — Unserialize a ReadConcern
- MongoDB\Driver\Cursor —
The MongoDB\Driver\Cursor class
- MongoDB\Driver\Cursor::__construct — Create a new Cursor (not used)
- MongoDB\Driver\Cursor::current — Returns the current element
- MongoDB\Driver\Cursor::getId — Returns the ID for this cursor
- MongoDB\Driver\Cursor::getServer — Returns the server associated with this cursor
- MongoDB\Driver\Cursor::isDead — Checks if the cursor is exhausted or may have additional results
- MongoDB\Driver\Cursor::key — Returns the current result's index within the cursor
- MongoDB\Driver\Cursor::next — Advances the cursor to the next result
- MongoDB\Driver\Cursor::rewind — Rewind the cursor to the first result
- MongoDB\Driver\Cursor::setTypeMap — Sets a type map to use for BSON unserialization
- MongoDB\Driver\Cursor::toArray — Returns an array containing all results for this cursor
- MongoDB\Driver\Cursor::valid — Checks if the current position in the cursor is valid
- MongoDB\Driver\CursorId
— The MongoDB\Driver\CursorId class
- MongoDB\Driver\CursorId::__construct — Create a new CursorId (not used)
- MongoDB\Driver\CursorId::serialize — Serialize a CursorId
- MongoDB\Driver\CursorId::__toString — String representation of the cursor ID
- MongoDB\Driver\CursorId::unserialize — Unserialize a CursorId
- MongoDB\Driver\Server —
The MongoDB\Driver\Server class
- MongoDB\Driver\Server::__construct — Create a new Server (not used)
- MongoDB\Driver\Server::executeBulkWrite — Execute one or more write operations on this server
- MongoDB\Driver\Server::executeCommand — Execute a database command on this server
- MongoDB\Driver\Server::executeQuery — Execute a database query on this server
- MongoDB\Driver\Server::executeReadCommand — Execute a database command that reads on this server
- MongoDB\Driver\Server::executeReadWriteCommand — Execute a database command that reads and writes on this server
- MongoDB\Driver\Server::executeWriteCommand — Execute a database command that writes on this server
- MongoDB\Driver\Server::getHost — Returns the hostname of this server
- MongoDB\Driver\Server::getInfo — Returns an array of information about this server
- MongoDB\Driver\Server::getLatency — Returns the latency of this server
- MongoDB\Driver\Server::getPort — Returns the port on which this server is listening
- MongoDB\Driver\Server::getTags — Returns an array of tags describing this server in a replica set
- MongoDB\Driver\Server::getType — Returns an integer denoting the type of this server
- MongoDB\Driver\Server::isArbiter — Checks if this server is an arbiter member of a replica set
- MongoDB\Driver\Server::isHidden — Checks if this server is a hidden member of a replica set
- MongoDB\Driver\Server::isPassive — Checks if this server is a passive member of a replica set
- MongoDB\Driver\Server::isPrimary — Checks if this server is a primary member of a replica set
- MongoDB\Driver\Server::isSecondary — Checks if this server is a secondary member of a replica set
- MongoDB\Driver\WriteConcernError
— The MongoDB\Driver\WriteConcernError class
- MongoDB\Driver\WriteConcernError::getCode — Returns the WriteConcernError's error code
- MongoDB\Driver\WriteConcernError::getInfo — Returns metadata document for the WriteConcernError
- MongoDB\Driver\WriteConcernError::getMessage — Returns the WriteConcernError's error message
- MongoDB\Driver\WriteError
— The MongoDB\Driver\WriteError class
- MongoDB\Driver\WriteError::getCode — Returns the WriteError's error code
- MongoDB\Driver\WriteError::getIndex — Returns the index of the write operation corresponding to this WriteError
- MongoDB\Driver\WriteError::getInfo — Returns metadata document for the WriteError
- MongoDB\Driver\WriteError::getMessage — Returns the WriteError's error message
- MongoDB\Driver\WriteResult
— The MongoDB\Driver\WriteResult class
- MongoDB\Driver\WriteResult::getDeletedCount — Returns the number of documents deleted
- MongoDB\Driver\WriteResult::getInsertedCount — Returns the number of documents inserted (excluding upserts)
- MongoDB\Driver\WriteResult::getMatchedCount — Returns the number of documents selected for update
- MongoDB\Driver\WriteResult::getModifiedCount — Returns the number of existing documents updated
- MongoDB\Driver\WriteResult::getServer — Returns the server associated with this write result
- MongoDB\Driver\WriteResult::getUpsertedCount — Returns the number of documents inserted by an upsert
- MongoDB\Driver\WriteResult::getUpsertedIds — Returns an array of identifiers for upserted documents
- MongoDB\Driver\WriteResult::getWriteConcernError — Returns any write concern error that occurred
- MongoDB\Driver\WriteResult::getWriteErrors — Returns any write errors that occurred
- MongoDB\Driver\WriteResult::isAcknowledged — Returns whether the write was acknowledged
简介
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 ([ <span
class="methodparam">string $uri<span
class="initializer"> = "mongodb://127.0.0.1/" [, <span
class="methodparam">array $uriOptions<span
class="initializer"> = array() [, <span
class="methodparam">array
$driverOptions = array()
]]] )
final public
MongoDB\Driver\ClientEncryption <span
class="methodname">createClientEncryption ( <span
class="methodparam">array $options )
final public
MongoDB\Driver\WriteResult <span
class="methodname">executeBulkWrite ( <span
class="methodparam">string $namespace
, <span
class="type">MongoDB\Driver\BulkWrite $bulk [, <span
class="methodparam">array $options<span
class="initializer"> = array() ] )
final public
MongoDB\Driver\Cursor <span
class="methodname">executeCommand ( <span
class="methodparam">string $db ,
<span
class="type">MongoDB\Driver\Command $command [, <span
class="methodparam">array $options<span
class="initializer"> = array() ] )
final public
MongoDB\Driver\Cursor <span
class="methodname">executeQuery ( <span
class="type">string $namespace , <span
class="methodparam">MongoDB\Driver\Query
$query [, <span
class="type">array $options =
array() ] )
final public
MongoDB\Driver\Cursor <span
class="methodname">executeReadCommand ( <span
class="methodparam">string $db ,
<span
class="type">MongoDB\Driver\Command $command [, <span
class="methodparam">array $options<span
class="initializer"> = array() ] )
final public
MongoDB\Driver\Cursor <span
class="methodname">executeReadWriteCommand ( <span
class="methodparam">string $db ,
<span
class="type">MongoDB\Driver\Command $command [, <span
class="methodparam">array $options<span
class="initializer"> = array() ] )
final public
MongoDB\Driver\Cursor <span
class="methodname">executeWriteCommand ( <span
class="methodparam">string $db ,
<span
class="type">MongoDB\Driver\Command $command [, <span
class="methodparam">array $options<span
class="initializer"> = array() ] )
final public MongoDB\Driver\ReadConcern <span class="methodname">getReadConcern ( <span class="methodparam">void )
final public MongoDB\Driver\ReadPreference <span class="methodname">getReadPreference ( <span class="methodparam">void )
final public array <span class="methodname">getServers ( <span class="methodparam">void )
final public MongoDB\Driver\WriteConcern <span class="methodname">getWriteConcern ( <span class="methodparam">void )
final public
MongoDB\Driver\Server <span
class="methodname">selectServer ( <span
class="type">MongoDB\Driver\ReadPreference
$readPreference )
final public
MongoDB\Driver\Session <span
class="methodname">startSession ([ <span
class="methodparam">array $options ]
)
}
范例
示例 #1 <span class="function">MongoDB\Driver\Manager::__construct basic example
var_dumping a <span class="classname">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
uriOptionsparameter, 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 <span 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]]][/[defaultAuthDb][?options]]
For details on supported URI 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 <span
class="function">rawurlencode function may be used to encode
constituent parts of the URI.
The defaultAuthDb component may be used to specify the database name associated with the user's credentials; however the authSource URI option will take priority if specified. If neither defaultAuthDb nor authSource are specified, the admin database will be used by default. The defaultAuthDb component has no effect in the absence of user credentials.
uriOptions
Additional
» connection string options,
which will overwrite any options with the same name in the uri
parameter.
| 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.
|
| authSource | string | The database name associated with the user's credentials. Defaults to the database component of the connection URI, or the admin database if both are unspecified. For authentication mechanisms that delegate credential storage to other services (e.g. GSSAPI), this should be "$external". |
| canonicalizeHostname | bool | If 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 | int | The time in milliseconds to attempt a connection before timing out. Defaults to 10,000 milliseconds. |
| directConnection | bool | This option can be used to control replica set discovery behavior when only a single host is provided in the connection string. By default, providing a single member in the connection string will establish a direct connection or discover additional members depending on whether the "replicaSet" URI option is omitted or present, respectively. Specify |
| 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 | int | 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 | bool | Corresponds to the default write concern's |
| localThresholdMS | int | 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 | int | 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 |
| 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 |
| readPreferenceTags | array | Corresponds to the read preference's
|
| replicaSet | string | Specifies the name of the replica set. |
| retryReads | bool | 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 See the » Retryable Reads Specification for more information. |
| retryWrites | bool | 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 See » Retryable Writes in the MongoDB manual for more information. |
| safe | bool | If This option is deprecated and should not be used. |
| serverSelectionTimeoutMS | int | Specifies how long in milliseconds to block for server selection before throwing an exception. Defaults to 30,000 milliseconds. |
| serverSelectionTryOnce | bool | When |
| slaveOk | bool | Specifies "secondaryPreferred" for the read preference mode if This option is deprecated and should not be used. |
| socketCheckIntervalMS | int | 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 | int | 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 | bool | Initiates the connection with TLS/SSL if This option is a deprecated alias for the "tls" URI option. |
| tls | bool | Initiates the connection with TLS/SSL if |
| tlsAllowInvalidCertificates | bool | Specifies whether or not the driver should error when the server's TLS certificate is invalid. Defaults to
Warning
Disabling certificate validation creates a vulnerability. |
| tlsAllowInvalidHostnames | bool | 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
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. |
| tlsDisableCertificateRevocationCheck | bool | If |
| tlsDisableOCSPEndpointCheck | bool | If |
| tlsInsecure | bool | Relax TLS constraints as much as possible. Specifying
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 | intstring | Corresponds to the default write concern's |
| wTimeoutMS | intstring | Corresponds to the default write concern's If specified, wTimeoutMS must be a signed 32-bit integer greater than or equal to zero. |
| zlibCompressionLevel | int | 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
| Option | Type | Description | |||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| allow_invalid_hostname | bool | Disables hostname validation if 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:
|
|||||||||||||||||||||
| 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:
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, version, and platform (i.e. PHP version) in the handshake. Custom drivers can specify strings for the "name", "version", and "platform" keys of this array, which will be appended to the respective field(s) in the handshake document.
|
|||||||||||||||||||||
| 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 | bool | Disables certificate validation if This option is a deprecated alias for the "tlsAllowInvalidHostnames" URI option. |
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span
class="classname">MongoDB\Driver\Exception\RuntimeException
if the
uriformat is invalid
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.8.0 | Added the "directConnection", "tlsDisableCertificateRevocationCheck", and "tlsDisableOCSPEndpointCheck" URI options. Added the "driver" driver option. |
| PECL mongodb 1.7.0 | Added the "autoEncryption" driver option. Specifying any SSL or TLS option via the |
| PECL mongodb 1.6.0 | Added the "retryReads", "tls", "tlsAllowInvalidCertificates", "tlsAllowInvalidHostnames", "tlsCAFile", "tlsCertificateKeyFile", "tlsCertificateKeyFilePassword", and "tlsInsecure" URI options. The "retryWrites" URI option defaults to Specifying any SSL or TLS URI option via the connection string or |
| PECL mongodb 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. |
| PECL mongodb 1.4.0 | Added the "compressors", "retryWrites", and "zlibCompressionLevel" URI options. |
| PECL mongodb 1.3.0 | The |
| PECL mongodb 1.2.0 | The 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. |
| PECL mongodb 1.1.0 | The |
范例
示例 #1 <span class="function">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:[email protected]/?authSource=databaseName");
?>
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, <span class="function">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%[email protected]/?authSource=databaseName");
?>
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 <span
class="methodname">MongoDB\Driver\Manager::createClientEncryption
( array
$options )
Constructs a new <span class="classname">MongoDB\Driver\ClientEncryption object with the specified 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: The format for local is as follows: |
返回值
Returns a new <span class="classname">MongoDB\Driver\ClientEncryption instance.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span class="classname">MongoDB\Driver\Exception\RuntimeException if the extension was compiled without libmongocrypt support
参见
- MongoDB\Driver\ClientEncryption
- » Explicit (Manual) Client-Side Field Level Encryption in the MongoDB manual
MongoDB\Driver\Manager::executeBulkWrite
Execute one or more write operations
说明
final public
MongoDB\Driver\WriteResult <span
class="methodname">MongoDB\Driver\Manager::executeBulkWrite (
string
$namespace , <span
class="type">MongoDB\Driver\BulkWrite $bulk [, <span
class="methodparam">array $options<span
class="initializer"> = 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 <span
class="classname">MongoDB\Driver\Exception\InvalidArgumentException
if
bulkdoes not contain any write operations. - Throws <span
class="classname">MongoDB\Driver\Exception\InvalidArgumentException
if
bulkhas already been executed. <span class="classname">MongoDB\Driver\BulkWrite objects may not be executed multiple times. - Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used in combination with an unacknowledged write concern.
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span class="classname">MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws <span class="classname">MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws <span class="classname">MongoDB\Driver\Exception\BulkWriteException on any write failure (e.g. write error, failure to apply a write concern)
- Throws <span class="classname">MongoDB\Driver\Exception\RuntimeException on other errors.
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.4.4 | MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the "session" option is used in combination with an unacknowledged write concern. |
| PECL mongodb 1.4.0 | The third parameter is now an options array. For backwards compatibility, this paramater will still accept a MongoDB\Driver\WriteConcern object. |
| PECL mongodb 1.3.0 | MongoDB\Driver\Exception\InvalidArgumentException is now thrown if bulk does not contain any write operations. Previously, a MongoDB\Driver\Exception\BulkWriteException was thrown. |
范例
示例 #1 <span class="function">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
- <span class="function">MongoDB\Driver\Server::executeBulkWrite
MongoDB\Driver\Manager::executeCommand
Execute a database command
说明
final public
MongoDB\Driver\Cursor <span
class="methodname">MongoDB\Driver\Manager::executeCommand (
string $db
, <span
class="type">MongoDB\Driver\Command $command [, <span
class="methodparam">array $options<span
class="initializer"> = 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
| 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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException being thrown. Instead, you should set these two options when you create the transaction with <span class="methodname">MongoDB\Driver\Session::startTransaction.
返回值
Returns MongoDB\Driver\Cursor on success.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used with an associated transaction in combination with a "readConcern" or "writeConcern" option.
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used in combination with an unacknowledged write concern.
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span class="classname">MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws <span class="classname">MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws <span class="classname">MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command, issuing a write command to a secondary).
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.4.4 | MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the "session" option is used in combination with an unacknowledged write concern. |
| PECL mongodb 1.4.0 | The third parameter is now an options array. For backwards compatibility, this paramater will still accept a MongoDB\Driver\ReadPreference object. |
范例
示例 #1 <span class="function">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 <span class="function">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 <span class="classname">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 <span class="classname">MongoDB\Driver\Exception\ExecutionTimeoutException will be thrown.
注释
Note: If a secondary
readPreferenceis used, it is the caller's responsibility to ensure that thecommandcan be executed on a secondary. No validation is done by the driver.
参见
- MongoDB\Driver\Command
- MongoDB\Driver\Cursor
- <span class="function">MongoDB\Driver\Manager::executeReadCommand
- <span class="function">MongoDB\Driver\Manager::executeReadWriteCommand
- <span class="function">MongoDB\Driver\Manager::executeWriteCommand
- <span class="function">MongoDB\Driver\Server::executeCommand
MongoDB\Driver\Manager::executeQuery
Execute a database query
说明
final public
MongoDB\Driver\Cursor <span
class="methodname">MongoDB\Driver\Manager::executeQuery ( <span
class="methodparam">string $namespace
, <span
class="type">MongoDB\Driver\Query $query [, <span
class="methodparam">array $options<span
class="initializer"> = 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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span class="classname">MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws <span class="classname">MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws <span class="classname">MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid query operators).
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.4.0 | The third parameter is now an options array. For backwards compatibility, this paramater will still accept a MongoDB\Driver\ReadPreference object. |
范例
示例 #1 <span class="function">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 <span class="classname">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 <span
class="methodname">MongoDB\Driver\Manager::executeReadCommand (
string $db
, <span
class="type">MongoDB\Driver\Command $command [, <span
class="methodparam">array $options<span
class="initializer"> = 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
| 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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException being thrown. Instead, you should set these two options when you create the transaction with <span class="methodname">MongoDB\Driver\Session::startTransaction.
返回值
Returns MongoDB\Driver\Cursor on success.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used with an associated transaction in combination with a "readConcern" or "writeConcern" option.
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span class="classname">MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws <span class="classname">MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws <span class="classname">MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command).
参见
- MongoDB\Driver\Command
- MongoDB\Driver\Cursor
- <span class="function">MongoDB\Driver\Manager::executeCommand
- <span class="function">MongoDB\Driver\Manager::executeReadWriteCommand
- <span class="function">MongoDB\Driver\Manager::executeWriteCommand
- <span class="function">MongoDB\Driver\Server::executeReadCommand
MongoDB\Driver\Manager::executeReadWriteCommand
Execute a database command that reads and writes
说明
final public
MongoDB\Driver\Cursor <span
class="methodname">MongoDB\Driver\Manager::executeReadWriteCommand
( string
$db , <span
class="type">MongoDB\Driver\Command $command [, <span
class="methodparam">array $options<span
class="initializer"> = array() ] )
Executes the command on the primary server.
This method will apply logic that is specific to commands that read and write (e.g. » aggregate) 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
| 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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException being thrown. Instead, you should set these two options when you create the transaction with <span class="methodname">MongoDB\Driver\Session::startTransaction.
返回值
Returns MongoDB\Driver\Cursor on success.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used with an associated transaction in combination with a "readConcern" or "writeConcern" option.
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used in combination with an unacknowledged write concern.
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span class="classname">MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws <span class="classname">MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws <span class="classname">MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command).
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.4.4 | MongoDB\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
- <span class="function">MongoDB\Driver\Manager::executeCommand
- <span class="function">MongoDB\Driver\Manager::executeReadCommand
- <span class="function">MongoDB\Driver\Manager::executeWriteCommand
- <span class="function">MongoDB\Driver\Server::executeReadWriteCommand
MongoDB\Driver\Manager::executeWriteCommand
Execute a database command that writes
说明
final public
MongoDB\Driver\Cursor <span
class="methodname">MongoDB\Driver\Manager::executeWriteCommand
( string
$db , <span
class="type">MongoDB\Driver\Command $command [, <span
class="methodparam">array $options<span
class="initializer"> = 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 <span 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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException being thrown. Instead, you should set these two options when you create the transaction with <span class="methodname">MongoDB\Driver\Session::startTransaction.
返回值
Returns MongoDB\Driver\Cursor on success.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used with an associated transaction in combination with a "readConcern" or "writeConcern" option.
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used in combination with an unacknowledged write concern.
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span class="classname">MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws <span class="classname">MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws <span class="classname">MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command).
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.4.4 | MongoDB\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
- <span class="function">MongoDB\Driver\Manager::executeCommand
- <span class="function">MongoDB\Driver\Manager::executeReadCommand
- <span class="function">MongoDB\Driver\Manager::executeReadWriteCommand
- <span class="function">MongoDB\Driver\Server::executeWriteCommand
MongoDB\Driver\Manager::getReadConcern
Return the ReadConcern for the Manager
说明
final public MongoDB\Driver\ReadConcern <span class="methodname">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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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
- <span class="function">MongoDB\Driver\Manager::__construct
MongoDB\Driver\Manager::getReadPreference
Return the ReadPreference for the Manager
说明
final public MongoDB\Driver\ReadPreference <span class="methodname">MongoDB\Driver\Manager::getReadPreference ( void )
Returns the <span class="classname">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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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
- <span class="function">MongoDB\Driver\Manager::__construct
MongoDB\Driver\Manager::getServers
Return the servers to which this manager is connected
说明
final public array <span class="methodname">MongoDB\Driver\Manager::getServers ( <span class="methodparam">void )
Returns an array of <span class="classname">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 <span class="type">array if called before executing an operation on the MongoDB\Driver\Manager.
参数
此函数没有参数。
返回值
Returns an array of <span class="classname">MongoDB\Driver\Server instances to which this manager is connected.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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 <span class="methodname">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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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
- <span class="function">MongoDB\Driver\Manager::__construct
MongoDB\Driver\Manager::selectServer
Select a server matching a read preference
说明
final public
MongoDB\Driver\Server <span
class="methodname">MongoDB\Driver\Manager::selectServer ( <span
class="methodparam"><span
class="type">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 <span 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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span class="classname">MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws <span class="classname">MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws <span class="classname">MongoDB\Driver\Exception\RuntimeException if a server matching the read preference could not be found.
参见
- MongoDB\Driver\Server
- MongoDB\Driver\Manager::getServers
- » Server Selection Specification
MongoDB\Driver\Manager::startSession
Start a new client session for use with this client
说明
final public
MongoDB\Driver\Session <span
class="methodname">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 <span class="classname">MongoDB\Driver\Session can only be used with the MongoDB\Driver\Manager from which it was created.
参数
options
| Option | Type | Description | Default | |||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| causalConsistency | bool | Configure causal consistency in a session. If 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.
This option is available in MongoDB 4.0+. |
[] |
返回值
Returns a MongoDB\Driver\Session.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span class="classname">MongoDB\Driver\Exception\RuntimeException if the session could not be created (e.g. libmongoc does not support crypto).
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.6.0 | The "maxCommitTimeMS" option was added to "defaultTransactionOptions". |
| PECL mongodb 1.5.0 | The "defaultTransactionOptions" option was added. |
参见
- MongoDB\Driver\Session
- » Casual Consistency in the MongoDB manual
简介
The MongoDB\Driver\Command class is a value object that represents a database command.
To provide “Command Helpers” the <span class="classname">MongoDB\Driver\Command object should be composed.
类摘要
MongoDB\Driver\Command
final class MongoDB\Driver\Command {
/* 方法 */
final public
__construct ( <span
class="methodparam"><span
class="type">arrayobject
$document [, <span
class="type">array $commandOptions ] )
}
范例
示例 #1 Composing <span class="classname">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
( <span
class="type">arrayobject
$document [, <span
class="type">array $commandOptions ] )
Constructs a new <span class="classname">MongoDB\Driver\Command, which is an immutable value object that represents a database command. The command may then be executed with <span class="methodname">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 <span
class="classname">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.
| Option | Type | Description |
|---|---|---|
| maxAwaitTimeMS | int | 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 commands that return a tailable cursor (e.g. » Change Streams). |
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.4.0 | Added a second commandOptions argument, which supports the "maxAwaitTimeMS" option. |
范例
示例 #1 <span class="function">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 <span class="function">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
参见
- <span class="methodname">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 ( <span
class="methodparam"><span
class="type">arrayobject
$filter [, <span
class="type">array $queryOptions ] )
}
MongoDB\Driver\Query::__construct
Create a new Query
说明
final public
MongoDB\Driver\Query::__construct (
<span
class="type">arrayobject
$filter [, <span
class="type">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 <span class="methodname">MongoDB\Driver\Manager::executeQuery.
参数
filter (arrayobject)
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
| Option | Type | Description |
|---|---|---|
| allowDiskUse | bool | Allows MongoDB to use temporary disk files to store data exceeding the 100 megabyte system memory limit while processing a blocking sort operation. |
| allowPartialResults | bool | 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 | bool | 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 | int | 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 | arrayobject | » 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 | bool | 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 | bool | If 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 | stringarrayobject | 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 | int | 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 |
| max | arrayobject | The exclusive upper bound for a specific index. Falls back to the deprecated "$max" modifier if not specified. |
| maxAwaitTimeMS | int | 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 | int |
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 | int | 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 | arrayobject | 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 | bool | Prevents the server from timing out idle cursors after an inactivity period (10 minutes). |
| oplogReplay | bool | Internal use for replica sets. To use oplogReplay, you must include the following condition in the filter:
|
| projection | arrayobject | 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 | bool | If Falls back to the deprecated "$returnKey" modifier if not specified. |
| showRecordId | bool | Determines whether to return the record identifier for each document. If Falls back to the deprecated "$showDiskLoc" modifier if not specified. |
| singleBatch | bool | Determines whether to close the cursor after the first batch. Defaults to false. |
| skip | int | Number of documents to skip. Defaults to 0. |
| slaveOk | bool | Allow query of replica set secondaries |
| snapshot | bool |
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 | arrayobject | The sort specification for the ordering of the results. Falls back to the deprecated "$orderby" modifier if not specified. |
| tailable | bool | Returns a tailable cursor for a capped collection. |
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.8.0 | Added the "allowDiskUse" option. The "oplogReplay" option is deprecated. |
| PECL mongodb 1.5.0 | The "maxScan" and "snapshot" options are deprecated. |
| PECL mongodb 1.3.0 | Added the "maxAwaitTimeMS" option. |
| PECL mongodb 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. |
| PECL mongodb 1.1.0 | Added the "readConcern" option. |
范例
示例 #1 <span class="function">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);
}
?>
参见
- <span class="methodname">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 <span class="methodname">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 <span class="oointerface">implements <span class="interfacename">Countable {
/* 方法 */
public <span
class="methodname">__construct ([ <span
class="methodparam">array $options ]
)
public int <span class="methodname">count ( void )
public void
delete ( <span
class="type">array<span
class="type">object $filter [, <span
class="methodparam">array
$deleteOptions ] )
public mixed
insert ( <span
class="type">array<span
class="type">object $document )
public void
update ( <span
class="type">array<span
class="type">object $filter , <span
class="methodparam"><span
class="type">arrayobject
$newObj [, <span
class="type">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)
参见
- <span class="methodname">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 <span
class="methodname">MongoDB\Driver\BulkWrite::__construct ([
array
$options ] )
Constructs a new <span class="classname">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 <span class="methodname">MongoDB\Driver\Manager::executeBulkWrite.
参数
options (array)
| Option | Type | Description | Default |
|---|---|---|---|
| bypassDocumentValidation | bool | If This option is available in MongoDB 3.2+ and is ignored for older server versions, which do not support document level validation. |
false |
| ordered | bool | 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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.1.0 | Added the "bypassDocumentValidation" option. |
范例
示例 #1 <span class="function">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)
参见
- <span class="methodname">MongoDB\Driver\Manager::executeBulkWrite
- MongoDB\Driver\WriteResult
MongoDB\Driver\BulkWrite::count
Count number of write operations in the bulk
说明
public int <span class="methodname">MongoDB\Driver\BulkWrite::count ( <span class="methodparam">void )
Returns the number of write operations added to the <span class="classname">MongoDB\Driver\BulkWrite object.
参数
此函数没有参数。
返回值
Returns number of write operations added to the <span class="classname">MongoDB\Driver\BulkWrite object.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.2.0 | Returns 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 <span class="function">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 (
<span
class="type">arrayobject
$filter [, <span
class="type">array $deleteOptions ] )
Adds a delete operation to the <span class="classname">MongoDB\Driver\BulkWrite.
参数
filter (arrayobject)
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
| Option | Type | Description | Default |
|---|---|---|---|
| collation | arrayobject | » 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 | stringarrayobject | 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. This option is available in MongoDB 4.4+ and will result in an exception at execution time if specified for an older server version. |
|
| limit | bool | Delete all matching documents (false), or only the first matching document (true) |
false |
返回值
没有返回值。
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.8.0 | Added the "hint" option. |
| PECL mongodb 1.2.0 | Added the "collation" option. |
范例
示例 #1 <span class="function">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);
?>
参见
- <span class="methodname">MongoDB\Driver\Manager::executeBulkWrite
- MongoDB\Driver\WriteResult
MongoDB\Driver\BulkWrite::insert
Add an insert operation to the bulk
说明
public mixed
MongoDB\Driver\BulkWrite::insert (
<span
class="type">arrayobject
$document )
Adds an insert operation to the <span class="classname">MongoDB\Driver\BulkWrite.
参数
document (arrayobject)
A document to insert.
返回值
Returns the _id of the inserted document. If the document did not
have an _id, the <span
class="classname">MongoDB\BSON\ObjectId generated for the
insert will be returned.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.3.0 | The _id of the inserted document is always returned. Previously, the method only returned a value if a MongoDB\BSON\ObjectId was generated. |
范例
示例 #1 <span class="function">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
参见
- <span class="methodname">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 (
<span
class="type">arrayobject
$filter , <span
class="type">arrayobject
$newObj [, <span
class="type">array $updateOptions ] )
Adds an update operation to the <span class="classname">MongoDB\Driver\BulkWrite.
参数
filter (arrayobject)
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 (arrayobject)
A document containing either update operators (e.g. $set), a
replacement document (i.e. only field:value expressions), or an
» aggregation pipeline.
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 | arrayobject | » 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 | stringarrayobject | 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. This option is available in MongoDB 4.2+ and will result in an exception at execution time if specified for an older server version. |
|
| multi | bool | 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 | bool | 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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.7.0 | Added the "hint" option. |
| PECL mongodb 1.6.0 | The 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. |
| PECL mongodb 1.5.0 | Using 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. |
| PECL mongodb 1.4.0 | Added the "arrayFilters" option. |
| PECL mongodb 1.2.0 | Added the "collation" option. |
范例
示例 #1 <span class="function">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);
?>
参见
- <span class="methodname">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 <span class="oointerface">implements <span class="interfacename">MongoDB\BSON\Serializable <span class="oointerface">, Serializable {
/* Constants */
const string
MongoDB\Driver\WriteConcern::MAJORITY =
"majority" ;
/* 方法 */
final public object <span class="methodname">bsonSerialize ( <span class="methodparam">void )
final public
__construct ( <span
class="methodparam"><span
class="type">stringint
$w [, int
$wtimeout [, <span
class="type">bool $journal ]] )
final public bool<span class="type">null <span class="methodname">getJournal ( <span class="methodparam">void )
final public string<span class="type">intnull <span class="methodname">getW ( void )
final public int<span class="type">MongoDB\BSON\Int64 <span class="methodname">getWtimeout ( <span class="methodparam">void )
final public bool isDefault ( void )
final public string <span class="methodname">serialize ( <span class="methodparam">void )
final public
void <span
class="methodname">unserialize ( <span
class="type">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.
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.7.0 | Implements Serializable. |
| PECL mongodb 1.2.0 | Implements MongoDB\BSON\Serializable. |
MongoDB\Driver\WriteConcern::bsonSerialize
Returns an object for BSON serialization
说明
final public object <span class="methodname">MongoDB\Driver\WriteConcern::bsonSerialize ( void )
参数
此函数没有参数。
返回值
Returns an object for serializing the WriteConcern as BSON.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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 <span class="function">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 }
参见
- <span class="methodname">MongoDB\BSON\Serializable::bsonSerialize
- » Write Concern reference
MongoDB\Driver\WriteConcern::__construct
Create a new WriteConcern
说明
final public
<span
class="methodname">MongoDB\Driver\WriteConcern::__construct (
<span
class="type">stringint
$w [, int
$wtimeout [, <span
class="type">bool $journal ]] )
Constructs a new <span class="classname">MongoDB\Driver\WriteConcern, which is an immutable value object.
参数
w
| 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 (<span class="classname">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.
| Value | Description |
|---|---|
| 0 | Block 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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span
class="classname">MongoDB\Driver\Exception\InvalidArgumentException
if
wis invalid orwtimeoutis either negative or greater than the bounds of a signed 32-bit integer.
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.7.0 | The wTimeout parameter now accepts 64-bit values. |
范例
示例 #1 <span class="function">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 bool<span class="type">null <span class="methodname">MongoDB\Driver\WriteConcern::getJournal ( void )
参数
此函数没有参数。
返回值
Returns the WriteConcern's "journal" option.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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<span class="type">intnull <span class="methodname">MongoDB\Driver\WriteConcern::getW ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns the WriteConcern's "w" option.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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<span class="type">MongoDB\BSON\Int64 <span class="methodname">MongoDB\Driver\WriteConcern::getWtimeout ( void )
参数
此函数没有参数。
返回值
Returns the WriteConcern's "wtimeout" option.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.7.0 | On 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 <span class="function">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 <span class="methodname">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 <span class="methodname">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. <span class="methodname">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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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)
参见
- <span class="methodname">MongoDB\Driver\Manager::getWriteConcern
- » Modify Default Write Concern in the MongoDB manual
- » Write Concern reference
MongoDB\Driver\WriteConcern::serialize
Serialize a WriteConcern
说明
final public string <span class="methodname">MongoDB\Driver\WriteConcern::serialize ( void )
参数
此函数没有参数。
返回值
Returns the serialized representation of the <span class="classname">MongoDB\Driver\WriteConcern.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
- <span class="methodname">MongoDB\Driver\WriteConcern::unserialize
- serialize
- Serializing Objects
MongoDB\Driver\WriteConcern::unserialize
Unserialize a WriteConcern
说明
final public
void <span
class="methodname">MongoDB\Driver\WriteConcern::unserialize (
string
$serialized )
参数
serialized
The serialized <span
class="classname">MongoDB\Driver\WriteConcern.
返回值
Returns the unserialized <span class="classname">MongoDB\Driver\WriteConcern.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span
class="classname">MongoDB\Driver\Exception\UnexpectedValueException
if the properties cannot be unserialized (i.e.
serializedwas malformed). - Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).
参见
- <span class="methodname">MongoDB\Driver\WriteConcern::serialize
- unserialize
- Serializing Objects
简介
类摘要
MongoDB\Driver\ReadPreference
final class MongoDB\Driver\ReadPreference <span class="oointerface">implements <span class="interfacename">MongoDB\BSON\Serializable <span class="oointerface">, Serializable {
/* Constants */
const int
MongoDB\Driver\ReadPreference::RP_PRIMARY =
1 ;
const int
MongoDB\Driver\ReadPreference::RP_PRIMARY_PREFERRED <span
class="initializer"> = 5 ;
const int
MongoDB\Driver\ReadPreference::RP_SECONDARY
= 2 ;
const int
MongoDB\Driver\ReadPreference::RP_SECONDARY_PREFERRED <span
class="initializer"> = 6 ;
const int
MongoDB\Driver\ReadPreference::RP_NEAREST =
10 ;
const string
MongoDB\Driver\ReadPreference::PRIMARY =
primary ;
const string
MongoDB\Driver\ReadPreference::PRIMARY_PREFERRED <span
class="initializer"> = primaryPreferred ;
const string
MongoDB\Driver\ReadPreference::SECONDARY =
secondary ;
const string
MongoDB\Driver\ReadPreference::SECONDARY_PREFERRED <span
class="initializer"> = secondaryPreferred ;
const string
MongoDB\Driver\ReadPreference::NEAREST =
nearest ;
const int
MongoDB\Driver\ReadPreference::NO_MAX_STALENESS <span
class="initializer"> = -1 ;
const int
MongoDB\Driver\ReadPreference::SMALLEST_MAX_STALENESS_SECONDS <span
class="initializer"> = 90 ;
/* 方法 */
final public object <span class="methodname">bsonSerialize ( <span class="methodparam">void )
final public
__construct ( <span
class="methodparam"><span
class="type">stringint
$mode [, <span
class="type">array $tagSets =
null [, <span
class="type">array $options =
array() ]] )
final public object<span class="type">null getHedge ( void )
final public int <span class="methodname">getMaxStalenessSeconds ( <span class="methodparam">void )
final public int getMode ( void )
final public string <span class="methodname">getModeString ( <span class="methodparam">void )
final public array <span class="methodname">getTagSets ( <span class="methodparam">void )
final public string <span class="methodname">serialize ( <span class="methodparam">void )
final public
void <span
class="methodname">unserialize ( <span
class="type">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.
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.7.0 | Added the Implements Serializable. |
| PECL mongodb 1.2.0 | Added the Implements MongoDB\BSON\Serializable. |
MongoDB\Driver\ReadPreference::bsonSerialize
Returns an object for BSON serialization
说明
final public object <span class="methodname">MongoDB\Driver\ReadPreference::bsonSerialize ( void )
参数
此函数没有参数。
返回值
Returns an object for serializing the ReadPreference as BSON.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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 <span class="function">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 <span class="function">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 }
参见
- <span class="methodname">MongoDB\BSON\Serializable::bsonSerialize
- » Read Preference reference
MongoDB\Driver\ReadPreference::__construct
Create a new ReadPreference
说明
final public
<span
class="methodname">MongoDB\Driver\ReadPreference::__construct
( <span
class="type">stringint
$mode [, <span
class="type">array $tagSets =
null [, <span
class="type">array $options =
array() ]] )
Constructs a new <span class="classname">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
| Option | Type | Description |
|---|---|---|
| hedge | objectarray | Specifies whether to use » hedged reads, which are supported by MongoDB 4.4+ for sharded queries. Server hedged reads are available for all non-primary read preferences and are enabled by default when using the "nearest" mode. This option allows explicitly enabling server hedged reads for non-primary read preferences by specifying ['enabled' => true], or explicitly disabling server hedged reads for the "nearest" read preference by specifying ['enabled' => false]. |
| maxStalenessSeconds | int | 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 Defaults to This option is not compatible with the |
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span
class="classname">MongoDB\Driver\Exception\InvalidArgumentException
if
modeis invalid. - Throws <span
class="classname">MongoDB\Driver\Exception\InvalidArgumentException
if
tagSetsis provided for a primary read preference or is malformed (i.e. not an array of zero or more documents). - Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException if the "maxStalenessSeconds" option is provided for a primary read preference or is out of range.
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.8.0 | Added the "hedge" option. |
| PECL mongodb 1.3.0 | The mode argument now accepts a string value, which is consistent with the "readPreference" URI option for MongoDB\Driver\Manager::__construct. |
| PECL mongodb 1.2.0 | Added a third options argument, which supports the "maxStalenessSeconds" option. |
范例
示例 #1 <span class="function">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]));
/* Explicitly enable server hedged reads */
var_dump(new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY, null, ['hedge' => ['enabled' => true]]));
?>
以上例程会输出:
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)
}
object(MongoDB\Driver\ReadPreference)#1 (2) {
["mode"]=>
string(9) "secondary"
["hedge"]=>
object(stdClass)#1 (1) {
["enabled"]=>
bool(true)
}
}
参见
MongoDB\Driver\ReadPreference::getHedge
Returns the ReadPreference's "hedge" option
说明
final public object<span class="type">null <span class="methodname">MongoDB\Driver\ReadPreference::getHedge ( void )
参数
此函数没有参数。
返回值
Returns the ReadPreference's "hedge" option.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
MongoDB\Driver\ReadPreference::getMaxStalenessSeconds
Returns the ReadPreference's "maxStalenessSeconds" option
说明
final public int <span class="methodname">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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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 <span class="methodname">MongoDB\Driver\ReadPreference::getMode ( void )
参数
此函数没有参数。
返回值
Returns the ReadPreference's "mode" option.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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)
参见
- <span class="methodname">MongoDB\Driver\ReadPreference::getModeString
- » Read Preference reference
MongoDB\Driver\ReadPreference::getModeString
Returns the ReadPreference's "mode" option as a string
说明
final public string <span class="methodname">MongoDB\Driver\ReadPreference::getModeString ( void )
参数
此函数没有参数。
返回值
Returns the ReadPreference's "mode" option as a string.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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"
参见
- <span class="methodname">MongoDB\Driver\ReadPreference::getMode
- » Read Preference reference
MongoDB\Driver\ReadPreference::getTagSets
Returns the ReadPreference's "tagSets" option
说明
final public array <span class="methodname">MongoDB\Driver\ReadPreference::getTagSets ( void )
参数
此函数没有参数。
返回值
Returns the ReadPreference's "tagSets" option.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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 <span class="methodname">MongoDB\Driver\ReadPreference::serialize ( void )
参数
此函数没有参数。
返回值
Returns the serialized representation of the <span class="classname">MongoDB\Driver\ReadPreference.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
- <span class="methodname">MongoDB\Driver\ReadPreference::unserialize
- serialize
- Serializing Objects
MongoDB\Driver\ReadPreference::unserialize
Unserialize a ReadPreference
说明
final public
void <span
class="methodname">MongoDB\Driver\ReadPreference::unserialize (
string
$serialized )
参数
serialized
The serialized <span
class="classname">MongoDB\Driver\ReadPreference.
返回值
Returns the unserialized <span class="classname">MongoDB\Driver\ReadPreference.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span
class="classname">MongoDB\Driver\Exception\UnexpectedValueException
if the properties cannot be unserialized (i.e.
serializedwas malformed). - Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).
参见
- <span class="methodname">MongoDB\Driver\ReadPreference::serialize
- unserialize
- Serializing Objects
简介
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 <span class="oointerface">implements <span class="interfacename">MongoDB\BSON\Serializable <span class="oointerface">, 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 <span class="methodname">bsonSerialize ( <span class="methodparam">void )
final public
__construct ([ <span
class="methodparam">string $level ]
)
final public string<span class="type">null getLevel ( void )
final public bool isDefault ( void )
final public string <span class="methodname">serialize ( <span class="methodparam">void )
final public
void <span
class="methodname">unserialize ( <span
class="type">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.
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.7.0 | Implements Serializable. |
| PECL mongodb 1.4.0 | Added the |
| PECL mongodb 1.2.0 | Added the Implements MongoDB\BSON\Serializable. |
参见
MongoDB\Driver\ReadConcern::bsonSerialize
Returns an object for BSON serialization
说明
final public object <span class="methodname">MongoDB\Driver\ReadConcern::bsonSerialize ( void )
参数
此函数没有参数。
返回值
Returns an object for serializing the ReadConcern as BSON.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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 <span class="function">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" }
参见
- <span class="methodname">MongoDB\BSON\Serializable::bsonSerialize
- » Read Concern reference
MongoDB\Driver\ReadConcern::__construct
Create a new ReadConcern
说明
final public
<span
class="methodname">MongoDB\Driver\ReadConcern::__construct
([ string
$level ] )
Constructs a new <span class="classname">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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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<span class="type">null <span class="methodname">MongoDB\Driver\ReadConcern::getLevel ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns the ReadConcern's "level" option.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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 <span class="methodname">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 <span class="methodname">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. <span class="methodname">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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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)
参见
- <span class="methodname">MongoDB\Driver\Manager::getReadConcern
- » Read Concern reference
MongoDB\Driver\ReadConcern::serialize
Serialize a ReadConcern
说明
final public string <span class="methodname">MongoDB\Driver\ReadConcern::serialize ( void )
参数
此函数没有参数。
返回值
Returns the serialized representation of the <span class="classname">MongoDB\Driver\ReadConcern.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
- <span class="methodname">MongoDB\Driver\ReadConcern::unserialize
- serialize
- Serializing Objects
MongoDB\Driver\ReadConcern::unserialize
Unserialize a ReadConcern
说明
final public
void <span
class="methodname">MongoDB\Driver\ReadConcern::unserialize (
string
$serialized )
参数
serialized
The serialized <span
class="classname">MongoDB\Driver\ReadConcern.
返回值
Returns the unserialized <span class="classname">MongoDB\Driver\ReadConcern.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span
class="classname">MongoDB\Driver\Exception\UnexpectedValueException
if the properties cannot be unserialized (i.e.
serializedwas malformed). - Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).
参见
- <span class="methodname">MongoDB\Driver\ReadConcern::serialize
- unserialize
- Serializing Objects
简介
The MongoDB\Driver\Cursor class encapsulates the results of a MongoDB command or query and may be returned by <span class="methodname">MongoDB\Driver\Manager::executeCommand or MongoDB\Driver\Manager::executeQuery, respectively.
类摘要
MongoDB\Driver\Cursor
final class MongoDB\Driver\Cursor implements MongoDB\Driver\CursorInterface , <span class="interfacename">Iterator {
/* 方法 */
final <span class="modifier">private <span class="methodname">__construct ( <span class="methodparam">void )
public <span class="type">arrayobject <span class="methodname">current ( <span class="methodparam">void )
final public MongoDB\Driver\CursorId <span class="methodname">getId ( void )
final public MongoDB\Driver\Server <span class="methodname">getServer ( <span class="methodparam">void )
final public bool isDead ( void )
public int <span class="methodname">key ( void )
public void next ( <span class="methodparam">void )
public void rewind ( <span class="methodparam">void )
final public
void <span
class="methodname">setTypeMap ( <span
class="type">array $typemap )
final public array toArray ( void )
public bool valid ( <span class="methodparam">void )
}
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.9.0 | Implements Iterator. |
| PECL mongodb 1.6.0 | Implements MongoDB\Driver\CursorInterface, which extends Traversable. |
范例
示例 #1 Reading a result set
MongoDB\Driver\Manager::executeCommand and <span class="methodname">MongoDB\Driver\Manager::executeQuery both return their result(s) as a <span class="classname">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 <span class="function">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 <span class="function">IteratorIterator::next will block and wait for additional results. <span class="function">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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException if a class in the type map cannot be instantiated or does not implement <span class="interfacename">MongoDB\BSON\Unserializable.
- Throws <span class="classname">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 <span class="modifier">private <span class="methodname">MongoDB\Driver\Cursor::__construct ( <span class="methodparam">void )
MongoDB\Driver\Cursor objects are returned as the result of an executed command or query and cannot be constructed directly.
参数
此函数没有参数。
参见
- <span class="function">MongoDB\Driver\Manager::executeCommand
- MongoDB\Driver\Manager::executeQuery
- <span class="function">MongoDB\Driver\Server::executeCommand
- MongoDB\Driver\Server::executeQuery
MongoDB\Driver\Cursor::current
Returns the current element
说明
public <span class="type">arrayobject <span class="methodname">MongoDB\Driver\Cursor::current ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns the current result document as an array or object, depending on
the cursor's type map. If iteration has not started or the current
position is not valid, null will be returned.
参见
- Iterator::current
MongoDB\Driver\Cursor::getId
Returns the ID for this cursor
说明
final public MongoDB\Driver\CursorId <span class="methodname">MongoDB\Driver\Cursor::getId ( <span class="methodparam">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 <span class="classname">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
- <span class="function">MongoDB\Driver\CursorId::__toString
MongoDB\Driver\Cursor::getServer
Returns the server associated with this cursor
说明
final public MongoDB\Driver\Server <span class="methodname">MongoDB\Driver\Cursor::getServer ( <span class="methodparam">void )
Returns the MongoDB\Driver\Server associated with this cursor. This is the server that executed the <span class="classname">MongoDB\Driver\Query or <span class="classname">MongoDB\Driver\Command.
参数
此函数没有参数。
返回值
Returns the MongoDB\Driver\Server associated with this cursor.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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 <span class="methodname">MongoDB\Driver\Cursor::isDead ( <span class="methodparam">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 <span class="classname">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)
参见
- » Tailable Cursors in the MongoDB manual
- » cursor.isExhausted() in the MongoDB manual
MongoDB\Driver\Cursor::key
Returns the current result's index within the cursor
说明
public int <span class="methodname">MongoDB\Driver\Cursor::key ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
The current result's numeric index within the cursor.
参见
- Iterator::key
MongoDB\Driver\Cursor::next
Advances the cursor to the next result
说明
public void MongoDB\Driver\Cursor::next ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Moves the current position to the next element in the cursor.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span class="classname">MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws <span class="classname">MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
参见
- Iterator::next
MongoDB\Driver\Cursor::rewind
Rewind the cursor to the first result
说明
public void MongoDB\Driver\Cursor::rewind ( <span class="methodparam">void )
If the cursor has advanced beyond its first position, it can no longer be rewound.
参数
此函数没有参数。
返回值
null.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span class="classname">MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws <span class="classname">MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws <span class="classname">MongoDB\Driver\Exception\LogicException if this method is called after the cursor has advanced beyond its first position.
参见
- Iterator::rewind
MongoDB\Driver\Cursor::setTypeMap
Sets a type map to use for BSON unserialization
说明
final public
void <span
class="methodname">MongoDB\Driver\Cursor::setTypeMap ( <span
class="methodparam">array $typemap )
Sets the type map configuration to use when unserializing the BSON results into PHP values.
参数
typeMap (array)
Type map configuration.
返回值
没有返回值。
错误/异常
- Throws <span class="classname">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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException if a class in the type map cannot be instantiated or does not implement <span class="interfacename">MongoDB\BSON\Unserializable.
范例
示例 #1 <span class="function">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 <span class="methodname">MongoDB\Driver\Cursor::toArray ( <span class="methodparam">void )
Iterates the cursor and returns its results in an array. <span class="function">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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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
MongoDB\Driver\Cursor::valid
Checks if the current position in the cursor is valid
说明
public bool MongoDB\Driver\Cursor::valid ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
true if the current cursor position is valid, false
otherwise.
参见
- Iterator::valid
简介
The MongoDB\Driver\CursorID class is a value object that represents a cursor ID. Instances of this class are returned by <span class="function">MongoDB\Driver\Cursor::getId.
类摘要
MongoDB\Driver\CursorId
final class MongoDB\Driver\CursorId <span class="oointerface">implements <span class="interfacename">Serializable {
/* 方法 */
final <span class="modifier">private <span class="methodname">__construct ( <span class="methodparam">void )
final public string <span class="methodname">serialize ( <span class="methodparam">void )
final public string <span class="methodname">__toString ( <span class="methodparam">void )
final public
void <span
class="methodname">unserialize ( <span
class="type">string $serialized )
}
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.7.0 | Implements Serializable. |
MongoDB\Driver\CursorId::__construct
Create a new CursorId (not used)
说明
final <span class="modifier">private <span class="methodname">MongoDB\Driver\CursorId::__construct ( void )
MongoDB\Driver\CursorId objects are returned from <span class="function">MongoDB\Driver\Cursor::getId and cannot be constructed directly.
参数
此函数没有参数。
参见
- MongoDB\Driver\Cursor::getId
MongoDB\Driver\CursorId::serialize
Serialize a CursorId
说明
final public string <span class="methodname">MongoDB\Driver\CursorId::serialize ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns the serialized representation of the <span class="classname">MongoDB\Driver\CursorId.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
- <span class="methodname">MongoDB\Driver\CursorId::unserialize
- serialize
- Serializing Objects
MongoDB\Driver\CursorId::__toString
String representation of the cursor ID
说明
final public string <span class="methodname">MongoDB\Driver\CursorId::__toString ( void )
Returns the string representation of the cursor ID.
参数
此函数没有参数。
返回值
Returns the string representation of the cursor ID.
范例
示例 #1 <span class="function">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 <span
class="methodname">MongoDB\Driver\CursorId::unserialize ( <span
class="methodparam">string
$serialized )
参数
serialized
The serialized MongoDB\Driver\CursorId.
返回值
Returns the unserialized <span class="classname">MongoDB\Driver\CursorId.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span
class="classname">MongoDB\Driver\Exception\UnexpectedValueException
if the properties cannot be unserialized (i.e.
serializedwas malformed). - Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).
参见
- MongoDB\Driver\CursorId::serialize
- unserialize
- Serializing Objects
简介
类摘要
MongoDB\Driver\Server
final class MongoDB\Driver\Server {
/* Constants */
const int
MongoDB\Driver\Server::TYPE_UNKNOWN =
0 ;
const int
MongoDB\Driver\Server::TYPE_STANDALONE =
1 ;
const int
MongoDB\Driver\Server::TYPE_MONGOS =
2 ;
const int
MongoDB\Driver\Server::TYPE_POSSIBLE_PRIMARY <span
class="initializer"> = 3 ;
const int
MongoDB\Driver\Server::TYPE_RS_PRIMARY =
4 ;
const int
MongoDB\Driver\Server::TYPE_RS_SECONDARY =
5 ;
const int
MongoDB\Driver\Server::TYPE_RS_ARBITER =
6 ;
const int
MongoDB\Driver\Server::TYPE_RS_OTHER =
7 ;
const int
MongoDB\Driver\Server::TYPE_RS_GHOST =
8 ;
/* 方法 */
final <span class="modifier">private <span class="methodname">__construct ( <span class="methodparam">void )
final public
MongoDB\Driver\WriteResult <span
class="methodname">executeBulkWrite ( <span
class="methodparam">string $namespace
, <span
class="type">MongoDB\Driver\BulkWrite $bulk [, <span
class="methodparam">array $options<span
class="initializer"> = array() ] )
final public
MongoDB\Driver\Cursor <span
class="methodname">executeCommand ( <span
class="methodparam">string $db ,
<span
class="type">MongoDB\Driver\Command $command [, <span
class="methodparam">array $options<span
class="initializer"> = array() ] )
final public
MongoDB\Driver\Cursor <span
class="methodname">executeQuery ( <span
class="type">string $namespace , <span
class="methodparam">MongoDB\Driver\Query
$query [, <span
class="type">array $options =
array() ] )
final public
MongoDB\Driver\Cursor <span
class="methodname">executeReadCommand ( <span
class="methodparam">string $db ,
<span
class="type">MongoDB\Driver\Command $command [, <span
class="methodparam">array $options<span
class="initializer"> = array() ] )
final public
MongoDB\Driver\Cursor <span
class="methodname">executeReadWriteCommand ( <span
class="methodparam">string $db ,
<span
class="type">MongoDB\Driver\Command $command [, <span
class="methodparam">array $options<span
class="initializer"> = array() ] )
final public
MongoDB\Driver\Cursor <span
class="methodname">executeWriteCommand ( <span
class="methodparam">string $db ,
<span
class="type">MongoDB\Driver\Command $command [, <span
class="methodparam">array $options<span
class="initializer"> = array() ] )
final public string getHost ( void )
final public array getInfo ( void )
final public string <span class="methodname">getLatency ( <span class="methodparam">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 <span class="methodname">isSecondary ( <span class="methodparam">void )
}
预定义常量
MongoDB\Driver\Server::TYPE_UNKNOWN
Unknown server type, returned by <span
class="methodname">MongoDB\Driver\Server::getType.
MongoDB\Driver\Server::TYPE_STANDALONE
Standalone server type, returned by <span
class="methodname">MongoDB\Driver\Server::getType.
MongoDB\Driver\Server::TYPE_MONGOS
Mongos server type, returned by <span
class="methodname">MongoDB\Driver\Server::getType.
MongoDB\Driver\Server::TYPE_POSSIBLE_PRIMARY
Replica set possible primary server type, returned by <span
class="methodname">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 <span
class="methodname">MongoDB\Driver\Server::getType.
MongoDB\Driver\Server::TYPE_RS_SECONDARY
Replica set secondary server type, returned by <span
class="methodname">MongoDB\Driver\Server::getType.
MongoDB\Driver\Server::TYPE_RS_ARBITER
Replica set arbiter server type, returned by <span
class="methodname">MongoDB\Driver\Server::getType.
MongoDB\Driver\Server::TYPE_RS_OTHER
Replica set other server type, returned by <span
class="methodname">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 <span
class="methodname">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 <span class="modifier">private <span class="methodname">MongoDB\Driver\Server::__construct ( <span class="methodparam">void )
MongoDB\Driver\Server objects are created internally by <span class="classname">MongoDB\Driver\Manager when a database connection is established and may be returned by <span class="function">MongoDB\Driver\Manager::getServers and <span class="function">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 <span
class="methodname">MongoDB\Driver\Server::executeBulkWrite (
string
$namespace , <span
class="type">MongoDB\Driver\BulkWrite $bulk [, <span
class="methodparam">array $options<span
class="initializer"> = 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 <span
class="classname">MongoDB\Driver\Exception\InvalidArgumentException
if
bulkdoes not contain any write operations. - Throws <span
class="classname">MongoDB\Driver\Exception\InvalidArgumentException
if
bulkhas already been executed. <span class="classname">MongoDB\Driver\BulkWrite objects may not be executed multiple times. - Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used in combination with an unacknowledged write concern.
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span class="classname">MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws <span class="classname">MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws <span class="classname">MongoDB\Driver\Exception\BulkWriteException on any write failure (e.g. write error, failure to apply a write concern)
- Throws <span class="classname">MongoDB\Driver\Exception\RuntimeException on other errors.
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.4.4 | MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the "session" option is used in combination with an unacknowledged write concern. |
| PECL mongodb 1.4.0 | The third parameter is now an options array. For backwards compatibility, this paramater will still accept a MongoDB\Driver\WriteConcern object. |
| PECL mongodb 1.3.0 | MongoDB\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
- <span class="function">MongoDB\Driver\Manager::executeBulkWrite
MongoDB\Driver\Server::executeCommand
Execute a database command on this server
说明
final public
MongoDB\Driver\Cursor <span
class="methodname">MongoDB\Driver\Server::executeCommand (
string $db
, <span
class="type">MongoDB\Driver\Command $command [, <span
class="methodparam">array $options<span
class="initializer"> = 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
| 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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException being thrown. Instead, you should set these two options when you create the transaction with <span class="methodname">MongoDB\Driver\Session::startTransaction.
返回值
Returns MongoDB\Driver\Cursor on success.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used with an associated transaction in combination with a "readConcern" or "writeConcern" option.
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used in combination with an unacknowledged write concern.
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span class="classname">MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws <span class="classname">MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws <span class="classname">MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command, issuing a write command to a secondary).
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.4.4 | MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the "session" option is used in combination with an unacknowledged write concern. |
| PECL mongodb 1.4.0 | The 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
- <span class="function">MongoDB\Driver\Server::executeReadCommand
- <span class="function">MongoDB\Driver\Server::executeReadWriteCommand
- <span class="function">MongoDB\Driver\Server::executeWriteCommand
- <span class="function">MongoDB\Driver\Manager::executeCommand
MongoDB\Driver\Server::executeQuery
Execute a database query on this server
说明
final public
MongoDB\Driver\Cursor <span
class="methodname">MongoDB\Driver\Server::executeQuery ( <span
class="methodparam">string $namespace
, <span
class="type">MongoDB\Driver\Query $query [, <span
class="methodparam">array $options<span
class="initializer"> = 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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span class="classname">MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws <span class="classname">MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws <span class="classname">MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid query operators).
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.4.0 | The 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 <span
class="methodname">MongoDB\Driver\Server::executeReadCommand (
string $db
, <span
class="type">MongoDB\Driver\Command $command [, <span
class="methodparam">array $options<span
class="initializer"> = 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
| 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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException being thrown. Instead, you should set these two options when you create the transaction with <span class="methodname">MongoDB\Driver\Session::startTransaction.
返回值
Returns MongoDB\Driver\Cursor on success.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used with an associated transaction in combination with a "readConcern" or "writeConcern" option.
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span class="classname">MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws <span class="classname">MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws <span class="classname">MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command).
参见
- MongoDB\Driver\Command
- MongoDB\Driver\Cursor
- <span class="function">MongoDB\Driver\Server::executeCommand
- <span class="function">MongoDB\Driver\Server::executeReadWriteCommand
- <span class="function">MongoDB\Driver\Server::executeWriteCommand
- <span class="function">MongoDB\Driver\Manager::executeReadCommand
MongoDB\Driver\Server::executeReadWriteCommand
Execute a database command that reads and writes on this server
说明
final public
MongoDB\Driver\Cursor <span
class="methodname">MongoDB\Driver\Server::executeReadWriteCommand
( string
$db , <span
class="type">MongoDB\Driver\Command $command [, <span
class="methodparam">array $options<span
class="initializer"> = array() ] )
Executes the command on this server.
This method will apply logic that is specific to commands that read and write (e.g. » aggregate) 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
| 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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException being thrown. Instead, you should set these two options when you create the transaction with <span class="methodname">MongoDB\Driver\Session::startTransaction.
返回值
Returns MongoDB\Driver\Cursor on success.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used with an associated transaction in combination with a "readConcern" or "writeConcern" option.
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used in combination with an unacknowledged write concern.
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span class="classname">MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws <span class="classname">MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws <span class="classname">MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command).
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.4.4 | MongoDB\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
- <span class="function">MongoDB\Driver\Server::executeCommand
- <span class="function">MongoDB\Driver\Server::executeReadCommand
- <span class="function">MongoDB\Driver\Server::executeWriteCommand
- <span class="function">MongoDB\Driver\Manager::executeReadWriteCommand
MongoDB\Driver\Server::executeWriteCommand
Execute a database command that writes on this server
说明
final public
MongoDB\Driver\Cursor <span
class="methodname">MongoDB\Driver\Server::executeWriteCommand (
string $db
, <span
class="type">MongoDB\Driver\Command $command [, <span
class="methodparam">array $options<span
class="initializer"> = 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 <span 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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException being thrown. Instead, you should set these two options when you create the transaction with <span class="methodname">MongoDB\Driver\Session::startTransaction.
返回值
Returns MongoDB\Driver\Cursor on success.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used with an associated transaction in combination with a "readConcern" or "writeConcern" option.
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used in combination with an unacknowledged write concern.
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span class="classname">MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws <span class="classname">MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws <span class="classname">MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command).
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.4.4 | MongoDB\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
- <span class="function">MongoDB\Driver\Server::executeCommand
- <span class="function">MongoDB\Driver\Server::executeReadCommand
- <span class="function">MongoDB\Driver\Server::executeReadWriteCommand
- <span class="function">MongoDB\Driver\Manager::executeWriteCommand
MongoDB\Driver\Server::getHost
Returns the hostname of this server
说明
final public string <span class="methodname">MongoDB\Driver\Server::getHost ( <span class="methodparam">void )
Returns the hostname of this server.
参数
此函数没有参数。
返回值
Returns the hostname of this server.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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 <span class="methodname">MongoDB\Driver\Server::getInfo ( <span class="methodparam">void )
Returns an array of information about this server.
参数
此函数没有参数。
返回值
Returns an array of information about this server.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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 <span class="methodname">MongoDB\Driver\Server::getLatency ( <span class="methodparam">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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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::getInfo
- » Server Discovery and Monitoring Specification
MongoDB\Driver\Server::getPort
Returns the port on which this server is listening
说明
final public int <span class="methodname">MongoDB\Driver\Server::getPort ( <span class="methodparam">void )
Returns the port on which this server is listening.
参数
此函数没有参数。
返回值
Returns the port on which this server is listening.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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 <span class="methodname">MongoDB\Driver\Server::getTags ( <span class="methodparam">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 <span class="classname">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 <span class="methodname">MongoDB\Driver\Server::getType ( <span class="methodparam">void )
Returns an int denoting the type of this server. The value will correlate with a <span class="classname">MongoDB\Driver\Server constant.
参数
此函数没有参数。
返回值
Returns an int denoting the type of this server.
错误/异常
- Throws <span class="classname">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 <span class="methodname">MongoDB\Driver\Server::isArbiter ( <span class="methodparam">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 <span class="classname">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 <span class="methodname">MongoDB\Driver\Server::isHidden ( <span class="methodparam">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 <span class="classname">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 <span class="methodname">MongoDB\Driver\Server::isPassive ( <span class="methodparam">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 <span class="classname">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 <span class="methodname">MongoDB\Driver\Server::isPrimary ( <span class="methodparam">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 <span class="classname">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 <span class="methodname">MongoDB\Driver\Server::isSecondary ( <span class="methodparam">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 <span class="classname">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 <span class="methodname">MongoDB\Driver\WriteResult::getWriteConcernError.
类摘要
MongoDB\Driver\WriteConcernError
final class MongoDB\Driver\WriteConcernError {
/* 方法 */
final public int getCode ( void )
final public object<span class="type">null getInfo ( void )
final public string <span class="methodname">getMessage ( <span class="methodparam">void )
}
MongoDB\Driver\WriteConcernError::getCode
Returns the WriteConcernError's error code
说明
final public int <span class="methodname">MongoDB\Driver\WriteConcernError::getCode ( void )
参数
此函数没有参数。
返回值
Returns the WriteConcernError's error code.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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 metadata document for the WriteConcernError
说明
final public object<span class="type">null <span class="methodname">MongoDB\Driver\WriteConcernError::getInfo ( void )
参数
此函数没有参数。
返回值
Returns the metadata document for the WriteConcernError, or null
if no metadata is available.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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 <span class="methodname">MongoDB\Driver\WriteConcernError::getMessage ( void )
参数
此函数没有参数。
返回值
Returns the WriteConcernError's error message.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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 <span class="methodname">MongoDB\Driver\WriteResult::getWriteErrors.
类摘要
MongoDB\Driver\WriteError
final class MongoDB\Driver\WriteError {
/* 方法 */
final public int getCode ( void )
final public int getIndex ( void )
final public object<span class="type">null getInfo ( void )
final public string <span class="methodname">getMessage ( <span class="methodparam">void )
}
MongoDB\Driver\WriteError::getCode
Returns the WriteError's error code
说明
final public int <span class="methodname">MongoDB\Driver\WriteError::getCode ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns the WriteError's error code.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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 <span class="methodname">MongoDB\Driver\WriteError::getIndex ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns the index of the write operation (from <span class="classname">MongoDB\Driver\BulkWrite) corresponding to this WriteError.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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 metadata document for the WriteError
说明
final public object<span class="type">null <span class="methodname">MongoDB\Driver\WriteError::getInfo ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns the metadata document for the WriteError, or null if no
metadata is available.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
MongoDB\Driver\WriteError::getMessage
Returns the WriteError's error message
说明
final public string <span class="methodname">MongoDB\Driver\WriteError::getMessage ( void )
参数
此函数没有参数。
返回值
Returns the WriteError's error message.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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 <span class="classname">MongoDB\Driver\BulkWrite and may be returned by <span class="methodname">MongoDB\Driver\Manager::executeBulkWrite.
类摘要
MongoDB\Driver\WriteResult
final class MongoDB\Driver\WriteResult {
/* 方法 */
final public int<span class="type">null <span class="methodname">getDeletedCount ( <span class="methodparam">void )
final public int<span class="type">null <span class="methodname">getInsertedCount ( <span class="methodparam">void )
final public int<span class="type">null <span class="methodname">getMatchedCount ( <span class="methodparam">void )
final public int<span class="type">null <span class="methodname">getModifiedCount ( <span class="methodparam">void )
final public MongoDB\Driver\Server <span class="methodname">getServer ( <span class="methodparam">void )
final public int<span class="type">null <span class="methodname">getUpsertedCount ( <span class="methodparam">void )
final public array <span class="methodname">getUpsertedIds ( <span class="methodparam">void )
final public <span class="type">MongoDB\Driver\WriteConcernError<span class="type">null <span class="methodname">getWriteConcernError ( <span class="methodparam">void )
final public array <span class="methodname">getWriteErrors ( <span class="methodparam">void )
final public bool <span class="methodname">isAcknowledged ( <span class="methodparam">void )
}
MongoDB\Driver\WriteResult::getDeletedCount
Returns the number of documents deleted
说明
final public int<span class="type">null <span class="methodname">MongoDB\Driver\WriteResult::getDeletedCount ( void )
参数
此函数没有参数。
返回值
Returns the number of documents deleted, or null if the write was
not acknowledged.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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)
参见
- <span class="methodname">MongoDB\Driver\WriteResult::isAcknowledged
MongoDB\Driver\WriteResult::getInsertedCount
Returns the number of documents inserted (excluding upserts)
说明
final public int<span class="type">null <span class="methodname">MongoDB\Driver\WriteResult::getInsertedCount ( void )
参数
此函数没有参数。
返回值
Returns the number of documents inserted (excluding upserts), or
null if the write was not acknowledged.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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)
参见
- <span class="methodname">MongoDB\Driver\WriteResult::isAcknowledged
MongoDB\Driver\WriteResult::getMatchedCount
Returns the number of documents selected for update
说明
final public int<span class="type">null <span class="methodname">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 <span class="methodname">MongoDB\Driver\WriteResult::getModifiedCount.
参数
此函数没有参数。
返回值
Returns the number of documents selected for update, or null if
the write was not acknowledged.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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)
参见
- <span class="methodname">MongoDB\Driver\WriteResult::getModifiedCount
- <span class="methodname">MongoDB\Driver\WriteResult::isAcknowledged
MongoDB\Driver\WriteResult::getModifiedCount
Returns the number of existing documents updated
说明
final public int<span class="type">null <span class="methodname">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 <span class="methodname">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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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)
参见
- <span class="methodname">MongoDB\Driver\WriteResult::getMatchedCount
- <span class="methodname">MongoDB\Driver\WriteResult::isAcknowledged
MongoDB\Driver\WriteResult::getServer
Returns the server associated with this write result
说明
final public MongoDB\Driver\Server <span class="methodname">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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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 int<span class="type">null <span class="methodname">MongoDB\Driver\WriteResult::getUpsertedCount ( void )
参数
此函数没有参数。
返回值
Returns the number of documents inserted by an upsert.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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)
参见
- <span class="methodname">MongoDB\Driver\WriteResult::getUpsertedIds
- <span class="methodname">MongoDB\Driver\WriteResult::isAcknowledged
MongoDB\Driver\WriteResult::getUpsertedIds
Returns an array of identifiers for upserted documents
说明
final public array <span class="methodname">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 <span class="classname">MongoDB\Driver\BulkWrite) responsible for the upsert.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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"
}
}
参见
- <span class="methodname">MongoDB\Driver\WriteResult::getUpsertedCount
- <span class="methodname">MongoDB\Driver\WriteResult::isAcknowledged
MongoDB\Driver\WriteResult::getWriteConcernError
Returns any write concern error that occurred
说明
final public <span class="type">MongoDB\Driver\WriteConcernError<span class="type">null <span class="methodname">MongoDB\Driver\WriteResult::getWriteConcernError ( void )
参数
此函数没有参数。
返回值
Returns a <span
class="classname">MongoDB\Driver\WriteConcernError if a write
concern error was encountered during the write operation, and null
otherwise.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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\WriteConcern
- » Write Concern reference
MongoDB\Driver\WriteResult::getWriteErrors
Returns any write errors that occurred
说明
final public array <span class="methodname">MongoDB\Driver\WriteResult::getWriteErrors ( void )
参数
此函数没有参数。
返回值
Returns an array of <span class="classname">MongoDB\Driver\WriteError objects for any write errors encountered during the write operation. The array will be empty if no write errors occurred.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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 <span class="function">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 <span class="methodname">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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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 <span class="function">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)
参见
- MongoDB\Driver\WriteConcern
- » Write Concern reference
BSON type classes and serialization functions
目录
- 函数
- MongoDB\BSON\fromJSON — Returns the BSON representation of a JSON value
- MongoDB\BSON\fromPHP — Returns the BSON representation of a PHP value
- MongoDB\BSON\toCanonicalExtendedJSON — Returns the Canonical Extended JSON representation of a BSON value
- MongoDB\BSON\toJSON — Returns the Legacy Extended JSON representation of a BSON value
- MongoDB\BSON\toPHP — Returns the PHP representation of a BSON value
- MongoDB\BSON\toRelaxedExtendedJSON — Returns the Relaxed Extended JSON representation of a BSON value
- MongoDB\BSON\Binary — The
MongoDB\BSON\Binary class
- MongoDB\BSON\Binary::__construct — Construct a new Binary
- MongoDB\BSON\Binary::getData — Returns the Binary's data
- MongoDB\BSON\Binary::getType — Returns the Binary's type
- MongoDB\BSON\Binary::jsonSerialize — Returns a representation that can be converted to JSON
- MongoDB\BSON\Binary::serialize — Serialize a Binary
- MongoDB\BSON\Binary::__toString — Returns the Binary's data
- MongoDB\BSON\Binary::unserialize — Unserialize a Binary
- MongoDB\BSON\Decimal128
— The MongoDB\BSON\Decimal128 class
- MongoDB\BSON\Decimal128::__construct — Construct a new Decimal128
- MongoDB\BSON\Decimal128::jsonSerialize — Returns a representation that can be converted to JSON
- MongoDB\BSON\Decimal128::serialize — Serialize a Decimal128
- MongoDB\BSON\Decimal128::__toString — Returns the string representation of this Decimal128
- MongoDB\BSON\Decimal128::unserialize — Unserialize a Decimal128
- MongoDB\BSON\Javascript
— The MongoDB\BSON\Javascript class
- MongoDB\BSON\Javascript::__construct — Construct a new Javascript
- MongoDB\BSON\Javascript::getCode — Returns the Javascript's code
- MongoDB\BSON\Javascript::getScope — Returns the Javascript's scope document
- MongoDB\BSON\Javascript::jsonSerialize — Returns a representation that can be converted to JSON
- MongoDB\BSON\Javascript::serialize — Serialize a Javascript
- MongoDB\BSON\Javascript::__toString — Returns the Javascript's code
- MongoDB\BSON\Javascript::unserialize — Unserialize a Javascript
- MongoDB\BSON\MaxKey — The
MongoDB\BSON\MaxKey class
- MongoDB\BSON\MaxKey::__construct — Construct a new MaxKey
- MongoDB\BSON\MaxKey::jsonSerialize — Returns a representation that can be converted to JSON
- MongoDB\BSON\MaxKey::serialize — Serialize a MaxKey
- MongoDB\BSON\MaxKey::unserialize — Unserialize a MaxKey
- MongoDB\BSON\MinKey — The
MongoDB\BSON\MinKey class
- MongoDB\BSON\MinKey::__construct — Construct a new MinKey
- MongoDB\BSON\MinKey::jsonSerialize — Returns a representation that can be converted to JSON
- MongoDB\BSON\MinKey::serialize — Serialize a MinKey
- MongoDB\BSON\MinKey::unserialize — Unserialize a MinKey
- MongoDB\BSON\ObjectId —
The MongoDB\BSON\ObjectId class
- MongoDB\BSON\ObjectId::__construct — Construct a new ObjectId
- MongoDB\BSON\ObjectId::getTimestamp — Returns the timestamp component of this ObjectId
- MongoDB\BSON\ObjectId::jsonSerialize — Returns a representation that can be converted to JSON
- MongoDB\BSON\ObjectId::serialize — Serialize an ObjectId
- MongoDB\BSON\ObjectId::__toString — Returns the hexidecimal representation of this ObjectId
- MongoDB\BSON\ObjectId::unserialize — Unserialize an ObjectId
- MongoDB\BSON\Regex — The
MongoDB\BSON\Regex class
- MongoDB\BSON\Regex::__construct — Construct a new Regex
- MongoDB\BSON\Regex::getFlags — Returns the Regex's flags
- MongoDB\BSON\Regex::getPattern — Returns the Regex's pattern
- MongoDB\BSON\Regex::jsonSerialize — Returns a representation that can be converted to JSON
- MongoDB\BSON\Regex::serialize — Serialize a Regex
- MongoDB\BSON\Regex::__toString — Returns the string representation of this Regex
- MongoDB\BSON\Regex::unserialize — Unserialize a Regex
- MongoDB\BSON\Timestamp
— The MongoDB\BSON\Timestamp class
- MongoDB\BSON\Timestamp::__construct — Construct a new Timestamp
- MongoDB\BSON\Timestamp::getIncrement — Returns the increment component of this Timestamp
- MongoDB\BSON\Timestamp::getTimestamp — Returns the timestamp component of this Timestamp
- MongoDB\BSON\Timestamp::jsonSerialize — Returns a representation that can be converted to JSON
- MongoDB\BSON\Timestamp::serialize — Serialize a Timestamp
- MongoDB\BSON\Timestamp::__toString — Returns the string representation of this Timestamp
- MongoDB\BSON\Timestamp::unserialize — Unserialize a Timestamp
- MongoDB\BSON\UTCDateTime
— The MongoDB\BSON\UTCDateTime class
- MongoDB\BSON\UTCDateTime::__construct — Construct a new UTCDateTime
- MongoDB\BSON\UTCDateTime::jsonSerialize — Returns a representation that can be converted to JSON
- MongoDB\BSON\UTCDateTime::serialize — Serialize a UTCDateTime
- MongoDB\BSON\UTCDateTime::toDateTime — Returns the DateTime representation of this UTCDateTime
- MongoDB\BSON\UTCDateTime::__toString — Returns the string representation of this UTCDateTime
- MongoDB\BSON\UTCDateTime::unserialize — Unserialize a UTCDateTime
- MongoDB\BSON\Type — The MongoDB\BSON\Type interface
- MongoDB\BSON\Persistable — The MongoDB\BSON\Persistable interface
- MongoDB\BSON\Serializable
— The MongoDB\BSON\Serializable interface
- MongoDB\BSON\Serializable::bsonSerialize — Provides an array or document to serialize as BSON
- MongoDB\BSON\Unserializable
— The MongoDB\BSON\Unserializable interface
- MongoDB\BSON\Unserializable::bsonUnserialize — Constructs the object from a BSON array or document
- MongoDB\BSON\BinaryInterface
— The MongoDB\BSON\BinaryInterface interface
- MongoDB\BSON\BinaryInterface::getData — Returns the BinaryInterface's data
- MongoDB\BSON\BinaryInterface::getType — Returns the BinaryInterface's type
- MongoDB\BSON\BinaryInterface::__toString — Returns the BinaryInterface's data
- MongoDB\BSON\Decimal128Interface
— The MongoDB\BSON\Decimal128Interface interface
- MongoDB\BSON\Decimal128Interface::__toString — Returns the string representation of this Decimal128Interface
- MongoDB\BSON\JavascriptInterface
— The MongoDB\BSON\JavascriptInterface interface
- MongoDB\BSON\JavascriptInterface::getCode — Returns the JavascriptInterface's code
- MongoDB\BSON\JavascriptInterface::getScope — Returns the JavascriptInterface's scope document
- MongoDB\BSON\JavascriptInterface::__toString — Returns the JavascriptInterface's code
- MongoDB\BSON\MaxKeyInterface — The MongoDB\BSON\MaxKeyInterface interface
- MongoDB\BSON\MinKeyInterface — The MongoDB\BSON\MinKeyInterface interface
- MongoDB\BSON\ObjectIdInterface
— The MongoDB\BSON\ObjectIdInterface interface
- MongoDB\BSON\ObjectIdInterface::getTimestamp — Returns the timestamp component of this ObjectIdInterface
- MongoDB\BSON\ObjectIdInterface::__toString — Returns the hexidecimal representation of this ObjectIdInterface
- MongoDB\BSON\RegexInterface
— The MongoDB\BSON\RegexInterface interface
- MongoDB\BSON\RegexInterface::getFlags — Returns the RegexInterface's flags
- MongoDB\BSON\RegexInterface::getPattern — Returns the RegexInterface's pattern
- MongoDB\BSON\RegexInterface::__toString — Returns the string representation of this RegexInterface
- MongoDB\BSON\TimestampInterface
— The MongoDB\BSON\TimestampInterface interface
- MongoDB\BSON\TimestampInterface::getIncrement — Returns the increment component of this TimestampInterface
- MongoDB\BSON\TimestampInterface::getTimestamp — Returns the timestamp component of this TimestampInterface
- MongoDB\BSON\TimestampInterface::__toString — Returns the string representation of this TimestampInterface
- MongoDB\BSON\UTCDateTimeInterface
— The MongoDB\BSON\UTCDateTimeInterface interface
- MongoDB\BSON\UTCDateTimeInterface::toDateTime — Returns the DateTime representation of this UTCDateTimeInterface
- MongoDB\BSON\UTCDateTimeInterface::__toString — Returns the string representation of this UTCDateTimeInterface
- MongoDB\BSON\DBPointer
— The MongoDB\BSON\DBPointer class (deprecated)
- MongoDB\BSON\DBPointer::__construct — Construct a new DBPointer (unused)
- MongoDB\BSON\DBPointer::jsonSerialize — Returns a representation that can be converted to JSON
- MongoDB\BSON\DBPointer::serialize — Serialize a DBPointer
- MongoDB\BSON\DBPointer::__toString — Returns an empty string
- MongoDB\BSON\DBPointer::unserialize — Unserialize a DBPointer
- MongoDB\BSON\Int64 — The
MongoDB\BSON\Int64 class
- MongoDB\BSON\Int64::__construct — Construct a new Int64 (unused)
- MongoDB\BSON\Int64::jsonSerialize — Returns a representation that can be converted to JSON
- MongoDB\BSON\Int64::serialize — Serialize an Int64
- MongoDB\BSON\Int64::__toString — Returns the string representation of this Int64
- MongoDB\BSON\Int64::unserialize — Unserialize an Int64
- MongoDB\BSON\Symbol — The
MongoDB\BSON\Symbol class (deprecated)
- MongoDB\BSON\Symbol::__construct — Construct a new Symbol (unused)
- MongoDB\BSON\Symbol::jsonSerialize — Returns a representation that can be converted to JSON
- MongoDB\BSON\Symbol::serialize — Serialize a Symbol
- MongoDB\BSON\Symbol::__toString — Returns the Symbol as a string
- MongoDB\BSON\Symbol::unserialize — Unserialize a Symbol
- MongoDB\BSON\Undefined
— The MongoDB\BSON\Undefined class (deprecated)
- MongoDB\BSON\Undefined::__construct — Construct a new Undefined (unused)
- MongoDB\BSON\Undefined::jsonSerialize — Returns a representation that can be converted to JSON
- MongoDB\BSON\Undefined::serialize — Serialize a Undefined
- MongoDB\BSON\Undefined::__toString — Returns an empty string
- MongoDB\BSON\Undefined::unserialize — Unserialize a Undefined
MongoDB\BSON\fromJSON
Returns the BSON representation of a JSON value
说明
string <span
class="methodname">MongoDB\BSON\fromJSON ( <span
class="methodparam">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 <span class="classname">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\toJSON
- » MongoDB Extended JSON
- » MongoDB BSON
MongoDB\BSON\fromPHP
Returns the BSON representation of a PHP value
说明
string <span
class="methodname">MongoDB\BSON\fromPHP ( <span
class="methodparam"><span
class="type">arrayobject
$value )
Serializes a PHP array or object (e.g. document) to its » BSON representation. The returned binary string will describe a BSON document.
参数
value (arrayobject)
PHP value to be serialized.
返回值
The serialized BSON document as a binary string.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\UnexpectedValueException if the PHP value cannot be converted to BSON. Possible reasons include, but are not limited to, encountering an unexpected <span class="interfacename">MongoDB\BSON\Type instance or <span class="function">MongoDB\BSON\Serializable::bsonSerialize failing to return an array or <span class="classname">stdClass.
范例
示例 #1 MongoDB\BSON\fromPHP example
<?php
$bson = MongoDB\BSON\fromPHP(['foo' => 1]);
echo bin2hex($bson), "\n";
?>
以上例程会输出:
0e00000010666f6f000100000000cat
参见
- MongoDB\BSON\toPHP
- » MongoDB BSON
MongoDB\BSON\toCanonicalExtendedJSON
Returns the Canonical Extended JSON representation of a BSON value
说明
string <span
class="methodname">MongoDB\BSON\toCanonicalExtendedJSON ( <span
class="methodparam">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 <span class="classname">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 <span class="function">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\fromJSON
- MongoDB\BSON\toRelaxedExtendedJSON
- » Extended JSON Specification
- » MongoDB BSON
MongoDB\BSON\toJSON
Returns the Legacy Extended JSON representation of a BSON value
说明
string <span
class="methodname">MongoDB\BSON\toJSON ( <span
class="methodparam">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 <span 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 <span
class="function">MongoDB\BSON\toCanonicalExtendedJSON or <span
class="function">MongoDB\BSON\toRelaxedExtendedJSON.
参数
bson (string)
BSON value to be converted.
返回值
The converted JSON value.
错误/异常
- Throws <span class="classname">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\fromJSON
- MongoDB\BSON\toCanonicalExtendedJSON
- MongoDB\BSON\toRelaxedExtendedJSON
- » MongoDB Extended JSON
- » MongoDB BSON
MongoDB\BSON\toPHP
Returns the PHP representation of a BSON value
说明
array<span
class="type">object <span
class="methodname">MongoDB\BSON\toPHP ( <span
class="methodparam">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, <span class="classname">MongoDB\BSON\Symbol, and <span class="classname">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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException if a class in the type map cannot be instantiated or does not implement <span class="interfacename">MongoDB\BSON\Unserializable.
- Throws <span class="classname">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.
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.4.0 | If 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. |
| PECL mongodb 1.3.2 | MongoDB\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). |
| PECL mongodb 1.3.0 | MongoDB\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\fromPHP
- » MongoDB BSON
MongoDB\BSON\toRelaxedExtendedJSON
Returns the Relaxed Extended JSON representation of a BSON value
说明
string <span
class="methodname">MongoDB\BSON\toRelaxedExtendedJSON ( <span
class="methodparam">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 <span class="classname">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 <span class="function">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 } }
参见
- MongoDB\BSON\fromJSON
- MongoDB\BSON\toCanonicalExtendedJSON
- » Extended JSON
- » MongoDB BSON
目录
- MongoDB\BSON\fromJSON — Returns the BSON representation of a JSON value
- MongoDB\BSON\fromPHP — Returns the BSON representation of a PHP value
- MongoDB\BSON\toCanonicalExtendedJSON — Returns the Canonical Extended JSON representation of a BSON value
- MongoDB\BSON\toJSON — Returns the Legacy Extended JSON representation of a BSON value
- MongoDB\BSON\toPHP — Returns the PHP representation of a BSON value
- MongoDB\BSON\toRelaxedExtendedJSON — Returns the Relaxed Extended JSON representation of a BSON value
简介
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 , <span class="interfacename">MongoDB\BSON\Type <span class="oointerface">, Serializable , <span class="interfacename">JsonSerializable {
/* Constants */
const int
MongoDB\BSON\Binary::TYPE_GENERIC =
0 ;
const int
MongoDB\BSON\Binary::TYPE_FUNCTION =
1 ;
const int
MongoDB\BSON\Binary::TYPE_OLD_BINARY =
2 ;
const int
MongoDB\BSON\Binary::TYPE_OLD_UUID =
3 ;
const int
MongoDB\BSON\Binary::TYPE_UUID = 4 ;
const int
MongoDB\BSON\Binary::TYPE_MD5 = 5 ;
const int
MongoDB\BSON\Binary::TYPE_ENCRYPTED =
6 ;
const int
MongoDB\BSON\Binary::TYPE_USER_DEFINED =
128 ;
/* 方法 */
final public
__construct ( <span
class="methodparam">string $data ,
int $type )
final public string getData ( void )
final public int getType ( void )
final public mixed <span class="methodname">jsonSerialize ( <span class="methodparam">void )
final public string <span class="methodname">serialize ( <span class="methodparam">void )
final public string <span class="methodname">__toString ( <span class="methodparam">void )
final public
void <span
class="methodname">unserialize ( <span
class="type">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.
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.3.0 | Implements MongoDB\BSON\BinaryInterface. |
| PECL mongodb 1.2.0 | Implements 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 (int)
Unsigned 8-bit integer denoting the data's type.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span
class="classname">MongoDB\Driver\Exception\InvalidArgumentException
if
typeis not an unsigned 8-bit integer. - Throws <span
class="classname">MongoDB\Driver\Exception\InvalidArgumentException
if
typeisMongoDB\BSON\Binary::TYPE_UUIDorMongoDB\BSON\Binary::TYPE_OLD_UUIDanddatais not exactly 16 bytes in length.
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.3.0 | MongoDB\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. |
| PECL mongodb 1.1.3 | MongoDB\Driver\Exception\InvalidArgumentException is thrown if type is not an unsigned 8-bit integer. |
范例
示例 #1 <span class="function">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 <span class="methodname">MongoDB\BSON\Binary::getData ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns the Binary's data.
错误/异常
- Throws <span class="classname">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 <span class="methodname">MongoDB\BSON\Binary::getType ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns the Binary's type.
错误/异常
- Throws <span class="classname">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 <span class="methodname">MongoDB\BSON\Binary::jsonSerialize ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns data which can be serialized by <span class="function">json_encode to produce an extended JSON representation of the <span class="classname">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 <span class="function">MongoDB\BSON\toRelaxedExtendedJSON and <span class="function">MongoDB\BSON\toCanonicalExtendedJSON, respectively.
错误/异常
- Throws <span class="classname">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 <span class="methodname">MongoDB\BSON\Binary::serialize ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns the serialized representation of the <span class="classname">MongoDB\BSON\Binary.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
- MongoDB\BSON\Binary::unserialize
- serialize
- Serializing Objects
MongoDB\BSON\Binary::__toString
Returns the Binary's data
说明
final public string <span class="methodname">MongoDB\BSON\Binary::__toString ( <span class="methodparam">void )
此方法是该方法的别名: <span class="methodname">MongoDB\BSON\Binary::getData.
参数
此函数没有参数。
返回值
Returns the Binary's data.
范例
示例 #1 <span class="function">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::getData
- » BSON Types
MongoDB\BSON\Binary::unserialize
Unserialize a Binary
说明
final public
void <span
class="methodname">MongoDB\BSON\Binary::unserialize ( <span
class="methodparam">string
$serialized )
参数
serialized
The serialized MongoDB\BSON\Binary.
返回值
Returns the unserialized <span class="classname">MongoDB\BSON\Binary.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span
class="classname">MongoDB\Driver\Exception\UnexpectedValueException
if the properties cannot be unserialized (i.e.
serializedwas malformed). - Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).
参见
- MongoDB\BSON\Binary::serialize
- unserialize
- Serializing Objects
简介
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: <span 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 <span class="oointerface">implements <span class="interfacename">MongoDB\BSON\Decimal128Interface , <span class="interfacename">MongoDB\BSON\Type <span class="oointerface">, Serializable , <span class="interfacename">JsonSerializable {
/* 方法 */
final public
__construct ([ <span
class="methodparam">string $value ]
)
final public mixed <span class="methodname">jsonSerialize ( <span class="methodparam">void )
final public string <span class="methodname">serialize ( <span class="methodparam">void )
final public string <span class="methodname">__toString ( <span class="methodparam">void )
final public
void <span
class="methodname">unserialize ( <span
class="type">string $serialized )
}
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.3.0 | Implements MongoDB\BSON\Decimal128Interface. |
| PECL mongodb 1.2.0 | Implements Serializable and JsonSerializable. |
MongoDB\BSON\Decimal128::__construct
Construct a new Decimal128
说明
final public
MongoDB\BSON\Decimal128::__construct
([ string
$value ] )
Note: <span 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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span
class="classname">MongoDB\Driver\Exception\InvalidArgumentException
if
valueis not a valid decimal string.
范例
示例 #1 <span class="function">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 <span class="methodname">MongoDB\BSON\Decimal128::jsonSerialize ( void )
参数
此函数没有参数。
返回值
Returns data which can be serialized by <span class="function">json_encode to produce an extended JSON representation of the <span class="classname">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 <span class="function">MongoDB\BSON\toRelaxedExtendedJSON and <span class="function">MongoDB\BSON\toCanonicalExtendedJSON, respectively.
错误/异常
- Throws <span class="classname">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 <span class="methodname">MongoDB\BSON\Decimal128::serialize ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns the serialized representation of the <span class="classname">MongoDB\BSON\Decimal128.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
- <span class="methodname">MongoDB\BSON\Decimal128::unserialize
- serialize
- Serializing Objects
MongoDB\BSON\Decimal128::__toString
Returns the string representation of this Decimal128
说明
final public string <span class="methodname">MongoDB\BSON\Decimal128::__toString ( void )
参数
此函数没有参数。
返回值
Returns the string representation of this Decimal128.
范例
示例 #1 <span class="function">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 <span
class="methodname">MongoDB\BSON\Decimal128::unserialize ( <span
class="methodparam">string
$serialized )
参数
serialized
The serialized MongoDB\BSON\Decimal128.
返回值
Returns the unserialized <span class="classname">MongoDB\BSON\Decimal128.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span
class="classname">MongoDB\Driver\Exception\UnexpectedValueException
if the properties cannot be unserialized (i.e.
serializedwas malformed). - Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).
参见
- MongoDB\BSON\Decimal128::serialize
- unserialize
- Serializing Objects
简介
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 <span class="oointerface">implements <span class="interfacename">MongoDB\BSON\JavascriptInterface , <span class="interfacename">MongoDB\BSON\Type <span class="oointerface">, Serializable , <span class="interfacename">JsonSerializable {
/* 方法 */
final public
__construct ( <span
class="methodparam">string $code [,
<span
class="type">arrayobject
$scope ] )
final public string getCode ( void )
final public object<span class="type">null getScope ( void )
final public mixed <span class="methodname">jsonSerialize ( <span class="methodparam">void )
final public string <span class="methodname">serialize ( <span class="methodparam">void )
final public string <span class="methodname">__toString ( <span class="methodparam">void )
final public
void <span
class="methodname">unserialize ( <span
class="type">string $serialized )
}
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.3.0 | Implements MongoDB\BSON\JavascriptInterface. |
| PECL mongodb 1.2.0 | Implements Serializable and JsonSerializable. |
MongoDB\BSON\Javascript::__construct
Construct a new Javascript
说明
final public
MongoDB\BSON\Javascript::__construct
( string
$code [, <span
class="type">arrayobject
$scope ] )
参数
code (string)
Javascript code.
scope (arrayobject)
Javascript scope.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span
class="classname">MongoDB\Driver\Exception\InvalidArgumentException
if
codecontains null bytes.
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.2.0 | MongoDB\Driver\Exception\InvalidArgumentException is thrown if code contains null bytes. Previously, values would be truncated at the first null byte. |
范例
示例 #1 <span class="function">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 <span class="methodname">MongoDB\BSON\Javascript::getCode ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns the Javascript's code.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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<span class="type">null <span class="methodname">MongoDB\BSON\Javascript::getScope ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns the Javascript's scope document, or null if the is no
scope.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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 <span class="methodname">MongoDB\BSON\Javascript::jsonSerialize ( void )
参数
此函数没有参数。
返回值
Returns data which can be serialized by <span class="function">json_encode to produce an extended JSON representation of the <span class="classname">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 <span class="function">MongoDB\BSON\toRelaxedExtendedJSON and <span class="function">MongoDB\BSON\toCanonicalExtendedJSON, respectively.
错误/异常
- Throws <span class="classname">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 <span class="methodname">MongoDB\BSON\Javascript::serialize ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns the serialized representation of the <span class="classname">MongoDB\BSON\Javascript.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
- <span class="methodname">MongoDB\BSON\Javascript::unserialize
- serialize
- Serializing Objects
MongoDB\BSON\Javascript::__toString
Returns the Javascript's code
说明
final public string <span class="methodname">MongoDB\BSON\Javascript::__toString ( void )
此方法是该方法的别名: <span class="methodname">MongoDB\BSON\Javascript::getCode.
参数
此函数没有参数。
返回值
Returns the Javascript's code.
范例
示例 #1 <span class="function">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::getCode
- » BSON Types
MongoDB\BSON\Javascript::unserialize
Unserialize a Javascript
说明
final public
void <span
class="methodname">MongoDB\BSON\Javascript::unserialize ( <span
class="methodparam">string
$serialized )
参数
serialized
The serialized MongoDB\BSON\Javascript.
返回值
Returns the unserialized <span class="classname">MongoDB\BSON\Javascript.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span
class="classname">MongoDB\Driver\Exception\UnexpectedValueException
if the properties cannot be unserialized (i.e.
serializedwas malformed). - Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).
参见
- MongoDB\BSON\Javascript::serialize
- unserialize
- Serializing Objects
简介
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 , <span class="interfacename">MongoDB\BSON\Type <span class="oointerface">, Serializable , <span class="interfacename">JsonSerializable {
/* 方法 */
final public __construct ( <span class="methodparam">void )
final public mixed <span class="methodname">jsonSerialize ( <span class="methodparam">void )
final public string <span class="methodname">serialize ( <span class="methodparam">void )
final public
void <span
class="methodname">unserialize ( <span
class="type">string $serialized )
}
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.3.0 | Implements MongoDB\BSON\MaxKeyInterface. |
| PECL mongodb 1.2.0 | Implements Serializable and JsonSerializable. |
MongoDB\BSON\MaxKey::__construct
Construct a new MaxKey
说明
final public MongoDB\BSON\MaxKey::__construct ( void )
参数
此函数没有参数。
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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 <span class="methodname">MongoDB\BSON\MaxKey::jsonSerialize ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns data which can be serialized by <span class="function">json_encode to produce an extended JSON representation of the <span class="classname">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 <span class="function">MongoDB\BSON\toRelaxedExtendedJSON and <span class="function">MongoDB\BSON\toCanonicalExtendedJSON, respectively.
错误/异常
- Throws <span class="classname">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 <span class="methodname">MongoDB\BSON\MaxKey::serialize ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns the serialized representation of the <span class="classname">MongoDB\BSON\MaxKey.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
- MongoDB\BSON\MaxKey::unserialize
- serialize
- Serializing Objects
MongoDB\BSON\MaxKey::unserialize
Unserialize a MaxKey
说明
final public
void <span
class="methodname">MongoDB\BSON\MaxKey::unserialize ( <span
class="methodparam">string
$serialized )
参数
serialized
The serialized MongoDB\BSON\MaxKey.
返回值
Returns the unserialized <span class="classname">MongoDB\BSON\MaxKey.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
- MongoDB\BSON\MaxKey::serialize
- unserialize
- Serializing Objects
简介
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 , <span class="interfacename">MongoDB\BSON\Type <span class="oointerface">, Serializable , <span class="interfacename">JsonSerializable {
/* 方法 */
final public __construct ( <span class="methodparam">void )
final public mixed <span class="methodname">jsonSerialize ( <span class="methodparam">void )
final public string <span class="methodname">serialize ( <span class="methodparam">void )
final public
void <span
class="methodname">unserialize ( <span
class="type">string $serialized )
}
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.3.0 | Implements MongoDB\BSON\MinKeyInterface. |
| PECL mongodb 1.2.0 | Implements Serializable and JsonSerializable. |
MongoDB\BSON\MinKey::__construct
Construct a new MinKey
说明
final public MongoDB\BSON\MinKey::__construct ( void )
参数
此函数没有参数。
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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 <span class="methodname">MongoDB\BSON\MinKey::jsonSerialize ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns data which can be serialized by <span class="function">json_encode to produce an extended JSON representation of the <span class="classname">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 <span class="function">MongoDB\BSON\toRelaxedExtendedJSON and <span class="function">MongoDB\BSON\toCanonicalExtendedJSON, respectively.
错误/异常
- Throws <span class="classname">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 <span class="methodname">MongoDB\BSON\MinKey::serialize ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns the serialized representation of the <span class="classname">MongoDB\BSON\MinKey.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
- MongoDB\BSON\MinKey::unserialize
- serialize
- Serializing Objects
MongoDB\BSON\MinKey::unserialize
Unserialize a MinKey
说明
final public
void <span
class="methodname">MongoDB\BSON\MinKey::unserialize ( <span
class="methodparam">string
$serialized )
参数
serialized
The serialized MongoDB\BSON\MinKey.
返回值
Returns the unserialized <span class="classname">MongoDB\BSON\MinKey.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
- MongoDB\BSON\MinKey::serialize
- unserialize
- Serializing Objects
简介
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 <span class="methodname">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 , <span class="interfacename">MongoDB\BSON\Type <span class="oointerface">, Serializable , <span class="interfacename">JsonSerializable {
/* 方法 */
final public
__construct ([ <span
class="methodparam">string $id ] )
final public int <span class="methodname">getTimestamp ( <span class="methodparam">void )
final public mixed <span class="methodname">jsonSerialize ( <span class="methodparam">void )
final public string <span class="methodname">serialize ( <span class="methodparam">void )
final public string <span class="methodname">__toString ( <span class="methodparam">void )
final public
void <span
class="methodname">unserialize ( <span
class="type">string $serialized )
}
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.3.0 | Renamed from MongoDB\BSON\ObjectID to MongoDB\BSON\ObjectId. Implements MongoDB\BSON\ObjectIdInterface. |
| PECL mongodb 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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span
class="classname">MongoDB\Driver\Exception\InvalidArgumentException
if
idis not a 24-character hexadecimal string.
范例
示例 #1 <span class="function">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 <span class="methodname">MongoDB\BSON\ObjectId::getTimestamp ( <span class="methodparam">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 <span class="function">sprintf may be used to obtain a string representation of the unsigned decimal value.
参数
此函数没有参数。
返回值
Returns the timestamp component of this ObjectId.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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 <span class="methodname">MongoDB\BSON\ObjectId::jsonSerialize ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns data which can be serialized by <span class="function">json_encode to produce an extended JSON representation of the <span class="classname">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 <span class="function">MongoDB\BSON\toRelaxedExtendedJSON and <span class="function">MongoDB\BSON\toCanonicalExtendedJSON, respectively.
错误/异常
- Throws <span class="classname">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 <span class="methodname">MongoDB\BSON\ObjectId::serialize ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns the serialized representation of the <span class="classname">MongoDB\BSON\ObjectId.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
- MongoDB\BSON\ObjectId::unserialize
- serialize
- Serializing Objects
MongoDB\BSON\ObjectId::__toString
Returns the hexidecimal representation of this ObjectId
说明
final public string <span class="methodname">MongoDB\BSON\ObjectId::__toString ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns the hexidecimal representation of this ObjectId.
范例
示例 #1 <span class="function">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 <span
class="methodname">MongoDB\BSON\ObjectId::unserialize ( <span
class="methodparam">string
$serialized )
参数
serialized
The serialized MongoDB\BSON\ObjectId.
返回值
Returns the unserialized <span class="classname">MongoDB\BSON\ObjectId.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span
class="classname">MongoDB\Driver\Exception\UnexpectedValueException
if the properties cannot be unserialized (i.e.
serializedwas malformed). - Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).
参见
- MongoDB\BSON\ObjectId::serialize
- unserialize
- Serializing Objects
简介
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 , <span class="interfacename">MongoDB\BSON\Type <span class="oointerface">, Serializable , <span class="interfacename">JsonSerializable {
/* 方法 */
final public
__construct ( <span
class="methodparam">string $pattern
[, string
$flags = "" ] )
final public string <span class="methodname">getFlags ( <span class="methodparam">void )
final public string <span class="methodname">getPattern ( <span class="methodparam">void )
final public mixed <span class="methodname">jsonSerialize ( <span class="methodparam">void )
final public string <span class="methodname">serialize ( <span class="methodparam">void )
final public string <span class="methodname">__toString ( <span class="methodparam">void )
final public
void <span
class="methodname">unserialize ( <span
class="type">string $serialized )
}
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.3.0 | Implements MongoDB\BSON\RegexInterface. |
| PECL mongodb 1.2.0 | Implements Serializable and JsonSerializable. |
MongoDB\BSON\Regex::__construct
Construct a new Regex
说明
final public
MongoDB\BSON\Regex::__construct (
string
$pattern [, <span
class="type">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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span
class="classname">MongoDB\Driver\Exception\InvalidArgumentException
if
patternorflagscontain null bytes.
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.2.0 | The Characters in the MongoDB\Driver\Exception\InvalidArgumentException is thrown if |
范例
示例 #1 <span class="function">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 <span class="methodname">MongoDB\BSON\Regex::getFlags ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns the Regex's flags.
错误/异常
- Throws <span class="classname">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 <span class="methodname">MongoDB\BSON\Regex::getPattern ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns the Regex's pattern.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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 <span class="methodname">MongoDB\BSON\Regex::jsonSerialize ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns data which can be serialized by <span class="function">json_encode to produce an extended JSON representation of the <span class="classname">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 <span class="function">MongoDB\BSON\toRelaxedExtendedJSON and <span class="function">MongoDB\BSON\toCanonicalExtendedJSON, respectively.
错误/异常
- Throws <span class="classname">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 <span class="methodname">MongoDB\BSON\Regex::serialize ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns the serialized representation of the <span class="classname">MongoDB\BSON\Regex.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
- MongoDB\BSON\Regex::unserialize
- serialize
- Serializing Objects
MongoDB\BSON\Regex::__toString
Returns the string representation of this Regex
说明
final public string <span class="methodname">MongoDB\BSON\Regex::__toString ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns the string representation of this Regex.
范例
示例 #1 <span class="function">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 <span
class="methodname">MongoDB\BSON\Regex::unserialize ( <span
class="methodparam">string
$serialized )
参数
serialized
The serialized MongoDB\BSON\Regex.
返回值
Returns the unserialized <span class="classname">MongoDB\BSON\Regex.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span
class="classname">MongoDB\Driver\Exception\UnexpectedValueException
if the properties cannot be unserialized (i.e.
serializedwas malformed). - Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).
参见
- MongoDB\BSON\Regex::serialize
- unserialize
- Serializing Objects
简介
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 <span class="oointerface">implements <span class="interfacename">MongoDB\BSON\TimestampInterface , <span class="interfacename">MongoDB\BSON\Type <span class="oointerface">, Serializable , <span class="interfacename">JsonSerializable {
/* 方法 */
final public
__construct ( <span
class="methodparam">int $increment ,
int
$timestamp )
final public int <span class="methodname">getIncrement ( <span class="methodparam">void )
final public int <span class="methodname">getTimestamp ( <span class="methodparam">void )
final public mixed <span class="methodname">jsonSerialize ( <span class="methodparam">void )
final public string <span class="methodname">serialize ( <span class="methodparam">void )
final public string <span class="methodname">__toString ( <span class="methodparam">void )
final public
void <span
class="methodname">unserialize ( <span
class="type">string $serialized )
}
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.3.0 | Implements MongoDB\BSON\TimestampInterface. |
| PECL mongodb 1.2.0 | Implements Serializable and JsonSerializable. |
MongoDB\BSON\Timestamp::__construct
Construct a new Timestamp
说明
final public
MongoDB\BSON\Timestamp::__construct
( int
$increment , <span
class="type">int $timestamp )
参数
increment (int)
32-bit integer denoting the incrementing ordinal for operations within a
given second.
timestamp (int)
32-bit integer denoting seconds since the Unix epoch.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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 <span class="methodname">MongoDB\BSON\Timestamp::getIncrement ( <span class="methodparam">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 <span 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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
MongoDB\BSON\Timestamp::getTimestamp
Returns the timestamp component of this Timestamp
说明
final public int <span class="methodname">MongoDB\BSON\Timestamp::getTimestamp ( <span class="methodparam">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 <span 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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
MongoDB\BSON\Timestamp::jsonSerialize
Returns a representation that can be converted to JSON
说明
final public mixed <span class="methodname">MongoDB\BSON\Timestamp::jsonSerialize ( void )
参数
此函数没有参数。
返回值
Returns data which can be serialized by <span class="function">json_encode to produce an extended JSON representation of the <span class="classname">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 <span class="function">MongoDB\BSON\toRelaxedExtendedJSON and <span class="function">MongoDB\BSON\toCanonicalExtendedJSON, respectively.
错误/异常
- Throws <span class="classname">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 <span class="methodname">MongoDB\BSON\Timestamp::serialize ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns the serialized representation of the <span class="classname">MongoDB\BSON\Timestamp.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
- <span class="methodname">MongoDB\BSON\Timestamp::unserialize
- serialize
- Serializing Objects
MongoDB\BSON\Timestamp::__toString
Returns the string representation of this Timestamp
说明
final public string <span class="methodname">MongoDB\BSON\Timestamp::__toString ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns the string representation of this Timestamp.
范例
示例 #1 <span class="function">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 <span
class="methodname">MongoDB\BSON\Timestamp::unserialize ( <span
class="methodparam">string
$serialized )
参数
serialized
The serialized MongoDB\BSON\Timestamp.
返回值
Returns the unserialized <span class="classname">MongoDB\BSON\Timestamp.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span
class="classname">MongoDB\Driver\Exception\UnexpectedValueException
if the properties cannot be unserialized (i.e.
serializedwas malformed). - Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).
参见
- MongoDB\BSON\Timestamp::serialize
- unserialize
- Serializing Objects
简介
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 <span class="oointerface">implements <span class="interfacename">MongoDB\BSON\UTCDateTimeInterface , <span class="interfacename">MongoDB\BSON\Type <span class="oointerface">, Serializable , <span class="interfacename">JsonSerializable {
/* 方法 */
final public
__construct ([ <span
class="methodparam"><span
class="type">intfloat<span
class="type">string<span
class="type">DateTimeInterface $milliseconds<span
class="initializer"> = null ] )
final public mixed <span class="methodname">jsonSerialize ( <span class="methodparam">void )
final public string <span class="methodname">serialize ( <span class="methodparam">void )
final public DateTime <span class="methodname">toDateTime ( <span class="methodparam">void )
final public string <span class="methodname">__toString ( <span class="methodparam">void )
final public
void <span
class="methodname">unserialize ( <span
class="type">string $serialized )
}
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.3.0 | Implements MongoDB\BSON\UTCDateTimeInterface. |
| PECL mongodb 1.2.0 | Implements Serializable and JsonSerializable. |
MongoDB\BSON\UTCDateTime::__construct
Construct a new UTCDateTime
说明
final public
<span
class="methodname">MongoDB\BSON\UTCDateTime::__construct ([
<span
class="type">intfloat<span
class="type">string<span
class="type">DateTimeInterface $milliseconds<span
class="initializer"> = null ] )
参数
milliseconds (intfloatstringDateTimeInterface)
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 int. For compatibility on 32-bit
systems, this parameter may also be provided as a <span
class="type">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, <span class="classname">DateTime and <span class="classname">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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.2.0 | The 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 int, float, and string types were accepted. |
范例
示例 #1 <span class="function">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 <span class="methodname">MongoDB\BSON\UTCDateTime::jsonSerialize ( void )
参数
此函数没有参数。
返回值
Returns data which can be serialized by <span class="function">json_encode to produce an extended JSON representation of the <span class="classname">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 <span class="function">MongoDB\BSON\toRelaxedExtendedJSON and <span class="function">MongoDB\BSON\toCanonicalExtendedJSON, respectively.
错误/异常
- Throws <span class="classname">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 <span class="methodname">MongoDB\BSON\UTCDateTime::serialize ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns the serialized representation of the <span class="classname">MongoDB\BSON\UTCDateTime.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
- <span class="methodname">MongoDB\BSON\UTCDateTime::unserialize
- serialize
- Serializing Objects
MongoDB\BSON\UTCDateTime::toDateTime
Returns the DateTime representation of this UTCDateTime
说明
final public DateTime <span class="methodname">MongoDB\BSON\UTCDateTime::toDateTime ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns the DateTime representation of this UTCDateTime. The returned DateTime will use the UTC time zone.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
范例
示例 #1 <span class="function">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 <span class="methodname">MongoDB\BSON\UTCDateTime::__toString ( void )
参数
此函数没有参数。
返回值
Returns the string representation of this UTCDateTime.
范例
示例 #1 <span class="function">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 <span
class="methodname">MongoDB\BSON\UTCDateTime::unserialize (
string
$serialized )
参数
serialized
The serialized <span
class="classname">MongoDB\BSON\UTCDateTime.
返回值
Returns the unserialized <span class="classname">MongoDB\BSON\UTCDateTime.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span
class="classname">MongoDB\Driver\Exception\UnexpectedValueException
if the properties cannot be unserialized (i.e.
serializedwas malformed). - Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).
参见
- <span class="methodname">MongoDB\BSON\UTCDateTime::serialize
- unserialize
- Serializing Objects
简介
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 <span class="function">MongoDB\BSON\Serializable::bsonSerialize. During unserialization, the same <span class="property">__pclass property will then be used to infer the PHP class (independent of any type map configuration) to be constructed before <span class="function">MongoDB\BSON\Unserializable::bsonUnserialize is invoked. See for additional information.
Note: Even if <span class="function">MongoDB\BSON\Serializable::bsonSerialize would return a sequential array, injection of the <span class="property">__pclass property will cause the object to be serialized as a BSON document.
接口摘要
MongoDB\BSON\Persistable
class MongoDB\BSON\Persistable implements <span class="interfacename">MongoDB\BSON\Unserializable <span class="oointerface">, <span class="interfacename">MongoDB\BSON\Serializable {
/* 继承的方法 */
abstract <span class="modifier">public <span class="type">arrayobject <span class="methodname">MongoDB\BSON\Serializable::bsonSerialize ( void )
abstract <span
class="modifier">public void <span
class="methodname">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 <span class="interfacename">MongoDB\BSON\Type {
/* 方法 */
abstract <span class="modifier">public <span class="type">arrayobject <span class="methodname">bsonSerialize ( <span class="methodparam">void )
}
MongoDB\BSON\Serializable::bsonSerialize
Provides an array or document to serialize as BSON
说明
abstract <span class="modifier">public <span class="type">arrayobject <span class="methodname">MongoDB\BSON\Serializable::bsonSerialize ( void )
Called during serialization of the object to BSON. The method must return an array or <span class="classname">stdClass.
Root documents (e.g. a <span class="interfacename">MongoDB\BSON\Serializable passed to <span class="function">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 <span class="classname">stdClass to be serialized as a BSON array or document.
范例
示例 #1 <span class="function">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 <span class="function">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 <span class="function">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 <span class="function">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 ] }
参见
简介
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 <span
class="modifier">public void <span
class="methodname">bsonUnserialize ( <span
class="methodparam">array $data )
}
MongoDB\BSON\Unserializable::bsonUnserialize
Constructs the object from a BSON array or document
说明
abstract <span
class="modifier">public void <span
class="methodname">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 <span class="type">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 <span class="function">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"
}
}
参见
简介
This interface is implemented by <span class="classname">MongoDB\BSON\Binary but may also be used for type-hinting and userland classes.
类摘要
MongoDB\BSON\BinaryInterface
class MongoDB\BSON\BinaryInterface {
/* 方法 */
abstract <span class="modifier">public string <span class="methodname">getData ( <span class="methodparam">void )
abstract <span class="modifier">public int <span class="methodname">getType ( <span class="methodparam">void )
abstract <span class="modifier">public string <span class="methodname">__toString ( <span class="methodparam">void )
}
MongoDB\BSON\BinaryInterface::getData
Returns the BinaryInterface's data
说明
abstract <span class="modifier">public string <span class="methodname">MongoDB\BSON\BinaryInterface::getData ( void )
参数
此函数没有参数。
返回值
Returns the BinaryInterface's data.
参见
- MongoDB\BSON\Binary::getData
MongoDB\BSON\BinaryInterface::getType
Returns the BinaryInterface's type
说明
abstract <span class="modifier">public int <span class="methodname">MongoDB\BSON\BinaryInterface::getType ( void )
参数
此函数没有参数。
返回值
Returns the BinaryInterface's type.
参见
- MongoDB\BSON\Binary::getType
MongoDB\BSON\BinaryInterface::__toString
Returns the BinaryInterface's data
说明
abstract <span class="modifier">public string <span class="methodname">MongoDB\BSON\BinaryInterface::__toString ( void )
此方法是该方法的别名: <span class="methodname">MongoDB\BSON\BinaryInterface::getData.
参数
此函数没有参数。
返回值
Returns the BinaryInterface's data.
参见
- <span class="methodname">MongoDB\BSON\BinaryInterface::getData
- MongoDB\BSON\Binary::__toString
简介
This interface is implemented by <span class="classname">MongoDB\BSON\Decimal128 but may also be used for type-hinting and userland classes.
类摘要
MongoDB\BSON\Decimal128Interface
class MongoDB\BSON\Decimal128Interface {
/* 方法 */
abstract <span class="modifier">public string <span class="methodname">__toString ( <span class="methodparam">void )
}
MongoDB\BSON\Decimal128Interface::__toString
Returns the string representation of this Decimal128Interface
说明
abstract <span class="modifier">public string <span class="methodname">MongoDB\BSON\Decimal128Interface::__toString ( void )
参数
此函数没有参数。
返回值
Returns the string representation of this Decimal128Interface.
参见
- <span class="methodname">MongoDB\BSON\Decimal128::__toString
简介
This interface is implemented by <span class="classname">MongoDB\BSON\Javascript but may also be used for type-hinting and userland classes.
类摘要
MongoDB\BSON\JavascriptInterface
class MongoDB\BSON\JavascriptInterface {
/* 方法 */
abstract <span class="modifier">public string <span class="methodname">getCode ( <span class="methodparam">void )
abstract <span class="modifier">public <span class="type">objectnull <span class="methodname">getScope ( <span class="methodparam">void )
abstract <span class="modifier">public string <span class="methodname">__toString ( <span class="methodparam">void )
}
MongoDB\BSON\JavascriptInterface::getCode
Returns the JavascriptInterface's code
说明
abstract <span class="modifier">public string <span class="methodname">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 <span class="modifier">public <span class="type">objectnull <span class="methodname">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 <span class="modifier">public string <span class="methodname">MongoDB\BSON\JavascriptInterface::__toString ( void )
此方法是该方法的别名: <span class="methodname">MongoDB\BSON\JavascriptInterface::getCode.
参数
此函数没有参数。
返回值
Returns the JavascriptInterface's code.
参见
- <span class="methodname">MongoDB\BSON\JavascriptInterface::getCode
- <span class="methodname">MongoDB\BSON\Javascript::__toString
简介
This interface is implemented by <span class="classname">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 <span class="classname">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 <span class="classname">MongoDB\BSON\ObjectId but may also be used for type-hinting and userland classes.
类摘要
MongoDB\BSON\ObjectIdInterface
class MongoDB\BSON\ObjectIdInterface {
/* 方法 */
abstract <span class="modifier">public int <span class="methodname">getTimestamp ( <span class="methodparam">void )
abstract <span class="modifier">public string <span class="methodname">__toString ( <span class="methodparam">void )
}
MongoDB\BSON\ObjectIdInterface::getTimestamp
Returns the timestamp component of this ObjectIdInterface
说明
abstract <span class="modifier">public int <span class="methodname">MongoDB\BSON\ObjectIdInterface::getTimestamp ( void )
参数
此函数没有参数。
返回值
Returns the timestamp component of this ObjectIdInterface.
参见
- <span class="methodname">MongoDB\BSON\ObjectId::getTimestamp
MongoDB\BSON\ObjectIdInterface::__toString
Returns the hexidecimal representation of this ObjectIdInterface
说明
abstract <span class="modifier">public string <span class="methodname">MongoDB\BSON\ObjectIdInterface::__toString ( void )
参数
此函数没有参数。
返回值
Returns the hexidecimal representation of this ObjectIdInterface.
参见
- <span class="methodname">MongoDB\BSON\ObjectId::__toString
简介
This interface is implemented by <span class="classname">MongoDB\BSON\Regex but may also be used for type-hinting and userland classes.
类摘要
MongoDB\BSON\RegexInterface
class MongoDB\BSON\RegexInterface {
/* 方法 */
abstract <span class="modifier">public string <span class="methodname">getFlags ( <span class="methodparam">void )
abstract <span class="modifier">public string <span class="methodname">getPattern ( <span class="methodparam">void )
abstract <span class="modifier">public string <span class="methodname">__toString ( <span class="methodparam">void )
}
MongoDB\BSON\RegexInterface::getFlags
Returns the RegexInterface's flags
说明
abstract <span class="modifier">public string <span class="methodname">MongoDB\BSON\RegexInterface::getFlags ( void )
参数
此函数没有参数。
返回值
Returns the RegexInterface's flags.
参见
- MongoDB\BSON\Regex::getFlags
MongoDB\BSON\RegexInterface::getPattern
Returns the RegexInterface's pattern
说明
abstract <span class="modifier">public string <span class="methodname">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 <span class="modifier">public string <span class="methodname">MongoDB\BSON\RegexInterface::__toString ( void )
参数
此函数没有参数。
返回值
Returns the string representation of this RegexInterface.
参见
- MongoDB\BSON\Regex::__toString
简介
This interface is implemented by <span class="classname">MongoDB\BSON\Timestamp but may also be used for type-hinting and userland classes.
类摘要
MongoDB\BSON\TimestampInterface
class MongoDB\BSON\TimestampInterface {
/* 方法 */
abstract <span class="modifier">public int <span class="methodname">getIncrement ( <span class="methodparam">void )
abstract <span class="modifier">public int <span class="methodname">getTimestamp ( <span class="methodparam">void )
abstract <span class="modifier">public string <span class="methodname">__toString ( <span class="methodparam">void )
}
MongoDB\BSON\TimestampInterface::getIncrement
Returns the increment component of this TimestampInterface
说明
abstract <span class="modifier">public int <span class="methodname">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.
参见
- <span class="methodname">MongoDB\BSON\Timestamp::getIncrement
MongoDB\BSON\TimestampInterface::getTimestamp
Returns the timestamp component of this TimestampInterface
说明
abstract <span class="modifier">public int <span class="methodname">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.
参见
- <span class="methodname">MongoDB\BSON\Timestamp::getTimestamp
MongoDB\BSON\TimestampInterface::__toString
Returns the string representation of this TimestampInterface
说明
abstract <span class="modifier">public string <span class="methodname">MongoDB\BSON\TimestampInterface::__toString ( void )
参数
此函数没有参数。
返回值
Returns the string representation of this TimestampInterface.
参见
- <span class="methodname">MongoDB\BSON\Timestamp::__toString
简介
This interface is implemented by <span class="classname">MongoDB\BSON\UTCDateTime but may also be used for type-hinting and userland classes.
类摘要
MongoDB\BSON\UTCDateTimeInterface
class MongoDB\BSON\UTCDateTimeInterface {
/* 方法 */
abstract <span class="modifier">public DateTime <span class="methodname">toDateTime ( <span class="methodparam">void )
abstract <span class="modifier">public string <span class="methodname">__toString ( <span class="methodparam">void )
}
MongoDB\BSON\UTCDateTimeInterface::toDateTime
Returns the DateTime representation of this UTCDateTimeInterface
说明
abstract <span class="modifier">public DateTime <span class="methodname">MongoDB\BSON\UTCDateTimeInterface::toDateTime ( void )
参数
此函数没有参数。
返回值
Returns the DateTime representation of this UTCDateTimeInterface. The returned <span class="classname">DateTime should use the UTC time zone.
参见
- <span class="methodname">MongoDB\BSON\UTCDateTime::toDateTime
MongoDB\BSON\UTCDateTimeInterface::__toString
Returns the string representation of this UTCDateTimeInterface
说明
abstract <span class="modifier">public string <span class="methodname">MongoDB\BSON\UTCDateTimeInterface::__toString ( void )
参数
此函数没有参数。
返回值
Returns the string representation of this UTCDateTimeInterface.
参见
- <span class="methodname">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 <span class="oointerface">implements <span class="interfacename">MongoDB\BSON\Type <span class="oointerface">, Serializable , <span class="interfacename">JsonSerializable {
/* 方法 */
final <span class="modifier">private <span class="methodname">__construct ( <span class="methodparam">void )
final public mixed <span class="methodname">jsonSerialize ( <span class="methodparam">void )
final public string <span class="methodname">serialize ( <span class="methodparam">void )
final public string <span class="methodname">__toString ( <span class="methodparam">void )
final public
void <span
class="methodname">unserialize ( <span
class="type">string $serialized )
}
MongoDB\BSON\DBPointer::__construct
Construct a new DBPointer (unused)
说明
final <span class="modifier">private <span class="methodname">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 <span class="methodname">MongoDB\BSON\DBPointer::jsonSerialize ( void )
参数
此函数没有参数。
返回值
Returns data which can be serialized by <span class="function">json_encode to produce an extended JSON representation of the <span class="classname">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 <span class="function">MongoDB\BSON\toRelaxedExtendedJSON and <span class="function">MongoDB\BSON\toCanonicalExtendedJSON, respectively.
错误/异常
- Throws <span class="classname">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 <span class="methodname">MongoDB\BSON\DBPointer::serialize ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns the serialized representation of the <span class="classname">MongoDB\BSON\DBPointer.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
- <span class="methodname">MongoDB\BSON\DBPointer::unserialize
- serialize
- Serializing Objects
MongoDB\BSON\DBPointer::__toString
Returns an empty string
说明
final public string <span class="methodname">MongoDB\BSON\DBPointer::__toString ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns an empty string.
参见
MongoDB\BSON\DBPointer::unserialize
Unserialize a DBPointer
说明
final public
void <span
class="methodname">MongoDB\BSON\DBPointer::unserialize ( <span
class="methodparam">string
$serialized )
参数
serialized
The serialized MongoDB\BSON\DBPointer.
返回值
Returns the unserialized <span class="classname">MongoDB\BSON\DBPointer.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
- MongoDB\BSON\DBPointer::serialize
- unserialize
- Serializing Objects
简介
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_SIZEis 8) should never encounter this class during normal operation.
类摘要
MongoDB\BSON\Int64
final class MongoDB\BSON\Int64 implements MongoDB\BSON\Type <span class="oointerface">, Serializable , <span class="interfacename">JsonSerializable {
/* 方法 */
final <span class="modifier">private <span class="methodname">__construct ( <span class="methodparam">void )
final public mixed <span class="methodname">jsonSerialize ( <span class="methodparam">void )
final public string <span class="methodname">serialize ( <span class="methodparam">void )
final public string <span class="methodname">__toString ( <span class="methodparam">void )
final public
void <span
class="methodname">unserialize ( <span
class="type">string $serialized )
}
MongoDB\BSON\Int64::__construct
Construct a new Int64 (unused)
说明
final <span class="modifier">private <span class="methodname">MongoDB\BSON\Int64::__construct ( <span class="methodparam">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 <span class="methodname">MongoDB\BSON\Int64::jsonSerialize ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns data which can be serialized by <span class="function">json_encode to produce an extended JSON representation of the <span class="classname">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 (<span class="function">MongoDB\BSON\toJSON), in order to ensure that the 64-bit integer value is correctly represented on 32-bit platforms.
错误/异常
- Throws <span class="classname">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 <span class="methodname">MongoDB\BSON\Int64::serialize ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns the serialized representation of the <span class="classname">MongoDB\BSON\Int64.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
- MongoDB\BSON\Int64::unserialize
- serialize
- Serializing Objects
MongoDB\BSON\Int64::__toString
Returns the string representation of this Int64
说明
final public string <span class="methodname">MongoDB\BSON\Int64::__toString ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns the string representation of this Int64.
范例
示例 #1 <span class="function">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 <span
class="methodname">MongoDB\BSON\Int64::unserialize ( <span
class="methodparam">string
$serialized )
参数
serialized
The serialized MongoDB\BSON\Int64.
返回值
Returns the unserialized <span class="classname">MongoDB\BSON\Int64.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws <span
class="classname">MongoDB\Driver\Exception\UnexpectedValueException
if the properties cannot be unserialized (i.e.
serializedwas malformed). - Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).
参见
- MongoDB\BSON\Int64::serialize
- unserialize
- Serializing Objects
简介
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 <span class="oointerface">, Serializable , <span class="interfacename">JsonSerializable {
/* 方法 */
final <span class="modifier">private <span class="methodname">__construct ( <span class="methodparam">void )
final public mixed <span class="methodname">jsonSerialize ( <span class="methodparam">void )
final public string <span class="methodname">serialize ( <span class="methodparam">void )
final public string <span class="methodname">__toString ( <span class="methodparam">void )
final public
void <span
class="methodname">unserialize ( <span
class="type">string $serialized )
}
MongoDB\BSON\Symbol::__construct
Construct a new Symbol (unused)
说明
final <span class="modifier">private <span class="methodname">MongoDB\BSON\Symbol::__construct ( <span class="methodparam">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 <span class="methodname">MongoDB\BSON\Symbol::jsonSerialize ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns data which can be serialized by <span class="function">json_encode to produce an extended JSON representation of the <span class="classname">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 <span class="function">MongoDB\BSON\toRelaxedExtendedJSON and <span class="function">MongoDB\BSON\toCanonicalExtendedJSON, respectively.
错误/异常
- Throws <span class="classname">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 <span class="methodname">MongoDB\BSON\Symbol::serialize ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns the serialized representation of the <span class="classname">MongoDB\BSON\Symbol.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
- MongoDB\BSON\Symbol::unserialize
- serialize
- Serializing Objects
MongoDB\BSON\Symbol::__toString
Returns the Symbol as a string
说明
final public string <span class="methodname">MongoDB\BSON\Symbol::__toString ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns the string representation of this Symbol.
参见
MongoDB\BSON\Symbol::unserialize
Unserialize a Symbol
说明
final public
void <span
class="methodname">MongoDB\BSON\Symbol::unserialize ( <span
class="methodparam">string
$serialized )
参数
serialized
The serialized MongoDB\BSON\Symbol.
返回值
Returns the unserialized <span class="classname">MongoDB\BSON\Symbol.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
- MongoDB\BSON\Symbol::serialize
- unserialize
- Serializing Objects
简介
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 <span class="oointerface">implements <span class="interfacename">MongoDB\BSON\Type <span class="oointerface">, Serializable , <span class="interfacename">JsonSerializable {
/* 方法 */
final <span class="modifier">private <span class="methodname">__construct ( <span class="methodparam">void )
final public mixed <span class="methodname">jsonSerialize ( <span class="methodparam">void )
final public string <span class="methodname">serialize ( <span class="methodparam">void )
final public string <span class="methodname">__toString ( <span class="methodparam">void )
final public
void <span
class="methodname">unserialize ( <span
class="type">string $serialized )
}
MongoDB\BSON\Undefined::__construct
Construct a new Undefined (unused)
说明
final <span class="modifier">private <span class="methodname">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 <span class="methodname">MongoDB\BSON\Undefined::jsonSerialize ( void )
参数
此函数没有参数。
返回值
Returns data which can be serialized by <span class="function">json_encode to produce an extended JSON representation of the <span class="classname">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 <span class="function">MongoDB\BSON\toRelaxedExtendedJSON and <span class="function">MongoDB\BSON\toCanonicalExtendedJSON, respectively.
错误/异常
- Throws <span class="classname">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 <span class="methodname">MongoDB\BSON\Undefined::serialize ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns the serialized representation of the <span class="classname">MongoDB\BSON\Undefined.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
- <span class="methodname">MongoDB\BSON\Undefined::unserialize
- serialize
- Serializing Objects
MongoDB\BSON\Undefined::__toString
Returns an empty string
说明
final public string <span class="methodname">MongoDB\BSON\Undefined::__toString ( <span class="methodparam">void )
参数
此函数没有参数。
返回值
Returns an empty string.
参见
MongoDB\BSON\Undefined::unserialize
Unserialize a Undefined
说明
final public
void <span
class="methodname">MongoDB\BSON\Undefined::unserialize ( <span
class="methodparam">string
$serialized )
参数
serialized
The serialized MongoDB\BSON\Undefined.
返回值
Returns the unserialized <span class="classname">MongoDB\BSON\Undefined.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
- MongoDB\BSON\Undefined::serialize
- unserialize
- Serializing Objects
Monitoring classes and subscriber functions
目录
- 函数
- MongoDB\Driver\Monitoring\addSubscriber — Registers a new monitoring event subscriber
- MongoDB\Driver\Monitoring\removeSubscriber — Unregisters an existing monitoring event subscriber
- MongoDB\Driver\Monitoring\CommandFailedEvent
— The MongoDB\Driver\Monitoring\CommandFailedEvent class
- MongoDB\Driver\Monitoring\CommandFailedEvent::getCommandName — Returns the command name
- MongoDB\Driver\Monitoring\CommandFailedEvent::getDurationMicros — Returns the command's duration in microseconds
- MongoDB\Driver\Monitoring\CommandFailedEvent::getError — Returns the Exception associated with the failed command
- MongoDB\Driver\Monitoring\CommandFailedEvent::getOperationId — Returns the command's operation ID
- MongoDB\Driver\Monitoring\CommandFailedEvent::getReply — Returns the command reply document
- MongoDB\Driver\Monitoring\CommandFailedEvent::getRequestId — Returns the command's request ID
- MongoDB\Driver\Monitoring\CommandFailedEvent::getServer — Returns the Server on which the command was executed
- MongoDB\Driver\Monitoring\CommandStartedEvent
— The MongoDB\Driver\Monitoring\CommandStartedEvent class
- MongoDB\Driver\Monitoring\CommandStartedEvent::getCommand — Returns the command document
- MongoDB\Driver\Monitoring\CommandStartedEvent::getCommandName — Returns the command name
- MongoDB\Driver\Monitoring\CommandStartedEvent::getDatabaseName — Returns the database on which the command was executed
- MongoDB\Driver\Monitoring\CommandStartedEvent::getOperationId — Returns the command's operation ID
- MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId — Returns the command's request ID
- MongoDB\Driver\Monitoring\CommandStartedEvent::getServer — Returns the Server on which the command was executed
- MongoDB\Driver\Monitoring\CommandSucceededEvent
— The MongoDB\Driver\Monitoring\CommandSucceededEvent class
- MongoDB\Driver\Monitoring\CommandSucceededEvent::getCommandName — Returns the command name
- MongoDB\Driver\Monitoring\CommandSucceededEvent::getDurationMicros — Returns the command's duration in microseconds
- MongoDB\Driver\Monitoring\CommandSucceededEvent::getOperationId — Returns the command's operation ID
- MongoDB\Driver\Monitoring\CommandSucceededEvent::getReply — Returns the command reply document
- MongoDB\Driver\Monitoring\CommandSucceededEvent::getRequestId — Returns the command's request ID
- MongoDB\Driver\Monitoring\CommandSucceededEvent::getServer — Returns the Server on which the command was executed
- MongoDB\Driver\Monitoring\CommandSubscriber
— The MongoDB\Driver\Monitoring\CommandSubscriber interface
- MongoDB\Driver\Monitoring\CommandSubscriber::commandFailed — Notification method for a failed command
- MongoDB\Driver\Monitoring\CommandSubscriber::commandStarted — Notification method for a started command
- MongoDB\Driver\Monitoring\CommandSubscriber::commandSucceeded — Notification method for a successful command
- MongoDB\Driver\Monitoring\Subscriber — The MongoDB\Driver\Monitoring\Subscriber interface
MongoDB\Driver\Monitoring\addSubscriber
Registers a new monitoring event subscriber
说明
void <span
class="methodname">MongoDB\Driver\Monitoring\addSubscriber (
<span
class="type">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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
- <span class="interfacename">MongoDB\Driver\Monitoring\Subscriber
- <span class="interfacename">MongoDB\Driver\Monitoring\CommandSubscriber
- <span class="function">MongoDB\Driver\Monitoring\removeSubscriber
MongoDB\Driver\Monitoring\removeSubscriber
Unregisters an existing monitoring event subscriber
说明
void <span
class="methodname">MongoDB\Driver\Monitoring\removeSubscriber
( <span
class="type">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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
- <span class="interfacename">MongoDB\Driver\Monitoring\Subscriber
- <span class="interfacename">MongoDB\Driver\Monitoring\CommandSubscriber
- <span class="function">MongoDB\Driver\Monitoring\addSubscriber
目录
- MongoDB\Driver\Monitoring\addSubscriber — Registers a new monitoring event subscriber
- MongoDB\Driver\Monitoring\removeSubscriber — Unregisters an existing monitoring event subscriber
简介
The <span class="classname">MongoDB\Driver\Monitoring\CommandFailedEvent class encapsulates information about a failed command.
类摘要
MongoDB\Driver\Monitoring\CommandFailedEvent
final class MongoDB\Driver\Monitoring\CommandFailedEvent {
/* 方法 */
final public string <span class="methodname">getCommandName ( <span class="methodparam">void )
final public int <span class="methodname">getDurationMicros ( <span class="methodparam">void )
final public Exception <span class="methodname">getError ( <span class="methodparam">void )
final public string <span class="methodname">getOperationId ( <span class="methodparam">void )
final public object <span class="methodname">getReply ( <span class="methodparam">void )
final public string <span class="methodname">getRequestId ( <span class="methodparam">void )
final public MongoDB\Driver\Server <span class="methodname">getServer ( <span class="methodparam">void )
}
MongoDB\Driver\Monitoring\CommandFailedEvent::getCommandName
Returns the command name
说明
final public string <span class="methodname">MongoDB\Driver\Monitoring\CommandFailedEvent::getCommandName ( void )
Returns the command name (e.g. "find", "aggregate").
参数
此函数没有参数。
返回值
Returns the command name.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
MongoDB\Driver\Monitoring\CommandFailedEvent::getDurationMicros
Returns the command's duration in microseconds
说明
final public int <span class="methodname">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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
MongoDB\Driver\Monitoring\CommandFailedEvent::getError
Returns the Exception associated with the failed command
说明
final public Exception <span class="methodname">MongoDB\Driver\Monitoring\CommandFailedEvent::getError ( void )
参数
此函数没有参数。
返回值
Returns the Exception associated with the failed command.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
MongoDB\Driver\Monitoring\CommandFailedEvent::getOperationId
Returns the command's operation ID
说明
final public string <span class="methodname">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 <span class="methodname">MongoDB\Driver\Monitoring\CommandFailedEvent::getRequestId should be used instead.
参数
此函数没有参数。
返回值
Returns the command's operation ID.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
- <span class="methodname">MongoDB\Driver\Monitoring\CommandStartedEvent::getOperationId
- <span class="methodname">MongoDB\Driver\Monitoring\CommandFailedEvent::getRequestId
MongoDB\Driver\Monitoring\CommandFailedEvent::getReply
Returns the command reply document
说明
final public object <span class="methodname">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 <span class="type">stdClass).
参数
此函数没有参数。
返回值
Returns the command reply document as a <span class="classname">stdClass object.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
MongoDB\Driver\Monitoring\CommandFailedEvent::getRequestId
Returns the command's request ID
说明
final public string <span class="methodname">MongoDB\Driver\Monitoring\CommandFailedEvent::getRequestId ( void )
The request ID is generated by the driver and may be used to associate this <span class="classname">MongoDB\Driver\Monitoring\CommandFailedEvent with a previous <span class="classname">MongoDB\Driver\Monitoring\CommandStartedEvent.
参数
此函数没有参数。
返回值
Returns the command's request ID.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
MongoDB\Driver\Monitoring\CommandFailedEvent::getServer
Returns the Server on which the command was executed
说明
final public MongoDB\Driver\Server <span class="methodname">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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
简介
The <span class="classname">MongoDB\Driver\Monitoring\CommandStartedEvent class encapsulates information about a started command.
类摘要
MongoDB\Driver\Monitoring\CommandStartedEvent
final class MongoDB\Driver\Monitoring\CommandStartedEvent {
/* 方法 */
final public object <span class="methodname">getCommand ( <span class="methodparam">void )
final public string <span class="methodname">getCommandName ( <span class="methodparam">void )
final public string <span class="methodname">getDatabaseName ( <span class="methodparam">void )
final public string <span class="methodname">getOperationId ( <span class="methodparam">void )
final public string <span class="methodname">getRequestId ( <span class="methodparam">void )
final public MongoDB\Driver\Server <span class="methodname">getServer ( <span class="methodparam">void )
}
MongoDB\Driver\Monitoring\CommandStartedEvent::getCommand
Returns the command document
说明
final public object <span class="methodname">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 <span class="type">stdClass).
参数
此函数没有参数。
返回值
Returns the command document as a <span class="classname">stdClass object.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
MongoDB\Driver\Monitoring\CommandStartedEvent::getCommandName
Returns the command name
说明
final public string <span class="methodname">MongoDB\Driver\Monitoring\CommandStartedEvent::getCommandName ( void )
Returns the command name (e.g. "find", "aggregate").
参数
此函数没有参数。
返回值
Returns the command name.
错误/异常
- Throws <span class="classname">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 <span class="methodname">MongoDB\Driver\Monitoring\CommandStartedEvent::getDatabaseName ( void )
参数
此函数没有参数。
返回值
Returns the database on which the command was executed.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
MongoDB\Driver\Monitoring\CommandStartedEvent::getOperationId
Returns the command's operation ID
说明
final public string <span class="methodname">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 <span class="methodname">MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId should be used instead.
参数
此函数没有参数。
返回值
Returns the command's operation ID.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
- <span class="methodname">MongoDB\Driver\Monitoring\CommandFailedEvent::getOperationId
- <span class="methodname">MongoDB\Driver\Monitoring\CommandSucceededEvent::getOperationId
- <span class="methodname">MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId
MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId
Returns the command's request ID
说明
final public string <span class="methodname">MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId ( void )
The request ID is generated by the driver and may be used to associate this <span class="classname">MongoDB\Driver\Monitoring\CommandStartedEvent with a later <span class="classname">MongoDB\Driver\Monitoring\CommandFailedEvent or <span class="classname">MongoDB\Driver\Monitoring\CommandSucceededEvent.
参数
此函数没有参数。
返回值
Returns the command's request ID.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
- <span class="methodname">MongoDB\Driver\Monitoring\CommandFailedEvent::getRequestId
- <span class="methodname">MongoDB\Driver\Monitoring\CommandSucceededEvent::getRequestId
MongoDB\Driver\Monitoring\CommandStartedEvent::getServer
Returns the Server on which the command was executed
说明
final public MongoDB\Driver\Server <span class="methodname">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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
- <span class="methodname">MongoDB\Driver\Monitoring\CommandFailedEvent::getServer
- <span class="methodname">MongoDB\Driver\Monitoring\CommandSucceededEvent::getServer
简介
The <span class="classname">MongoDB\Driver\Monitoring\CommandSucceededEvent class encapsulates information about a successful command.
类摘要
MongoDB\Driver\Monitoring\CommandSucceededEvent
final class MongoDB\Driver\Monitoring\CommandSucceededEvent {
/* 方法 */
final public string <span class="methodname">getCommandName ( <span class="methodparam">void )
final public int <span class="methodname">getDurationMicros ( <span class="methodparam">void )
final public string <span class="methodname">getOperationId ( <span class="methodparam">void )
final public object <span class="methodname">getReply ( <span class="methodparam">void )
final public string <span class="methodname">getRequestId ( <span class="methodparam">void )
final public MongoDB\Driver\Server <span class="methodname">getServer ( <span class="methodparam">void )
}
MongoDB\Driver\Monitoring\CommandSucceededEvent::getCommandName
Returns the command name
说明
final public string <span class="methodname">MongoDB\Driver\Monitoring\CommandSucceededEvent::getCommandName ( void )
Returns the command name (e.g. "find", "aggregate").
参数
此函数没有参数。
返回值
Returns the command name.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
MongoDB\Driver\Monitoring\CommandSucceededEvent::getDurationMicros
Returns the command's duration in microseconds
说明
final public int <span class="methodname">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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
MongoDB\Driver\Monitoring\CommandSucceededEvent::getOperationId
Returns the command's operation ID
说明
final public string <span class="methodname">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 <span class="methodname">MongoDB\Driver\Monitoring\CommandSucceededEvent::getRequestId should be used instead.
参数
此函数没有参数。
返回值
Returns the command's operation ID.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
- <span class="methodname">MongoDB\Driver\Monitoring\CommandStartedEvent::getOperationId
- <span class="methodname">MongoDB\Driver\Monitoring\CommandSucceededEvent::getRequestId
MongoDB\Driver\Monitoring\CommandSucceededEvent::getReply
Returns the command reply document
说明
final public object <span class="methodname">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 <span class="type">stdClass).
参数
此函数没有参数。
返回值
Returns the command reply document as a <span class="classname">stdClass object.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
MongoDB\Driver\Monitoring\CommandSucceededEvent::getRequestId
Returns the command's request ID
说明
final public string <span class="methodname">MongoDB\Driver\Monitoring\CommandSucceededEvent::getRequestId ( void )
The request ID is generated by the driver and may be used to associate this <span class="classname">MongoDB\Driver\Monitoring\CommandSucceededEvent with a previous <span class="classname">MongoDB\Driver\Monitoring\CommandStartedEvent.
参数
此函数没有参数。
返回值
Returns the command's request ID.
错误/异常
- Throws <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
MongoDB\Driver\Monitoring\CommandSucceededEvent::getServer
Returns the Server on which the command was executed
说明
final public MongoDB\Driver\Server <span class="methodname">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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
- <span class="methodname">MongoDB\Driver\Monitoring\CommandStartedEvent::getServer
- MongoDB\Driver\Cursor::getServer
- <span class="methodname">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 <span class="oointerface">implements <span class="interfacename">MongoDB\Driver\Monitoring\Subscriber {
/* 方法 */
abstract <span
class="modifier">public void <span
class="methodname">commandFailed ( <span
class="methodparam"><span
class="type">MongoDB\Driver\Monitoring\CommandFailedEvent
$event )
abstract <span
class="modifier">public void <span
class="methodname">commandStarted ( <span
class="methodparam"><span
class="type">MongoDB\Driver\Monitoring\CommandStartedEvent
$event )
abstract <span
class="modifier">public void <span
class="methodname">commandSucceeded ( <span
class="methodparam"><span
class="type">MongoDB\Driver\Monitoring\CommandSucceededEvent
$event )
}
MongoDB\Driver\Monitoring\CommandSubscriber::commandFailed
Notification method for a failed command
说明
abstract <span
class="modifier">public void <span
class="methodname">MongoDB\Driver\Monitoring\CommandSubscriber::commandFailed
( <span
class="type">MongoDB\Driver\Monitoring\CommandFailedEvent
$event )
If the subscriber has been registered with <span class="function">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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
- <span class="classname">MongoDB\Driver\Monitoring\CommandFailedEvent
- <span class="function">MongoDB\Driver\Monitoring\addSubscriber
MongoDB\Driver\Monitoring\CommandSubscriber::commandStarted
Notification method for a started command
说明
abstract <span
class="modifier">public void <span
class="methodname">MongoDB\Driver\Monitoring\CommandSubscriber::commandStarted
( <span
class="type">MongoDB\Driver\Monitoring\CommandStartedEvent
$event )
If the subscriber has been registered with <span class="function">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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
- <span class="classname">MongoDB\Driver\Monitoring\CommandStartedEvent
- <span class="function">MongoDB\Driver\Monitoring\addSubscriber
MongoDB\Driver\Monitoring\CommandSubscriber::commandSucceeded
Notification method for a successful command
说明
abstract <span
class="modifier">public void <span
class="methodname">MongoDB\Driver\Monitoring\CommandSubscriber::commandSucceeded
( <span
class="type">MongoDB\Driver\Monitoring\CommandSucceededEvent
$event )
If the subscriber has been registered with <span class="function">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 <span class="classname">MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
参见
- <span class="classname">MongoDB\Driver\Monitoring\CommandSucceededEvent
- <span class="function">MongoDB\Driver\Monitoring\addSubscriber
简介
Base interface for event subscribers. This is used for type-hinting MongoDB\Driver\Monitoring\addSubscriber and <span class="function">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 类
目录
- MongoDB\Driver\Exception\AuthenticationException — The MongoDB\Driver\Exception\AuthenticationException class
- MongoDB\Driver\Exception\BulkWriteException — The MongoDB\Driver\Exception\BulkWriteException class
- MongoDB\Driver\Exception\ConnectionException — The MongoDB\Driver\Exception\ConnectionException class
- MongoDB\Driver\Exception\ConnectionTimeoutException — The MongoDB\Driver\Exception\ConnectionTimeoutException class
- MongoDB\Driver\Exception\Exception — The MongoDB\Driver\Exception\Exception interface
- MongoDB\Driver\Exception\ExecutionTimeoutException — The MongoDB\Driver\Exception\ExecutionTimeoutException class
- MongoDB\Driver\Exception\InvalidArgumentException — The MongoDB\Driver\Exception\InvalidArgumentException class
- MongoDB\Driver\Exception\LogicException — The MongoDB\Driver\Exception\LogicException class
- MongoDB\Driver\Exception\RuntimeException
— The MongoDB\Driver\Exception\RuntimeException class
- MongoDB\Driver\Exception\RuntimeException::hasErrorLabel — Returns whether an error label is associated with an exception
- MongoDB\Driver\Exception\SSLConnectionException — The MongoDB\Driver\Exception\SSLConnectionException class (deprecated)
- MongoDB\Driver\Exception\UnexpectedValueException — The MongoDB\Driver\Exception\UnexpectedValueException class
- MongoDB\Driver\Exception\WriteException
— The MongoDB\Driver\Exception\WriteException class
- MongoDB\Driver\Exception\WriteException::getWriteResult — Returns the WriteResult for the failed write operation
简介
Thrown when the driver fails to authenticate with the server.
类摘要
MongoDB\Driver\Exception\AuthenticationException
class MongoDB\Driver\Exception\AuthenticationException <span class="ooclass"> extends MongoDB\Driver\Exception\ConnectionException <span class="oointerface">implements <span class="interfacename">MongoDB\Driver\Exception\Exception {
/* 继承的属性 */
protected <span
class="type">arraynull
$errorLabels ;
protected string
$message ;
protected int
$code ;
protected string
$file ;
protected int
$line ;
/* 继承的方法 */
final public
bool <span
class="methodname">MongoDB\Driver\Exception\RuntimeException::hasErrorLabel
( string
$errorLabel )
final public string <span class="methodname">Exception::getMessage ( <span class="methodparam">void )
final public Throwable <span class="methodname">Exception::getPrevious ( <span class="methodparam">void )
final public mixed <span class="methodname">Exception::getCode ( <span class="methodparam">void )
final public string <span class="methodname">Exception::getFile ( <span class="methodparam">void )
final public int <span class="methodname">Exception::getLine ( <span class="methodparam">void )
final public array <span class="methodname">Exception::getTrace ( <span class="methodparam">void )
final public string <span class="methodname">Exception::getTraceAsString ( <span class="methodparam">void )
public string Exception::__toString ( <span class="methodparam">void )
final <span class="modifier">private void <span class="methodname">Exception::__clone ( <span class="methodparam">void )
}
简介
Thrown when a bulk write operation fails.
类摘要
MongoDB\Driver\Exception\BulkWriteException
class MongoDB\Driver\Exception\BulkWriteException <span class="ooclass"> extends MongoDB\Driver\Exception\WriteException <span class="oointerface">implements <span class="interfacename">MongoDB\Driver\Exception\Exception {
/* 继承的属性 */
protected <span
class="type">MongoDB\Driver\WriteResult $writeResult ;
protected <span
class="type">arraynull
$errorLabels ;
protected string
$message ;
protected int
$code ;
protected string
$file ;
protected int
$line ;
/* 继承的方法 */
final public MongoDB\Driver\WriteResult <span class="methodname">MongoDB\Driver\Exception\WriteException::getWriteResult ( void )
final public
bool <span
class="methodname">MongoDB\Driver\Exception\RuntimeException::hasErrorLabel
( string
$errorLabel )
final public string <span class="methodname">Exception::getMessage ( <span class="methodparam">void )
final public Throwable <span class="methodname">Exception::getPrevious ( <span class="methodparam">void )
final public mixed <span class="methodname">Exception::getCode ( <span class="methodparam">void )
final public string <span class="methodname">Exception::getFile ( <span class="methodparam">void )
final public int <span class="methodname">Exception::getLine ( <span class="methodparam">void )
final public array <span class="methodname">Exception::getTrace ( <span class="methodparam">void )
final public string <span class="methodname">Exception::getTraceAsString ( <span class="methodparam">void )
public string Exception::__toString ( <span class="methodparam">void )
final <span class="modifier">private void <span class="methodname">Exception::__clone ( <span class="methodparam">void )
}
简介
Base class for exceptions thrown when the driver fails to establish a database connection.
类摘要
MongoDB\Driver\Exception\ConnectionException
class MongoDB\Driver\Exception\ConnectionException <span class="ooclass"> extends MongoDB\Driver\Exception\RuntimeException <span class="oointerface">implements <span class="interfacename">MongoDB\Driver\Exception\Exception {
/* 继承的属性 */
protected <span
class="type">arraynull
$errorLabels ;
protected string
$message ;
protected int
$code ;
protected string
$file ;
protected int
$line ;
/* 继承的方法 */
final public
bool <span
class="methodname">MongoDB\Driver\Exception\RuntimeException::hasErrorLabel
( string
$errorLabel )
final public string <span class="methodname">Exception::getMessage ( <span class="methodparam">void )
final public Throwable <span class="methodname">Exception::getPrevious ( <span class="methodparam">void )
final public mixed <span class="methodname">Exception::getCode ( <span class="methodparam">void )
final public string <span class="methodname">Exception::getFile ( <span class="methodparam">void )
final public int <span class="methodname">Exception::getLine ( <span class="methodparam">void )
final public array <span class="methodname">Exception::getTrace ( <span class="methodparam">void )
final public string <span class="methodname">Exception::getTraceAsString ( <span class="methodparam">void )
public string Exception::__toString ( <span class="methodparam">void )
final <span class="modifier">private void <span class="methodname">Exception::__clone ( <span class="methodparam">void )
}
简介
Thrown when the driver fails to establish a database connection within a specified time limit (connectTimeoutMS) or server selection fails (serverSelectionTimeoutMS).
类摘要
MongoDB\Driver\Exception\ConnectionTimeoutException
final class MongoDB\Driver\Exception\ConnectionTimeoutException <span class="ooclass"> extends MongoDB\Driver\Exception\ConnectionException <span class="oointerface">implements <span class="interfacename">MongoDB\Driver\Exception\Exception {
/* 继承的属性 */
protected <span
class="type">arraynull
$errorLabels ;
protected string
$message ;
protected int
$code ;
protected string
$file ;
protected int
$line ;
/* 继承的方法 */
final public
bool <span
class="methodname">MongoDB\Driver\Exception\RuntimeException::hasErrorLabel
( string
$errorLabel )
final public string <span class="methodname">Exception::getMessage ( <span class="methodparam">void )
final public Throwable <span class="methodname">Exception::getPrevious ( <span class="methodparam">void )
final public mixed <span class="methodname">Exception::getCode ( <span class="methodparam">void )
final public string <span class="methodname">Exception::getFile ( <span class="methodparam">void )
final public int <span class="methodname">Exception::getLine ( <span class="methodparam">void )
final public array <span class="methodname">Exception::getTrace ( <span class="methodparam">void )
final public string <span class="methodname">Exception::getTraceAsString ( <span class="methodparam">void )
public string Exception::__toString ( <span class="methodparam">void )
final <span class="modifier">private void <span class="methodname">Exception::__clone ( <span class="methodparam">void )
}
简介
Common interface for all driver exceptions. This may be used to catch only exceptions originating from the driver itself.
类摘要
MongoDB\Driver\Exception\Exception
class MongoDB\Driver\Exception\Exception {
}
简介
Thrown when a query or command fails to complete within a specified time limit (e.g. » maxTimeMS).
类摘要
MongoDB\Driver\Exception\ExecutionTimeoutException
final class MongoDB\Driver\Exception\ExecutionTimeoutException <span class="ooclass"> extends MongoDB\Driver\Exception\ServerException <span class="oointerface">implements <span class="interfacename">MongoDB\Driver\Exception\Exception {
/* 继承的属性 */
protected <span
class="type">arraynull
$errorLabels ;
protected string
$message ;
protected int
$code ;
protected string
$file ;
protected int
$line ;
/* 继承的方法 */
final public
bool <span
class="methodname">MongoDB\Driver\Exception\RuntimeException::hasErrorLabel
( string
$errorLabel )
final public string <span class="methodname">Exception::getMessage ( <span class="methodparam">void )
final public Throwable <span class="methodname">Exception::getPrevious ( <span class="methodparam">void )
final public mixed <span class="methodname">Exception::getCode ( <span class="methodparam">void )
final public string <span class="methodname">Exception::getFile ( <span class="methodparam">void )
final public int <span class="methodname">Exception::getLine ( <span class="methodparam">void )
final public array <span class="methodname">Exception::getTrace ( <span class="methodparam">void )
final public string <span class="methodname">Exception::getTraceAsString ( <span class="methodparam">void )
public string Exception::__toString ( <span class="methodparam">void )
final <span class="modifier">private void <span class="methodname">Exception::__clone ( <span class="methodparam">void )
}
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.5.0 | This class now extends MongoDB\Driver\Exception\ServerException instead of MongoDB\Driver\Exception\RuntimeException. |
简介
Thrown when a driver method is given invalid arguments (e.g. invalid option types).
类摘要
MongoDB\Driver\Exception\InvalidArgumentException
class MongoDB\Driver\Exception\InvalidArgumentException <span class="ooclass"> extends InvalidArgumentException <span class="oointerface">implements <span class="interfacename">MongoDB\Driver\Exception\Exception {
/* 继承的属性 */
protected string
$message ;
protected int
$code ;
protected string
$file ;
protected int
$line ;
/* 继承的方法 */
final public string <span class="methodname">Exception::getMessage ( <span class="methodparam">void )
final public Throwable <span class="methodname">Exception::getPrevious ( <span class="methodparam">void )
final public mixed <span class="methodname">Exception::getCode ( <span class="methodparam">void )
final public string <span class="methodname">Exception::getFile ( <span class="methodparam">void )
final public int <span class="methodname">Exception::getLine ( <span class="methodparam">void )
final public array <span class="methodname">Exception::getTrace ( <span class="methodparam">void )
final public string <span class="methodname">Exception::getTraceAsString ( <span class="methodparam">void )
public string Exception::__toString ( <span class="methodparam">void )
final <span class="modifier">private void <span class="methodname">Exception::__clone ( <span class="methodparam">void )
}
简介
Thrown when the driver is incorrectly used (e.g. rewinding a cursor).
类摘要
MongoDB\Driver\Exception\LogicException
class MongoDB\Driver\Exception\LogicException <span class="ooclass"> extends LogicException implements <span class="interfacename">MongoDB\Driver\Exception\Exception {
/* 继承的属性 */
protected string
$message ;
protected int
$code ;
protected string
$file ;
protected int
$line ;
/* 继承的方法 */
final public string <span class="methodname">Exception::getMessage ( <span class="methodparam">void )
final public Throwable <span class="methodname">Exception::getPrevious ( <span class="methodparam">void )
final public mixed <span class="methodname">Exception::getCode ( <span class="methodparam">void )
final public string <span class="methodname">Exception::getFile ( <span class="methodparam">void )
final public int <span class="methodname">Exception::getLine ( <span class="methodparam">void )
final public array <span class="methodname">Exception::getTrace ( <span class="methodparam">void )
final public string <span class="methodname">Exception::getTraceAsString ( <span class="methodparam">void )
public string Exception::__toString ( <span class="methodparam">void )
final <span class="modifier">private void <span class="methodname">Exception::__clone ( <span class="methodparam">void )
}
简介
Thrown when the driver encounters a runtime error (e.g. internal error from » libmongoc).
类摘要
MongoDB\Driver\Exception\RuntimeException
class MongoDB\Driver\Exception\RuntimeException <span class="ooclass"> extends RuntimeException implements <span class="interfacename">MongoDB\Driver\Exception\Exception {
/* 属性 */
protected <span
class="type">arraynull
$errorLabels ;
/* 继承的属性 */
protected string
$message ;
protected int
$code ;
protected string
$file ;
protected int
$line ;
/* 方法 */
final public
bool <span
class="methodname">hasErrorLabel ( <span
class="methodparam">string
$errorLabel )
/* 继承的方法 */
final public string <span class="methodname">Exception::getMessage ( <span class="methodparam">void )
final public Throwable <span class="methodname">Exception::getPrevious ( <span class="methodparam">void )
final public mixed <span class="methodname">Exception::getCode ( <span class="methodparam">void )
final public string <span class="methodname">Exception::getFile ( <span class="methodparam">void )
final public int <span class="methodname">Exception::getLine ( <span class="methodparam">void )
final public array <span class="methodname">Exception::getTrace ( <span class="methodparam">void )
final public string <span class="methodname">Exception::getTraceAsString ( <span class="methodparam">void )
public string Exception::__toString ( <span class="methodparam">void )
final <span class="modifier">private void <span class="methodname">Exception::__clone ( <span class="methodparam">void )
}
属性
errorLabels
Contains an array of error labels to go with an exception. For example,
error labels can be used to detect whether a transaction can be retried
safely if the TransientTransactionError label is present. The
existence of a specific error label should be tested for with the <span
class="methodname">MongoDB\Driver\Exception\RuntimeException::hasErrorLabel,
instead of interpreting this errorLabels property manually.
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.6.0 | The MongoDB\Driver\Exception\RuntimeException::hasErrorLabel method and MongoDB\Driver\Exception\RuntimeException::errorLabels property have been added. |
MongoDB\Driver\Exception\RuntimeException::hasErrorLabel
Returns whether an error label is associated with an exception
说明
final public
bool <span
class="methodname">MongoDB\Driver\Exception\RuntimeException::hasErrorLabel
( string
$errorLabel )
Returns whether the errorLabel has been set for this exception. Error
labels are set by either the server or the driver to indicated specific
situations on which you might want to decide on how you want to handle a
specific exception. A common situation might be to find out whether you
can safely retry a transaction that failed due to a transient error
(like a networking issue, or a transaction conflict). Examples of error
labels are TransientTransactionError and
UnknownTransactionCommitResult.
参数
errorLabel
The name of the errorLabel to test for.
返回值
Whether the given errorLabel is associated with this exception.
参见
- <span class="function">MongoDB\Driver\Session::commitTransaction
- » MongoDB documentation on transactions
Warning
This exception class is deprecated and may be removed in a future major version. The driver has never thrown this exception.
简介
Thrown when the driver fails to establish an SSL connection with the server.
类摘要
MongoDB\Driver\Exception\SSLConnectionException
final class MongoDB\Driver\Exception\SSLConnectionException <span class="ooclass"> extends MongoDB\Driver\Exception\ConnectionException <span class="oointerface">implements <span class="interfacename">MongoDB\Driver\Exception\Exception {
/* 继承的属性 */
protected <span
class="type">arraynull
$errorLabels ;
protected string
$message ;
protected int
$code ;
protected string
$file ;
protected int
$line ;
/* 继承的方法 */
final public
bool <span
class="methodname">MongoDB\Driver\Exception\RuntimeException::hasErrorLabel
( string
$errorLabel )
final public string <span class="methodname">Exception::getMessage ( <span class="methodparam">void )
final public Throwable <span class="methodname">Exception::getPrevious ( <span class="methodparam">void )
final public mixed <span class="methodname">Exception::getCode ( <span class="methodparam">void )
final public string <span class="methodname">Exception::getFile ( <span class="methodparam">void )
final public int <span class="methodname">Exception::getLine ( <span class="methodparam">void )
final public array <span class="methodname">Exception::getTrace ( <span class="methodparam">void )
final public string <span class="methodname">Exception::getTraceAsString ( <span class="methodparam">void )
public string Exception::__toString ( <span class="methodparam">void )
final <span class="modifier">private void <span class="methodname">Exception::__clone ( <span class="methodparam">void )
}
简介
Thrown when the driver encounters an unexpected value (e.g. during BSON serialization or deserialization).
类摘要
MongoDB\Driver\Exception\UnexpectedValueException
class MongoDB\Driver\Exception\UnexpectedValueException <span class="ooclass"> extends UnexpectedValueException <span class="oointerface">implements <span class="interfacename">MongoDB\Driver\Exception\Exception {
/* 继承的属性 */
protected string
$message ;
protected int
$code ;
protected string
$file ;
protected int
$line ;
/* 继承的方法 */
final public string <span class="methodname">Exception::getMessage ( <span class="methodparam">void )
final public Throwable <span class="methodname">Exception::getPrevious ( <span class="methodparam">void )
final public mixed <span class="methodname">Exception::getCode ( <span class="methodparam">void )
final public string <span class="methodname">Exception::getFile ( <span class="methodparam">void )
final public int <span class="methodname">Exception::getLine ( <span class="methodparam">void )
final public array <span class="methodname">Exception::getTrace ( <span class="methodparam">void )
final public string <span class="methodname">Exception::getTraceAsString ( <span class="methodparam">void )
public string Exception::__toString ( <span class="methodparam">void )
final <span class="modifier">private void <span class="methodname">Exception::__clone ( <span class="methodparam">void )
}
简介
Base class for exceptions thrown by a failed write operation. The exception encapsulates a <span class="classname">MongoDB\Driver\WriteResult object.
类摘要
MongoDB\Driver\Exception\WriteException
abstract class MongoDB\Driver\Exception\WriteException <span class="ooclass"> extends MongoDB\Driver\Exception\ServerException <span class="oointerface">implements <span class="interfacename">MongoDB\Driver\Exception\Exception {
/* 属性 */
protected <span
class="type">MongoDB\Driver\WriteResult $writeResult ;
/* 继承的属性 */
protected <span
class="type">arraynull
$errorLabels ;
protected string
$message ;
protected int
$code ;
protected string
$file ;
protected int
$line ;
/* 方法 */
final public MongoDB\Driver\WriteResult <span class="methodname">getWriteResult ( <span class="methodparam">void )
/* 继承的方法 */
final public
bool <span
class="methodname">MongoDB\Driver\Exception\RuntimeException::hasErrorLabel
( string
$errorLabel )
final public string <span class="methodname">Exception::getMessage ( <span class="methodparam">void )
final public Throwable <span class="methodname">Exception::getPrevious ( <span class="methodparam">void )
final public mixed <span class="methodname">Exception::getCode ( <span class="methodparam">void )
final public string <span class="methodname">Exception::getFile ( <span class="methodparam">void )
final public int <span class="methodname">Exception::getLine ( <span class="methodparam">void )
final public array <span class="methodname">Exception::getTrace ( <span class="methodparam">void )
final public string <span class="methodname">Exception::getTraceAsString ( <span class="methodparam">void )
public string Exception::__toString ( <span class="methodparam">void )
final <span class="modifier">private void <span class="methodname">Exception::__clone ( <span class="methodparam">void )
}
属性
writeResult
The MongoDB\Driver\WriteResult
associated with the failed write operation.
更新日志
| 版本 | 说明 |
|---|---|
| PECL mongodb 1.5.0 | This class now extends MongoDB\Driver\Exception\ServerException instead of MongoDB\Driver\Exception\RuntimeException. |
MongoDB\Driver\Exception\WriteException::getWriteResult
Returns the WriteResult for the failed write operation
说明
final public MongoDB\Driver\WriteResult <span class="methodname">MongoDB\Driver\Exception\WriteException::getWriteResult ( void )
Returns the MongoDB\Driver\WriteResult for the failed write operation. The <span class="function">MongoDB\Driver\WriteResult::getWriteErrors and <span class="function">MongoDB\Driver\WriteResult::getWriteConcernError methods may be used to get more details about the failure.
参数
此函数没有参数。
返回值
The MongoDB\Driver\WriteResult for the failed write operation.
范例
示例 #1 <span class="function">MongoDB\Driver\Exception\WriteException::getWriteResult example
<?php
$manager = new MongoDB\Driver\Manager('mongodb://localhost');
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 1]);
try {
$manager->executeBulkWrite('db.collection', $bulk);
} catch (MongoDB\Driver\Exception\WriteException $e) {
$writeResult = $e->getWriteResult();
if ($writeConcernError = $writeResult->getWriteConcernError()) {
var_dump($writeConcernError);
}
if ($writeErrors = $writeResult->getWriteErrors()) {
var_dump($writeErrors);
}
}
?>
以上例程的输出类似于:
array(1) {
[0]=>
object(MongoDB\Driver\WriteError)#5 (4) {
["message"]=>
string(70) "E11000 duplicate key error index: db.collection.$_id_ dup key: { : 1 }"
["code"]=>
int(11000)
["index"]=>
int(1)
["info"]=>
NULL
}
}
参见
- MongoDB\Driver\WriteResult
- <span class="function">MongoDB\Driver\Manager::executeBulkWrite