phpcs.xml.dist 0000666 00000014062 13645314021 0007353 0 ustar 00
.phpcs/autoload.php
.phpcs
src
tests
/src/GridFS/StreamWrapper
/tests/DocumentationExamplesTest.php
/tests/Compat/PolyfillAssertTrait.php
LICENSE 0000666 00000026136 13645314021 0005564 0 ustar 00
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
README.md 0000666 00000005533 13645314021 0006034 0 ustar 00 # MongoDB PHP Library
[![Build Status](https://api.travis-ci.org/mongodb/mongo-php-library.png?branch=master)](https://travis-ci.org/mongodb/mongo-php-library)
This library provides a high-level abstraction around the lower-level
[PHP driver](https://github.com/mongodb/mongo-php-driver) (`mongodb` extension).
While the extension provides a limited API for executing commands, queries, and
write operations, this library implements an API similar to that of the
[legacy PHP driver](https://php.net/manual/en/book.mongo.php). It contains
abstractions for client, database, and collection objects, and provides methods
for CRUD operations and common commands (e.g. index and collection management).
If you are developing an application with MongoDB, you should consider using
this library, or another high-level abstraction, instead of the extension alone.
Additional information about the architecture of this library and the `mongodb`
extension may be found in
[Architecture Overview](https://php.net/manual/en/mongodb.overview.php).
## Documentation
- https://docs.mongodb.com/php-library/
- https://docs.mongodb.com/ecosystem/drivers/php/
## Installation
The preferred method of installing this library is with
[Composer](https://getcomposer.org/) by running the following from your project
root:
$ composer require mongodb/mongodb
Additional installation instructions may be found in the
[library documentation](https://docs.mongodb.com/php-library/current/tutorial/install-php-library/).
Since this library is a high-level abstraction for the driver, it also requires
that the `mongodb` extension be installed:
$ pecl install mongodb
$ echo "extension=mongodb.so" >> `php --ini | grep "Loaded Configuration" | sed -e "s|.*:\s*||"`
Additional installation instructions for the extension may be found in its
[PHP.net documentation](https://php.net/manual/en/mongodb.installation.php).
## Reporting Issues
Issues pertaining to the library should be reported in the
[PHPLIB](https://jira.mongodb.org/secure/CreateIssue!default.jspa?project-field=PHPLIB)
project in MongoDB's JIRA. Extension-related issues should be reported in the
[PHPC](https://jira.mongodb.org/secure/CreateIssue!default.jspa?project-field=PHPC)
project.
For general questions and support requests, please use one of MongoDB's
[Technical Support](https://docs.mongodb.com/manual/support/) channels.
### Security Vulnerabilities
If you've identified a security vulnerability in a driver or any other MongoDB
project, please report it according to the instructions in
[Create a Vulnerability Report](https://docs.mongodb.org/manual/tutorial/create-a-vulnerability-report).
## Development
Development is tracked in the
[PHPLIB](https://jira.mongodb.org/projects/PHPLIB/summary) project in MongoDB's
JIRA. Documentation for contributing to this project may be found in
[CONTRIBUTING.md](CONTRIBUTING.md).
.travis/setup_mo.sh 0000666 00000005627 13645314021 0010336 0 ustar 00 #!/bin/bash
echo Loading MO for $DEPLOYMENT
if [[ -z $TRAVIS_BUILD_DIR ]]; then
export TRAVIS_BUILD_DIR=`pwd`;
fi
case $DEPLOYMENT in
SHARDED_CLUSTER)
${TRAVIS_BUILD_DIR}/.travis/mo.sh ${TRAVIS_BUILD_DIR}/mongo-orchestration/sharded_clusters/cluster.json start > /tmp/mo-result.json
cat /tmp/mo-result.json | tail -n 1 | php -r 'echo json_decode(file_get_contents("php://stdin"))->mongodb_uri, "/?retryWrites=false";' > /tmp/uri.txt
;;
SHARDED_CLUSTER_RS)
${TRAVIS_BUILD_DIR}/.travis/mo.sh ${TRAVIS_BUILD_DIR}/mongo-orchestration/sharded_clusters/cluster_replset.json start > /tmp/mo-result.json
cat /tmp/mo-result.json | tail -n 1 | php -r 'echo json_decode(file_get_contents("php://stdin"))->mongodb_uri;' > /tmp/uri.txt
;;
STANDALONE_AUTH)
${TRAVIS_BUILD_DIR}/.travis/mo.sh ${TRAVIS_BUILD_DIR}/mongo-orchestration/standalone/standalone-auth.json start > /tmp/mo-result.json
cat /tmp/mo-result.json | tail -n 1 | php -r 'echo json_decode(file_get_contents("php://stdin"))->mongodb_auth_uri;' > /tmp/uri.txt
;;
STANDALONE_OLD)
${TRAVIS_BUILD_DIR}/.travis/mo.sh ${TRAVIS_BUILD_DIR}/mongo-orchestration/standalone/standalone-old.json start > /tmp/mo-result.json
cat /tmp/mo-result.json | tail -n 1 | php -r 'echo json_decode(file_get_contents("php://stdin"))->mongodb_uri;' > /tmp/uri.txt
;;
STANDALONE_SSL)
${TRAVIS_BUILD_DIR}/.travis/mo.sh ${TRAVIS_BUILD_DIR}/mongo-orchestration/standalone/standalone-ssl.json start > /tmp/mo-result.json
cat /tmp/mo-result.json | tail -n 1 | php -r 'echo json_decode(file_get_contents("php://stdin"))->mongodb_uri, "/?ssl=true&sslallowinvalidcertificates=true";' > /tmp/uri.txt
;;
REPLICASET)
${TRAVIS_BUILD_DIR}/.travis/mo.sh ${TRAVIS_BUILD_DIR}/mongo-orchestration/replica_sets/replicaset.json start > /tmp/mo-result.json
cat /tmp/mo-result.json | tail -n 1 | php -r 'echo json_decode(file_get_contents("php://stdin"))->mongodb_uri;' > /tmp/uri.txt
;;
REPLICASET_SINGLE)
${TRAVIS_BUILD_DIR}/.travis/mo.sh ${TRAVIS_BUILD_DIR}/mongo-orchestration/replica_sets/replicaset-one-node.json start > /tmp/mo-result.json
cat /tmp/mo-result.json | tail -n 1 | php -r 'echo json_decode(file_get_contents("php://stdin"))->mongodb_uri;' > /tmp/uri.txt
;;
REPLICASET_OLD)
${TRAVIS_BUILD_DIR}/.travis/mo.sh ${TRAVIS_BUILD_DIR}/mongo-orchestration/replica_sets/replicaset-old.json start > /tmp/mo-result.json
cat /tmp/mo-result.json | tail -n 1 | php -r 'echo json_decode(file_get_contents("php://stdin"))->mongodb_uri;' > /tmp/uri.txt
;;
*)
${TRAVIS_BUILD_DIR}/.travis/mo.sh ${TRAVIS_BUILD_DIR}/mongo-orchestration/standalone/standalone.json start > /tmp/mo-result.json
cat /tmp/mo-result.json | tail -n 1 | php -r 'echo json_decode(file_get_contents("php://stdin"))->mongodb_uri;' > /tmp/uri.txt
;;
esac
echo -n "MongoDB Test URI: "
cat /tmp/uri.txt
echo
echo "Raw MO Response:"
cat /tmp/mo-result.json
echo
.travis/debug-core.sh 0000666 00000000462 13645314021 0010507 0 ustar 00 #!/bin/sh
if [ "${TRAVIS_OS_NAME}" = "osx" ]; then
# https://www.ics.uci.edu/~pattis/common/handouts/macmingweclipse/allexperimental/mac-gdb-install.html
echo "Cannot debug core files on macOS: ${1}"
exit 1
fi
PHP_BINARY=`which php`
gdb -batch -ex "bt full" -ex "quit" "${PHP_BINARY}" "${1}"
.travis/mo.sh 0000666 00000005573 13645314021 0007116 0 ustar 00 #!/bin/bash
# Copyright 2012-2014 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
function eval_params {
local params=$(sed -e 's|["]|\\\"|g' $1)
echo $(eval echo \"$params\")
}
function r {
echo $1| awk -F'/' '{print $(NF-1)}'| sed 's/standalone/servers/'
}
function a {
echo $(cd $(dirname $1); pwd)/$(basename $1)
}
function id {
local id_line=$(grep id $1 | head -n 1)
echo $(expr "$id_line" : '.*: *"\(.*\)" *,*')
}
function get {
echo "GET $1 $(curl --header 'Accept: application/json' --include --silent --request GET $1)"
}
function post {
echo "POST $1 $(curl --header 'Accept: application/json' --include --silent --request POST --data "$2" $1)"
}
function delete {
echo "DELETE $1 $(curl --header 'Accept: application/json' --include --silent --request DELETE $1)"
}
function code {
expr "$1" : '.*HTTP/1.[01] \([0-9]*\)'
}
function usage {
echo "usage: $0 configurations/cluster/file.json action"
echo "cluster: servers|replica_sets|sharded_clusters"
echo "action: start|status|stop"
exit 1
}
SSL_FILES=$(a ./ssl-files)
BASE_URL=${MONGO_ORCHESTRATION:-'http://localhost:8889'}
if [ $# -ne 2 ]; then usage; fi
if [ ! -f "$1" ]; then echo "configuration file '$1' not found"; exit 1; fi
ID=$(id $1)
if [ ! "$ID" ]; then echo "id field not found in configuration file '$1'"; exit 1; fi
R=$(r $1)
GET=$(get $BASE_URL/$R/$ID)
HTTP_CODE=$(code "$GET")
EXIT_CODE=0
case $2 in
start)
if [ "$HTTP_CODE" != "200" ]
then
WORKSPACE=${TRAVIS_BUILD_DIR}/orchestrations
rm -fr $WORKSPACE
mkdir $WORKSPACE
LOGPATH=$WORKSPACE
DBPATH=$WORKSPACE
POST_DATA=$(eval_params $1)
echo "DBPATH=$DBPATH"
echo "LOGPATH=$LOGPATH"
echo "POST_DATA='$POST_DATA'"
echo
POST=$(post $BASE_URL/$R "$POST_DATA")
echo "$POST"
HTTP_CODE=$(code "$POST")
if [ "$HTTP_CODE" != 200 ]; then EXIT_CODE=1; fi
else
echo "$GET"
fi
;;
stop)
if [ "$HTTP_CODE" == "200" ]
then
DELETE=$(delete $BASE_URL/$R/$ID)
echo "$DELETE"
HTTP_CODE=$(code "$DELETE")
if [ "$HTTP_CODE" != 204 ]; then EXIT_CODE=1; fi
else
echo "$GET"
fi
;;
status)
if [ "$HTTP_CODE" == "200" ]
then
echo "$GET"
else
echo "$GET"
EXIT_CODE=1
fi
;;
*)
usage
;;
esac
exit $EXIT_CODE
.travis/install-extension.sh 0000666 00000002525 13645314021 0012155 0 ustar 00 #!/bin/sh
INI=~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/travis.ini
# tpecl is a helper to compile and cache php extensions
tpecl () {
local ext_name=$1
local ext_so=$2
local ext_dir=$(php -r "echo ini_get('extension_dir');")
local ext_cache=~/php-ext/$(basename $ext_dir)/$ext_name
if [[ -e $ext_cache/$ext_so ]]; then
echo extension = $ext_cache/$ext_so >> $INI
else
mkdir -p $ext_cache
echo yes | pecl install -f $ext_name &&
cp $ext_dir/$ext_so $ext_cache
fi
}
if [ "x${DRIVER_BRANCH}" != "x" ] || [ "x${DRIVER_REPO}" != "x" ]; then
CLONE_REPO=${DRIVER_REPO:-https://github.com/mongodb/mongo-php-driver}
CHECKOUT_BRANCH=${DRIVER_BRANCH:-master}
echo "Compiling driver branch ${CHECKOUT_BRANCH} from repository ${CLONE_REPO}"
mkdir -p /tmp/compile
git clone ${CLONE_REPO} /tmp/compile/mongo-php-driver
cd /tmp/compile/mongo-php-driver
git checkout ${CHECKOUT_BRANCH}
git submodule update --init
phpize
./configure --enable-mongodb-developer-flags
make all -j20 > /dev/null
make install
echo "extension=mongodb.so" >> `php --ini | grep "Scan for additional .ini files in" | sed -e "s|.*:\s*||"`/mongodb.ini
elif [ "x${DRIVER_VERSION}" != "x" ]; then
echo "Installing driver version ${DRIVER_VERSION} from PECL"
tpecl mongodb-${DRIVER_VERSION} mongodb.so
fi
.github/ISSUE_TEMPLATE/bug-report.md 0000666 00000006164 13645314021 0012711 0 ustar 00 ---
name: Bug Report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
### Bug Report
### Environment
### Test Script
### Expected and Actual Behavior
### Debug Log
src/InsertOneResult.php 0000666 00000005266 13645314021 0011165 0 ustar 00 writeResult = $writeResult;
$this->insertedId = $insertedId;
$this->isAcknowledged = $writeResult->isAcknowledged();
}
/**
* Return the number of documents that were inserted.
*
* This method should only be called if the write was acknowledged.
*
* @see InsertOneResult::isAcknowledged()
* @return integer
* @throws BadMethodCallException is the write result is unacknowledged
*/
public function getInsertedCount()
{
if ($this->isAcknowledged) {
return $this->writeResult->getInsertedCount();
}
throw BadMethodCallException::unacknowledgedWriteResultAccess(__METHOD__);
}
/**
* Return the inserted document's ID.
*
* If the document had an ID prior to inserting (i.e. the driver did not
* need to generate an ID), this will contain its "_id". Any
* driver-generated ID will be a MongoDB\BSON\ObjectId instance.
*
* @return mixed
*/
public function getInsertedId()
{
return $this->insertedId;
}
/**
* Return whether this insert was acknowledged by the server.
*
* If the insert was not acknowledged, other fields from the WriteResult
* (e.g. insertedCount) will be undefined.
*
* If the insert was not acknowledged, other fields from the WriteResult
* (e.g. insertedCount) will be undefined and their getter methods should
* not be invoked.
*
* @return boolean
*/
public function isAcknowledged()
{
return $this->writeResult->isAcknowledged();
}
}
src/GridFS/Bucket.php 0000666 00000057147 13645314021 0010420 0 ustar 00 BSONArray::class,
'document' => BSONDocument::class,
'root' => BSONDocument::class,
];
/** @var string */
private static $streamWrapperProtocol = 'gridfs';
/** @var CollectionWrapper */
private $collectionWrapper;
/** @var string */
private $databaseName;
/** @var Manager */
private $manager;
/** @var string */
private $bucketName;
/** @var boolean */
private $disableMD5;
/** @var integer */
private $chunkSizeBytes;
/** @var ReadConcern */
private $readConcern;
/** @var ReadPreference */
private $readPreference;
/** @var array */
private $typeMap;
/** @var WriteConcern */
private $writeConcern;
/**
* Constructs a GridFS bucket.
*
* Supported options:
*
* * bucketName (string): The bucket name, which will be used as a prefix
* for the files and chunks collections. Defaults to "fs".
*
* * chunkSizeBytes (integer): The chunk size in bytes. Defaults to
* 261120 (i.e. 255 KiB).
*
* * disableMD5 (boolean): When true, no MD5 sum will be generated for
* each stored file. Defaults to "false".
*
* * readConcern (MongoDB\Driver\ReadConcern): Read concern.
*
* * readPreference (MongoDB\Driver\ReadPreference): Read preference.
*
* * typeMap (array): Default type map for cursors and BSON documents.
*
* * writeConcern (MongoDB\Driver\WriteConcern): Write concern.
*
* @param Manager $manager Manager instance from the driver
* @param string $databaseName Database name
* @param array $options Bucket options
* @throws InvalidArgumentException for parameter/option parsing errors
*/
public function __construct(Manager $manager, $databaseName, array $options = [])
{
$options += [
'bucketName' => self::$defaultBucketName,
'chunkSizeBytes' => self::$defaultChunkSizeBytes,
'disableMD5' => false,
];
if (! is_string($options['bucketName'])) {
throw InvalidArgumentException::invalidType('"bucketName" option', $options['bucketName'], 'string');
}
if (! is_integer($options['chunkSizeBytes'])) {
throw InvalidArgumentException::invalidType('"chunkSizeBytes" option', $options['chunkSizeBytes'], 'integer');
}
if ($options['chunkSizeBytes'] < 1) {
throw new InvalidArgumentException(sprintf('Expected "chunkSizeBytes" option to be >= 1, %d given', $options['chunkSizeBytes']));
}
if (! is_bool($options['disableMD5'])) {
throw InvalidArgumentException::invalidType('"disableMD5" option', $options['disableMD5'], 'boolean');
}
if (isset($options['readConcern']) && ! $options['readConcern'] instanceof ReadConcern) {
throw InvalidArgumentException::invalidType('"readConcern" option', $options['readConcern'], ReadConcern::class);
}
if (isset($options['readPreference']) && ! $options['readPreference'] instanceof ReadPreference) {
throw InvalidArgumentException::invalidType('"readPreference" option', $options['readPreference'], ReadPreference::class);
}
if (isset($options['typeMap']) && ! is_array($options['typeMap'])) {
throw InvalidArgumentException::invalidType('"typeMap" option', $options['typeMap'], 'array');
}
if (isset($options['writeConcern']) && ! $options['writeConcern'] instanceof WriteConcern) {
throw InvalidArgumentException::invalidType('"writeConcern" option', $options['writeConcern'], WriteConcern::class);
}
$this->manager = $manager;
$this->databaseName = (string) $databaseName;
$this->bucketName = $options['bucketName'];
$this->chunkSizeBytes = $options['chunkSizeBytes'];
$this->disableMD5 = $options['disableMD5'];
$this->readConcern = $options['readConcern'] ?? $this->manager->getReadConcern();
$this->readPreference = $options['readPreference'] ?? $this->manager->getReadPreference();
$this->typeMap = $options['typeMap'] ?? self::$defaultTypeMap;
$this->writeConcern = $options['writeConcern'] ?? $this->manager->getWriteConcern();
$collectionOptions = array_intersect_key($options, ['readConcern' => 1, 'readPreference' => 1, 'typeMap' => 1, 'writeConcern' => 1]);
$this->collectionWrapper = new CollectionWrapper($manager, $databaseName, $options['bucketName'], $collectionOptions);
$this->registerStreamWrapper();
}
/**
* Return internal properties for debugging purposes.
*
* @see http://php.net/manual/en/language.oop5.magic.php#language.oop5.magic.debuginfo
* @return array
*/
public function __debugInfo()
{
return [
'bucketName' => $this->bucketName,
'databaseName' => $this->databaseName,
'manager' => $this->manager,
'chunkSizeBytes' => $this->chunkSizeBytes,
'readConcern' => $this->readConcern,
'readPreference' => $this->readPreference,
'typeMap' => $this->typeMap,
'writeConcern' => $this->writeConcern,
];
}
/**
* Delete a file from the GridFS bucket.
*
* If the files collection document is not found, this method will still
* attempt to delete orphaned chunks.
*
* @param mixed $id File ID
* @throws FileNotFoundException if no file could be selected
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function delete($id)
{
$file = $this->collectionWrapper->findFileById($id);
$this->collectionWrapper->deleteFileAndChunksById($id);
if ($file === null) {
throw FileNotFoundException::byId($id, $this->getFilesNamespace());
}
}
/**
* Writes the contents of a GridFS file to a writable stream.
*
* @param mixed $id File ID
* @param resource $destination Writable Stream
* @throws FileNotFoundException if no file could be selected
* @throws InvalidArgumentException if $destination is not a stream
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function downloadToStream($id, $destination)
{
if (! is_resource($destination) || get_resource_type($destination) != "stream") {
throw InvalidArgumentException::invalidType('$destination', $destination, 'resource');
}
stream_copy_to_stream($this->openDownloadStream($id), $destination);
}
/**
* Writes the contents of a GridFS file, which is selected by name and
* revision, to a writable stream.
*
* Supported options:
*
* * revision (integer): Which revision (i.e. documents with the same
* filename and different uploadDate) of the file to retrieve. Defaults
* to -1 (i.e. the most recent revision).
*
* Revision numbers are defined as follows:
*
* * 0 = the original stored file
* * 1 = the first revision
* * 2 = the second revision
* * etc…
* * -2 = the second most recent revision
* * -1 = the most recent revision
*
* @param string $filename Filename
* @param resource $destination Writable Stream
* @param array $options Download options
* @throws FileNotFoundException if no file could be selected
* @throws InvalidArgumentException if $destination is not a stream
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function downloadToStreamByName($filename, $destination, array $options = [])
{
if (! is_resource($destination) || get_resource_type($destination) != "stream") {
throw InvalidArgumentException::invalidType('$destination', $destination, 'resource');
}
stream_copy_to_stream($this->openDownloadStreamByName($filename, $options), $destination);
}
/**
* Drops the files and chunks collections associated with this GridFS
* bucket.
*
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function drop()
{
$this->collectionWrapper->dropCollections();
}
/**
* Finds documents from the GridFS bucket's files collection matching the
* query.
*
* @see Find::__construct() for supported options
* @param array|object $filter Query by which to filter documents
* @param array $options Additional options
* @return Cursor
* @throws UnsupportedException if options are not supported by the selected server
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function find($filter = [], array $options = [])
{
return $this->collectionWrapper->findFiles($filter, $options);
}
/**
* Finds a single document from the GridFS bucket's files collection
* matching the query.
*
* @see FindOne::__construct() for supported options
* @param array|object $filter Query by which to filter documents
* @param array $options Additional options
* @return array|object|null
* @throws UnsupportedException if options are not supported by the selected server
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function findOne($filter = [], array $options = [])
{
return $this->collectionWrapper->findOneFile($filter, $options);
}
/**
* Return the bucket name.
*
* @return string
*/
public function getBucketName()
{
return $this->bucketName;
}
/**
* Return the chunks collection.
*
* @return Collection
*/
public function getChunksCollection()
{
return $this->collectionWrapper->getChunksCollection();
}
/**
* Return the chunk size in bytes.
*
* @return integer
*/
public function getChunkSizeBytes()
{
return $this->chunkSizeBytes;
}
/**
* Return the database name.
*
* @return string
*/
public function getDatabaseName()
{
return $this->databaseName;
}
/**
* Gets the file document of the GridFS file associated with a stream.
*
* @param resource $stream GridFS stream
* @return array|object
* @throws InvalidArgumentException if $stream is not a GridFS stream
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function getFileDocumentForStream($stream)
{
$file = $this->getRawFileDocumentForStream($stream);
// Filter the raw document through the specified type map
return apply_type_map_to_document($file, $this->typeMap);
}
/**
* Gets the file document's ID of the GridFS file associated with a stream.
*
* @param resource $stream GridFS stream
* @return mixed
* @throws CorruptFileException if the file "_id" field does not exist
* @throws InvalidArgumentException if $stream is not a GridFS stream
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function getFileIdForStream($stream)
{
$file = $this->getRawFileDocumentForStream($stream);
/* Filter the raw document through the specified type map, but override
* the root type so we can reliably access the ID.
*/
$typeMap = ['root' => 'stdClass'] + $this->typeMap;
$file = apply_type_map_to_document($file, $typeMap);
if (! isset($file->_id) && ! property_exists($file, '_id')) {
throw new CorruptFileException('file._id does not exist');
}
return $file->_id;
}
/**
* Return the files collection.
*
* @return Collection
*/
public function getFilesCollection()
{
return $this->collectionWrapper->getFilesCollection();
}
/**
* Return the read concern for this GridFS bucket.
*
* @see http://php.net/manual/en/mongodb-driver-readconcern.isdefault.php
* @return ReadConcern
*/
public function getReadConcern()
{
return $this->readConcern;
}
/**
* Return the read preference for this GridFS bucket.
*
* @return ReadPreference
*/
public function getReadPreference()
{
return $this->readPreference;
}
/**
* Return the type map for this GridFS bucket.
*
* @return array
*/
public function getTypeMap()
{
return $this->typeMap;
}
/**
* Return the write concern for this GridFS bucket.
*
* @see http://php.net/manual/en/mongodb-driver-writeconcern.isdefault.php
* @return WriteConcern
*/
public function getWriteConcern()
{
return $this->writeConcern;
}
/**
* Opens a readable stream for reading a GridFS file.
*
* @param mixed $id File ID
* @return resource
* @throws FileNotFoundException if no file could be selected
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function openDownloadStream($id)
{
$file = $this->collectionWrapper->findFileById($id);
if ($file === null) {
throw FileNotFoundException::byId($id, $this->getFilesNamespace());
}
return $this->openDownloadStreamByFile($file);
}
/**
* Opens a readable stream stream to read a GridFS file, which is selected
* by name and revision.
*
* Supported options:
*
* * revision (integer): Which revision (i.e. documents with the same
* filename and different uploadDate) of the file to retrieve. Defaults
* to -1 (i.e. the most recent revision).
*
* Revision numbers are defined as follows:
*
* * 0 = the original stored file
* * 1 = the first revision
* * 2 = the second revision
* * etc…
* * -2 = the second most recent revision
* * -1 = the most recent revision
*
* @param string $filename Filename
* @param array $options Download options
* @return resource
* @throws FileNotFoundException if no file could be selected
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function openDownloadStreamByName($filename, array $options = [])
{
$options += ['revision' => -1];
$file = $this->collectionWrapper->findFileByFilenameAndRevision($filename, $options['revision']);
if ($file === null) {
throw FileNotFoundException::byFilenameAndRevision($filename, $options['revision'], $this->getFilesNamespace());
}
return $this->openDownloadStreamByFile($file);
}
/**
* Opens a writable stream for writing a GridFS file.
*
* Supported options:
*
* * _id (mixed): File document identifier. Defaults to a new ObjectId.
*
* * chunkSizeBytes (integer): The chunk size in bytes. Defaults to the
* bucket's chunk size.
*
* * disableMD5 (boolean): When true, no MD5 sum will be generated for
* the stored file. Defaults to "false".
*
* * metadata (document): User data for the "metadata" field of the files
* collection document.
*
* @param string $filename Filename
* @param array $options Upload options
* @return resource
*/
public function openUploadStream($filename, array $options = [])
{
$options += ['chunkSizeBytes' => $this->chunkSizeBytes];
$path = $this->createPathForUpload();
$context = stream_context_create([
self::$streamWrapperProtocol => [
'collectionWrapper' => $this->collectionWrapper,
'filename' => $filename,
'options' => $options,
],
]);
return fopen($path, 'w', false, $context);
}
/**
* Renames the GridFS file with the specified ID.
*
* @param mixed $id File ID
* @param string $newFilename New filename
* @throws FileNotFoundException if no file could be selected
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function rename($id, $newFilename)
{
$updateResult = $this->collectionWrapper->updateFilenameForId($id, $newFilename);
if ($updateResult->getModifiedCount() === 1) {
return;
}
/* If the update resulted in no modification, it's possible that the
* file did not exist, in which case we must raise an error. Checking
* the write result's matched count will be most efficient, but fall
* back to a findOne operation if necessary (i.e. legacy writes).
*/
$found = $updateResult->getMatchedCount() !== null
? $updateResult->getMatchedCount() === 1
: $this->collectionWrapper->findFileById($id) !== null;
if (! $found) {
throw FileNotFoundException::byId($id, $this->getFilesNamespace());
}
}
/**
* Writes the contents of a readable stream to a GridFS file.
*
* Supported options:
*
* * _id (mixed): File document identifier. Defaults to a new ObjectId.
*
* * chunkSizeBytes (integer): The chunk size in bytes. Defaults to the
* bucket's chunk size.
*
* * disableMD5 (boolean): When true, no MD5 sum will be generated for
* the stored file. Defaults to "false".
*
* * metadata (document): User data for the "metadata" field of the files
* collection document.
*
* @param string $filename Filename
* @param resource $source Readable stream
* @param array $options Stream options
* @return mixed ID of the newly created GridFS file
* @throws InvalidArgumentException if $source is not a GridFS stream
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function uploadFromStream($filename, $source, array $options = [])
{
if (! is_resource($source) || get_resource_type($source) != "stream") {
throw InvalidArgumentException::invalidType('$source', $source, 'resource');
}
$destination = $this->openUploadStream($filename, $options);
stream_copy_to_stream($source, $destination);
return $this->getFileIdForStream($destination);
}
/**
* Creates a path for an existing GridFS file.
*
* @param stdClass $file GridFS file document
* @return string
*/
private function createPathForFile(stdClass $file)
{
if (! is_object($file->_id) || method_exists($file->_id, '__toString')) {
$id = (string) $file->_id;
} else {
$id = toJSON(fromPHP(['_id' => $file->_id]));
}
return sprintf(
'%s://%s/%s.files/%s',
self::$streamWrapperProtocol,
urlencode($this->databaseName),
urlencode($this->bucketName),
urlencode($id)
);
}
/**
* Creates a path for a new GridFS file, which does not yet have an ID.
*
* @return string
*/
private function createPathForUpload()
{
return sprintf(
'%s://%s/%s.files',
self::$streamWrapperProtocol,
urlencode($this->databaseName),
urlencode($this->bucketName)
);
}
/**
* Returns the names of the files collection.
*
* @return string
*/
private function getFilesNamespace()
{
return sprintf('%s.%s.files', $this->databaseName, $this->bucketName);
}
/**
* Gets the file document of the GridFS file associated with a stream.
*
* This returns the raw document from the StreamWrapper, which does not
* respect the Bucket's type map.
*
* @param resource $stream GridFS stream
* @return stdClass
* @throws InvalidArgumentException
*/
private function getRawFileDocumentForStream($stream)
{
if (! is_resource($stream) || get_resource_type($stream) != "stream") {
throw InvalidArgumentException::invalidType('$stream', $stream, 'resource');
}
$metadata = stream_get_meta_data($stream);
if (! isset($metadata['wrapper_data']) || ! $metadata['wrapper_data'] instanceof StreamWrapper) {
throw InvalidArgumentException::invalidType('$stream wrapper data', $metadata['wrapper_data'] ?? null, StreamWrapper::class);
}
return $metadata['wrapper_data']->getFile();
}
/**
* Opens a readable stream for the GridFS file.
*
* @param stdClass $file GridFS file document
* @return resource
*/
private function openDownloadStreamByFile(stdClass $file)
{
$path = $this->createPathForFile($file);
$context = stream_context_create([
self::$streamWrapperProtocol => [
'collectionWrapper' => $this->collectionWrapper,
'file' => $file,
],
]);
return fopen($path, 'r', false, $context);
}
/**
* Registers the GridFS stream wrapper if it is not already registered.
*/
private function registerStreamWrapper()
{
if (in_array(self::$streamWrapperProtocol, stream_get_wrappers())) {
return;
}
StreamWrapper::register(self::$streamWrapperProtocol);
}
}
src/GridFS/StreamWrapper.php 0000666 00000021362 13645314021 0011765 0 ustar 00 stream->getFile();
}
/**
* Register the GridFS stream wrapper.
*
* @param string $protocol Protocol to use for stream_wrapper_register()
*/
public static function register($protocol = 'gridfs')
{
if (in_array($protocol, stream_get_wrappers())) {
stream_wrapper_unregister($protocol);
}
stream_wrapper_register($protocol, static::class, STREAM_IS_URL);
}
/**
* Closes the stream.
*
* @see http://php.net/manual/en/streamwrapper.stream-close.php
*/
public function stream_close()
{
$this->stream->close();
}
/**
* Returns whether the file pointer is at the end of the stream.
*
* @see http://php.net/manual/en/streamwrapper.stream-eof.php
* @return boolean
*/
public function stream_eof()
{
if (! $this->stream instanceof ReadableStream) {
return false;
}
return $this->stream->isEOF();
}
/**
* Opens the stream.
*
* @see http://php.net/manual/en/streamwrapper.stream-open.php
* @param string $path Path to the file resource
* @param string $mode Mode used to open the file (only "r" and "w" are supported)
* @param integer $options Additional flags set by the streams API
* @param string $openedPath Not used
* @return boolean
*/
public function stream_open($path, $mode, $options, &$openedPath)
{
$this->initProtocol($path);
$this->mode = $mode;
if ($mode === 'r') {
return $this->initReadableStream();
}
if ($mode === 'w') {
return $this->initWritableStream();
}
return false;
}
/**
* Read bytes from the stream.
*
* Note: this method may return a string smaller than the requested length
* if data is not available to be read.
*
* @see http://php.net/manual/en/streamwrapper.stream-read.php
* @param integer $length Number of bytes to read
* @return string
*/
public function stream_read($length)
{
if (! $this->stream instanceof ReadableStream) {
return '';
}
try {
return $this->stream->readBytes($length);
} catch (Throwable $e) {
trigger_error(sprintf('%s: %s', get_class($e), $e->getMessage()), E_USER_WARNING);
return false;
}
}
/**
* Return the current position of the stream.
*
* @see http://php.net/manual/en/streamwrapper.stream-seek.php
* @param integer $offset Stream offset to seek to
* @param integer $whence One of SEEK_SET, SEEK_CUR, or SEEK_END
* @return boolean True if the position was updated and false otherwise
*/
public function stream_seek($offset, $whence = SEEK_SET)
{
$size = $this->stream->getSize();
if ($whence === SEEK_CUR) {
$offset += $this->stream->tell();
}
if ($whence === SEEK_END) {
$offset += $size;
}
// WritableStreams are always positioned at the end of the stream
if ($this->stream instanceof WritableStream) {
return $offset === $size;
}
if ($offset < 0 || $offset > $size) {
return false;
}
$this->stream->seek($offset);
return true;
}
/**
* Return information about the stream.
*
* @see http://php.net/manual/en/streamwrapper.stream-stat.php
* @return array
*/
public function stream_stat()
{
$stat = $this->getStatTemplate();
$stat[2] = $stat['mode'] = $this->stream instanceof ReadableStream
? 0100444 // S_IFREG & S_IRUSR & S_IRGRP & S_IROTH
: 0100222; // S_IFREG & S_IWUSR & S_IWGRP & S_IWOTH
$stat[7] = $stat['size'] = $this->stream->getSize();
$file = $this->stream->getFile();
if (isset($file->uploadDate) && $file->uploadDate instanceof UTCDateTime) {
$timestamp = $file->uploadDate->toDateTime()->getTimestamp();
$stat[9] = $stat['mtime'] = $timestamp;
$stat[10] = $stat['ctime'] = $timestamp;
}
if (isset($file->chunkSize) && is_integer($file->chunkSize)) {
$stat[11] = $stat['blksize'] = $file->chunkSize;
}
return $stat;
}
/**
* Return the current position of the stream.
*
* @see http://php.net/manual/en/streamwrapper.stream-tell.php
* @return integer The current position of the stream
*/
public function stream_tell()
{
return $this->stream->tell();
}
/**
* Write bytes to the stream.
*
* @see http://php.net/manual/en/streamwrapper.stream-write.php
* @param string $data Data to write
* @return integer The number of bytes written
*/
public function stream_write($data)
{
if (! $this->stream instanceof WritableStream) {
return 0;
}
try {
return $this->stream->writeBytes($data);
} catch (Throwable $e) {
trigger_error(sprintf('%s: %s', get_class($e), $e->getMessage()), E_USER_WARNING);
return false;
}
}
/**
* Returns a stat template with default values.
*
* @return array
*/
private function getStatTemplate()
{
return [
// phpcs:disable Squiz.Arrays.ArrayDeclaration.IndexNoNewline
0 => 0, 'dev' => 0,
1 => 0, 'ino' => 0,
2 => 0, 'mode' => 0,
3 => 0, 'nlink' => 0,
4 => 0, 'uid' => 0,
5 => 0, 'gid' => 0,
6 => -1, 'rdev' => -1,
7 => 0, 'size' => 0,
8 => 0, 'atime' => 0,
9 => 0, 'mtime' => 0,
10 => 0, 'ctime' => 0,
11 => -1, 'blksize' => -1,
12 => -1, 'blocks' => -1,
// phpcs:enable
];
}
/**
* Initialize the protocol from the given path.
*
* @see StreamWrapper::stream_open()
* @param string $path
*/
private function initProtocol($path)
{
$parts = explode('://', $path, 2);
$this->protocol = $parts[0] ?: 'gridfs';
}
/**
* Initialize the internal stream for reading.
*
* @see StreamWrapper::stream_open()
* @return boolean
*/
private function initReadableStream()
{
$context = stream_context_get_options($this->context);
$this->stream = new ReadableStream(
$context[$this->protocol]['collectionWrapper'],
$context[$this->protocol]['file']
);
return true;
}
/**
* Initialize the internal stream for writing.
*
* @see StreamWrapper::stream_open()
* @return boolean
*/
private function initWritableStream()
{
$context = stream_context_get_options($this->context);
$this->stream = new WritableStream(
$context[$this->protocol]['collectionWrapper'],
$context[$this->protocol]['filename'],
$context[$this->protocol]['options']
);
return true;
}
}
src/GridFS/ReadableStream.php 0000666 00000022243 13645314021 0012043 0 ustar 00 chunkSize) || ! is_integer($file->chunkSize) || $file->chunkSize < 1) {
throw new CorruptFileException('file.chunkSize is not an integer >= 1');
}
if (! isset($file->length) || ! is_integer($file->length) || $file->length < 0) {
throw new CorruptFileException('file.length is not an integer > 0');
}
if (! isset($file->_id) && ! property_exists($file, '_id')) {
throw new CorruptFileException('file._id does not exist');
}
$this->file = $file;
$this->chunkSize = (integer) $file->chunkSize;
$this->length = (integer) $file->length;
$this->collectionWrapper = $collectionWrapper;
if ($this->length > 0) {
$this->numChunks = (integer) ceil($this->length / $this->chunkSize);
$this->expectedLastChunkSize = ($this->length - (($this->numChunks - 1) * $this->chunkSize));
}
}
/**
* Return internal properties for debugging purposes.
*
* @see http://php.net/manual/en/language.oop5.magic.php#language.oop5.magic.debuginfo
* @return array
*/
public function __debugInfo()
{
return [
'bucketName' => $this->collectionWrapper->getBucketName(),
'databaseName' => $this->collectionWrapper->getDatabaseName(),
'file' => $this->file,
];
}
public function close()
{
// Nothing to do
}
/**
* Return the stream's file document.
*
* @return stdClass
*/
public function getFile()
{
return $this->file;
}
/**
* Return the stream's size in bytes.
*
* @return integer
*/
public function getSize()
{
return $this->length;
}
/**
* Return whether the current read position is at the end of the stream.
*
* @return boolean
*/
public function isEOF()
{
if ($this->chunkOffset === $this->numChunks - 1) {
return $this->bufferOffset >= $this->expectedLastChunkSize;
}
return $this->chunkOffset >= $this->numChunks;
}
/**
* Read bytes from the stream.
*
* Note: this method may return a string smaller than the requested length
* if data is not available to be read.
*
* @param integer $length Number of bytes to read
* @return string
* @throws InvalidArgumentException if $length is negative
*/
public function readBytes($length)
{
if ($length < 0) {
throw new InvalidArgumentException(sprintf('$length must be >= 0; given: %d', $length));
}
if ($this->chunksIterator === null) {
$this->initChunksIterator();
}
if ($this->buffer === null && ! $this->initBufferFromCurrentChunk()) {
return '';
}
$data = '';
while (strlen($data) < $length) {
if ($this->bufferOffset >= strlen($this->buffer) && ! $this->initBufferFromNextChunk()) {
break;
}
$initialDataLength = strlen($data);
$data .= substr($this->buffer, $this->bufferOffset, $length - $initialDataLength);
$this->bufferOffset += strlen($data) - $initialDataLength;
}
return $data;
}
/**
* Seeks the chunk and buffer offsets for the next read operation.
*
* @param integer $offset
* @throws InvalidArgumentException if $offset is out of range
*/
public function seek($offset)
{
if ($offset < 0 || $offset > $this->file->length) {
throw new InvalidArgumentException(sprintf('$offset must be >= 0 and <= %d; given: %d', $this->file->length, $offset));
}
/* Compute the offsets for the chunk and buffer (i.e. chunk data) from
* which we will expect to read after seeking. If the chunk offset
* changed, we'll also need to reset the buffer.
*/
$lastChunkOffset = $this->chunkOffset;
$this->chunkOffset = (integer) floor($offset / $this->chunkSize);
$this->bufferOffset = $offset % $this->chunkSize;
if ($lastChunkOffset === $this->chunkOffset) {
return;
}
if ($this->chunksIterator === null) {
return;
}
// Clear the buffer since the current chunk will be changed
$this->buffer = null;
/* If we are seeking to a previous chunk, we need to reinitialize the
* chunk iterator.
*/
if ($lastChunkOffset > $this->chunkOffset) {
$this->chunksIterator = null;
return;
}
/* If we are seeking to a subsequent chunk, we do not need to
* reinitalize the chunk iterator. Instead, we can simply move forward
* to $this->chunkOffset.
*/
$numChunks = $this->chunkOffset - $lastChunkOffset;
for ($i = 0; $i < $numChunks; $i++) {
$this->chunksIterator->next();
}
}
/**
* Return the current position of the stream.
*
* This is the offset within the stream where the next byte would be read.
*
* @return integer
*/
public function tell()
{
return ($this->chunkOffset * $this->chunkSize) + $this->bufferOffset;
}
/**
* Initialize the buffer to the current chunk's data.
*
* @return boolean Whether there was a current chunk to read
* @throws CorruptFileException if an expected chunk could not be read successfully
*/
private function initBufferFromCurrentChunk()
{
if ($this->chunkOffset === 0 && $this->numChunks === 0) {
return false;
}
if (! $this->chunksIterator->valid()) {
throw CorruptFileException::missingChunk($this->chunkOffset);
}
$currentChunk = $this->chunksIterator->current();
if ($currentChunk->n !== $this->chunkOffset) {
throw CorruptFileException::unexpectedIndex($currentChunk->n, $this->chunkOffset);
}
$this->buffer = $currentChunk->data->getData();
$actualChunkSize = strlen($this->buffer);
$expectedChunkSize = $this->chunkOffset === $this->numChunks - 1
? $this->expectedLastChunkSize
: $this->chunkSize;
if ($actualChunkSize !== $expectedChunkSize) {
throw CorruptFileException::unexpectedSize($actualChunkSize, $expectedChunkSize);
}
return true;
}
/**
* Advance to the next chunk and initialize the buffer to its data.
*
* @return boolean Whether there was a next chunk to read
* @throws CorruptFileException if an expected chunk could not be read successfully
*/
private function initBufferFromNextChunk()
{
if ($this->chunkOffset === $this->numChunks - 1) {
return false;
}
$this->bufferOffset = 0;
$this->chunkOffset++;
$this->chunksIterator->next();
return $this->initBufferFromCurrentChunk();
}
/**
* Initializes the chunk iterator starting from the current offset.
*/
private function initChunksIterator()
{
$cursor = $this->collectionWrapper->findChunksByFileId($this->file->_id, $this->chunkOffset);
$this->chunksIterator = new IteratorIterator($cursor);
$this->chunksIterator->rewind();
}
}
src/GridFS/CollectionWrapper.php 0000666 00000024757 13645314021 0012640 0 ustar 00 databaseName = (string) $databaseName;
$this->bucketName = (string) $bucketName;
$this->filesCollection = new Collection($manager, $databaseName, sprintf('%s.files', $bucketName), $collectionOptions);
$this->chunksCollection = new Collection($manager, $databaseName, sprintf('%s.chunks', $bucketName), $collectionOptions);
}
/**
* Deletes all GridFS chunks for a given file ID.
*
* @param mixed $id
*/
public function deleteChunksByFilesId($id)
{
$this->chunksCollection->deleteMany(['files_id' => $id]);
}
/**
* Deletes a GridFS file and related chunks by ID.
*
* @param mixed $id
*/
public function deleteFileAndChunksById($id)
{
$this->filesCollection->deleteOne(['_id' => $id]);
$this->chunksCollection->deleteMany(['files_id' => $id]);
}
/**
* Drops the GridFS files and chunks collections.
*/
public function dropCollections()
{
$this->filesCollection->drop(['typeMap' => []]);
$this->chunksCollection->drop(['typeMap' => []]);
}
/**
* Finds GridFS chunk documents for a given file ID and optional offset.
*
* @param mixed $id File ID
* @param integer $fromChunk Starting chunk (inclusive)
* @return Cursor
*/
public function findChunksByFileId($id, $fromChunk = 0)
{
return $this->chunksCollection->find(
[
'files_id' => $id,
'n' => ['$gte' => $fromChunk],
],
[
'sort' => ['n' => 1],
'typeMap' => ['root' => 'stdClass'],
]
);
}
/**
* Finds a GridFS file document for a given filename and revision.
*
* Revision numbers are defined as follows:
*
* * 0 = the original stored file
* * 1 = the first revision
* * 2 = the second revision
* * etc…
* * -2 = the second most recent revision
* * -1 = the most recent revision
*
* @see Bucket::downloadToStreamByName()
* @see Bucket::openDownloadStreamByName()
* @param string $filename
* @param integer $revision
* @return stdClass|null
*/
public function findFileByFilenameAndRevision($filename, $revision)
{
$filename = (string) $filename;
$revision = (integer) $revision;
if ($revision < 0) {
$skip = abs($revision) - 1;
$sortOrder = -1;
} else {
$skip = $revision;
$sortOrder = 1;
}
return $this->filesCollection->findOne(
['filename' => $filename],
[
'skip' => $skip,
'sort' => ['uploadDate' => $sortOrder],
'typeMap' => ['root' => 'stdClass'],
]
);
}
/**
* Finds a GridFS file document for a given ID.
*
* @param mixed $id
* @return stdClass|null
*/
public function findFileById($id)
{
return $this->filesCollection->findOne(
['_id' => $id],
['typeMap' => ['root' => 'stdClass']]
);
}
/**
* Finds documents from the GridFS bucket's files collection.
*
* @see Find::__construct() for supported options
* @param array|object $filter Query by which to filter documents
* @param array $options Additional options
* @return Cursor
*/
public function findFiles($filter, array $options = [])
{
return $this->filesCollection->find($filter, $options);
}
/**
* Finds a single document from the GridFS bucket's files collection.
*
* @param array|object $filter Query by which to filter documents
* @param array $options Additional options
* @return array|object|null
*/
public function findOneFile($filter, array $options = [])
{
return $this->filesCollection->findOne($filter, $options);
}
/**
* Return the bucket name.
*
* @return string
*/
public function getBucketName()
{
return $this->bucketName;
}
/**
* Return the chunks collection.
*
* @return Collection
*/
public function getChunksCollection()
{
return $this->chunksCollection;
}
/**
* Return the database name.
*
* @return string
*/
public function getDatabaseName()
{
return $this->databaseName;
}
/**
* Return the files collection.
*
* @return Collection
*/
public function getFilesCollection()
{
return $this->filesCollection;
}
/**
* Inserts a document into the chunks collection.
*
* @param array|object $chunk Chunk document
*/
public function insertChunk($chunk)
{
if (! $this->checkedIndexes) {
$this->ensureIndexes();
}
$this->chunksCollection->insertOne($chunk);
}
/**
* Inserts a document into the files collection.
*
* The file document should be inserted after all chunks have been inserted.
*
* @param array|object $file File document
*/
public function insertFile($file)
{
if (! $this->checkedIndexes) {
$this->ensureIndexes();
}
$this->filesCollection->insertOne($file);
}
/**
* Updates the filename field in the file document for a given ID.
*
* @param mixed $id
* @param string $filename
* @return UpdateResult
*/
public function updateFilenameForId($id, $filename)
{
return $this->filesCollection->updateOne(
['_id' => $id],
['$set' => ['filename' => (string) $filename]]
);
}
/**
* Create an index on the chunks collection if it does not already exist.
*/
private function ensureChunksIndex()
{
$expectedIndex = ['files_id' => 1, 'n' => 1];
foreach ($this->chunksCollection->listIndexes() as $index) {
if ($index->isUnique() && $this->indexKeysMatch($expectedIndex, $index->getKey())) {
return;
}
}
$this->chunksCollection->createIndex($expectedIndex, ['unique' => true]);
}
/**
* Create an index on the files collection if it does not already exist.
*/
private function ensureFilesIndex()
{
$expectedIndex = ['filename' => 1, 'uploadDate' => 1];
foreach ($this->filesCollection->listIndexes() as $index) {
if ($this->indexKeysMatch($expectedIndex, $index->getKey())) {
return;
}
}
$this->filesCollection->createIndex($expectedIndex);
}
/**
* Ensure indexes on the files and chunks collections exist.
*
* This method is called once before the first write operation on a GridFS
* bucket. Indexes are only be created if the files collection is empty.
*/
private function ensureIndexes()
{
if ($this->checkedIndexes) {
return;
}
$this->checkedIndexes = true;
if (! $this->isFilesCollectionEmpty()) {
return;
}
$this->ensureFilesIndex();
$this->ensureChunksIndex();
}
private function indexKeysMatch(array $expectedKeys, array $actualKeys) : bool
{
if (count($expectedKeys) !== count($actualKeys)) {
return false;
}
$iterator = new MultipleIterator(MultipleIterator::MIT_NEED_ANY);
$iterator->attachIterator(new ArrayIterator($expectedKeys));
$iterator->attachIterator(new ArrayIterator($actualKeys));
foreach ($iterator as $key => $value) {
list($expectedKey, $actualKey) = $key;
list($expectedValue, $actualValue) = $value;
if ($expectedKey !== $actualKey) {
return false;
}
/* Since we don't expect special indexes (e.g. text), we mark any
* index with a non-numeric definition as unequal. All others are
* compared against their int value to avoid differences due to
* some drivers using float values in the key specification. */
if (! is_numeric($actualValue) || (int) $expectedValue !== (int) $actualValue) {
return false;
}
}
return true;
}
/**
* Returns whether the files collection is empty.
*
* @return boolean
*/
private function isFilesCollectionEmpty()
{
return null === $this->filesCollection->findOne([], [
'readPreference' => new ReadPreference(ReadPreference::RP_PRIMARY),
'projection' => ['_id' => 1],
'typeMap' => [],
]);
}
}
src/GridFS/WritableStream.php 0000666 00000021756 13645314021 0012125 0 ustar 00 new ObjectId(),
'chunkSizeBytes' => self::$defaultChunkSizeBytes,
'disableMD5' => false,
];
if (isset($options['aliases']) && ! is_string_array($options['aliases'])) {
throw InvalidArgumentException::invalidType('"aliases" option', $options['aliases'], 'array of strings');
}
if (! is_integer($options['chunkSizeBytes'])) {
throw InvalidArgumentException::invalidType('"chunkSizeBytes" option', $options['chunkSizeBytes'], 'integer');
}
if ($options['chunkSizeBytes'] < 1) {
throw new InvalidArgumentException(sprintf('Expected "chunkSizeBytes" option to be >= 1, %d given', $options['chunkSizeBytes']));
}
if (! is_bool($options['disableMD5'])) {
throw InvalidArgumentException::invalidType('"disableMD5" option', $options['disableMD5'], 'boolean');
}
if (isset($options['contentType']) && ! is_string($options['contentType'])) {
throw InvalidArgumentException::invalidType('"contentType" option', $options['contentType'], 'string');
}
if (isset($options['metadata']) && ! is_array($options['metadata']) && ! is_object($options['metadata'])) {
throw InvalidArgumentException::invalidType('"metadata" option', $options['metadata'], 'array or object');
}
$this->chunkSize = $options['chunkSizeBytes'];
$this->collectionWrapper = $collectionWrapper;
$this->disableMD5 = $options['disableMD5'];
if (! $this->disableMD5) {
$this->hashCtx = hash_init('md5');
}
$this->file = [
'_id' => $options['_id'],
'chunkSize' => $this->chunkSize,
'filename' => (string) $filename,
] + array_intersect_key($options, ['aliases' => 1, 'contentType' => 1, 'metadata' => 1]);
}
/**
* Return internal properties for debugging purposes.
*
* @see http://php.net/manual/en/language.oop5.magic.php#language.oop5.magic.debuginfo
* @return array
*/
public function __debugInfo()
{
return [
'bucketName' => $this->collectionWrapper->getBucketName(),
'databaseName' => $this->collectionWrapper->getDatabaseName(),
'file' => $this->file,
];
}
/**
* Closes an active stream and flushes all buffered data to GridFS.
*/
public function close()
{
if ($this->isClosed) {
// TODO: Should this be an error condition? e.g. BadMethodCallException
return;
}
if (strlen($this->buffer) > 0) {
$this->insertChunkFromBuffer();
}
$this->fileCollectionInsert();
$this->isClosed = true;
}
/**
* Return the stream's file document.
*
* @return stdClass
*/
public function getFile()
{
return (object) $this->file;
}
/**
* Return the stream's size in bytes.
*
* Note: this value will increase as more data is written to the stream.
*
* @return integer
*/
public function getSize()
{
return $this->length + strlen($this->buffer);
}
/**
* Return the current position of the stream.
*
* This is the offset within the stream where the next byte would be
* written. Since seeking is not supported and writes are appended, this is
* always the end of the stream.
*
* @see WritableStream::getSize()
* @return integer
*/
public function tell()
{
return $this->getSize();
}
/**
* Inserts binary data into GridFS via chunks.
*
* Data will be buffered internally until chunkSizeBytes are accumulated, at
* which point a chunk document will be inserted and the buffer reset.
*
* @param string $data Binary data to write
* @return integer
*/
public function writeBytes($data)
{
if ($this->isClosed) {
// TODO: Should this be an error condition? e.g. BadMethodCallException
return;
}
$bytesRead = 0;
while ($bytesRead != strlen($data)) {
$initialBufferLength = strlen($this->buffer);
$this->buffer .= substr($data, $bytesRead, $this->chunkSize - $initialBufferLength);
$bytesRead += strlen($this->buffer) - $initialBufferLength;
if (strlen($this->buffer) == $this->chunkSize) {
$this->insertChunkFromBuffer();
}
}
return $bytesRead;
}
private function abort()
{
try {
$this->collectionWrapper->deleteChunksByFilesId($this->file['_id']);
} catch (DriverRuntimeException $e) {
// We are already handling an error if abort() is called, so suppress this
}
$this->isClosed = true;
}
private function fileCollectionInsert()
{
$this->file['length'] = $this->length;
$this->file['uploadDate'] = new UTCDateTime();
if (! $this->disableMD5) {
$this->file['md5'] = hash_final($this->hashCtx);
}
try {
$this->collectionWrapper->insertFile($this->file);
} catch (DriverRuntimeException $e) {
$this->abort();
throw $e;
}
return $this->file['_id'];
}
private function insertChunkFromBuffer()
{
if (strlen($this->buffer) == 0) {
return;
}
$data = $this->buffer;
$this->buffer = '';
$chunk = [
'files_id' => $this->file['_id'],
'n' => $this->chunkOffset,
'data' => new Binary($data, Binary::TYPE_GENERIC),
];
if (! $this->disableMD5) {
hash_update($this->hashCtx, $data);
}
try {
$this->collectionWrapper->insertChunk($chunk);
} catch (DriverRuntimeException $e) {
$this->abort();
throw $e;
}
$this->length += strlen($data);
$this->chunkOffset++;
}
}
src/GridFS/Exception/CorruptFileException.php 0000666 00000003577 13645314021 0015254 0 ustar 00 $id]));
return new static(sprintf('File "%s" not found in "%s"', $json, $namespace));
}
}
src/BulkWriteResult.php 0000666 00000013325 13645314021 0011162 0 ustar 00 writeResult = $writeResult;
$this->insertedIds = $insertedIds;
$this->isAcknowledged = $writeResult->isAcknowledged();
}
/**
* Return the number of documents that were deleted.
*
* This method should only be called if the write was acknowledged.
*
* @see BulkWriteResult::isAcknowledged()
* @return integer
* @throws BadMethodCallException is the write result is unacknowledged
*/
public function getDeletedCount()
{
if ($this->isAcknowledged) {
return $this->writeResult->getDeletedCount();
}
throw BadMethodCallException::unacknowledgedWriteResultAccess(__METHOD__);
}
/**
* Return the number of documents that were inserted.
*
* This method should only be called if the write was acknowledged.
*
* @see BulkWriteResult::isAcknowledged()
* @return integer
* @throws BadMethodCallException is the write result is unacknowledged
*/
public function getInsertedCount()
{
if ($this->isAcknowledged) {
return $this->writeResult->getInsertedCount();
}
throw BadMethodCallException::unacknowledgedWriteResultAccess(__METHOD__);
}
/**
* Return a map of the inserted documents' IDs.
*
* The index of each ID in the map corresponds to each document's position
* in the bulk operation. If a document had an ID prior to inserting (i.e.
* the driver did not generate an ID), the index will contain its "_id"
* field value. Any driver-generated ID will be a MongoDB\BSON\ObjectId
* instance.
*
* @return mixed[]
*/
public function getInsertedIds()
{
return $this->insertedIds;
}
/**
* Return the number of documents that were matched by the filter.
*
* This method should only be called if the write was acknowledged.
*
* @see BulkWriteResult::isAcknowledged()
* @return integer
* @throws BadMethodCallException is the write result is unacknowledged
*/
public function getMatchedCount()
{
if ($this->isAcknowledged) {
return $this->writeResult->getMatchedCount();
}
throw BadMethodCallException::unacknowledgedWriteResultAccess(__METHOD__);
}
/**
* Return the number of documents that were modified.
*
* This value is undefined (i.e. null) if the write executed as a legacy
* operation instead of command.
*
* This method should only be called if the write was acknowledged.
*
* @see BulkWriteResult::isAcknowledged()
* @return integer|null
* @throws BadMethodCallException is the write result is unacknowledged
*/
public function getModifiedCount()
{
if ($this->isAcknowledged) {
return $this->writeResult->getModifiedCount();
}
throw BadMethodCallException::unacknowledgedWriteResultAccess(__METHOD__);
}
/**
* Return the number of documents that were upserted.
*
* This method should only be called if the write was acknowledged.
*
* @see BulkWriteResult::isAcknowledged()
* @return integer
* @throws BadMethodCallException is the write result is unacknowledged
*/
public function getUpsertedCount()
{
if ($this->isAcknowledged) {
return $this->writeResult->getUpsertedCount();
}
throw BadMethodCallException::unacknowledgedWriteResultAccess(__METHOD__);
}
/**
* Return a map of the upserted documents' IDs.
*
* The index of each ID in the map corresponds to each document's position
* in bulk operation. If a document had an ID prior to upserting (i.e. the
* server did not need to generate an ID), this will contain its "_id". Any
* server-generated ID will be a MongoDB\BSON\ObjectId instance.
*
* This method should only be called if the write was acknowledged.
*
* @see BulkWriteResult::isAcknowledged()
* @return mixed[]
* @throws BadMethodCallException is the write result is unacknowledged
*/
public function getUpsertedIds()
{
if ($this->isAcknowledged) {
return $this->writeResult->getUpsertedIds();
}
throw BadMethodCallException::unacknowledgedWriteResultAccess(__METHOD__);
}
/**
* Return whether this update was acknowledged by the server.
*
* If the update was not acknowledged, other fields from the WriteResult
* (e.g. matchedCount) will be undefined.
*
* @return boolean
*/
public function isAcknowledged()
{
return $this->isAcknowledged;
}
}
src/InsertManyResult.php 0000666 00000005224 13645314021 0011342 0 ustar 00 writeResult = $writeResult;
$this->insertedIds = $insertedIds;
$this->isAcknowledged = $writeResult->isAcknowledged();
}
/**
* Return the number of documents that were inserted.
*
* This method should only be called if the write was acknowledged.
*
* @see InsertManyResult::isAcknowledged()
* @return integer
* @throws BadMethodCallException is the write result is unacknowledged
*/
public function getInsertedCount()
{
if ($this->isAcknowledged) {
return $this->writeResult->getInsertedCount();
}
throw BadMethodCallException::unacknowledgedWriteResultAccess(__METHOD__);
}
/**
* Return a map of the inserted documents' IDs.
*
* The index of each ID in the map corresponds to each document's position
* in the bulk operation. If a document had an ID prior to inserting (i.e.
* the driver did not generate an ID), the index will contain its "_id"
* field value. Any driver-generated ID will be a MongoDB\BSON\ObjectId
* instance.
*
* @return mixed[]
*/
public function getInsertedIds()
{
return $this->insertedIds;
}
/**
* Return whether this insert result was acknowledged by the server.
*
* If the insert was not acknowledged, other fields from the WriteResult
* (e.g. insertedCount) will be undefined.
*
* @return boolean
*/
public function isAcknowledged()
{
return $this->writeResult->isAcknowledged();
}
}
src/ChangeStream.php 0000666 00000016370 13645314021 0010417 0 ustar 00 iterator = $iterator;
$this->resumeCallable = $resumeCallable;
}
/**
* @see http://php.net/iterator.current
* @return mixed
*/
public function current()
{
return $this->iterator->current();
}
/**
* @return CursorId
*/
public function getCursorId()
{
return $this->iterator->getInnerIterator()->getId();
}
/**
* Returns the resume token for the iterator's current position.
*
* Null may be returned if no change documents have been iterated and the
* server did not include a postBatchResumeToken in its aggregate or getMore
* command response.
*
* @return array|object|null
*/
public function getResumeToken()
{
return $this->iterator->getResumeToken();
}
/**
* @see http://php.net/iterator.key
* @return mixed
*/
public function key()
{
if ($this->valid()) {
return $this->key;
}
return null;
}
/**
* @see http://php.net/iterator.next
* @return void
* @throws ResumeTokenException
*/
public function next()
{
try {
$this->iterator->next();
$this->onIteration($this->hasAdvanced);
} catch (RuntimeException $e) {
$this->resumeOrThrow($e);
}
}
/**
* @see http://php.net/iterator.rewind
* @return void
* @throws ResumeTokenException
*/
public function rewind()
{
try {
$this->iterator->rewind();
/* Unlike next() and resume(), the decision to increment the key
* does not depend on whether the change stream has advanced. This
* ensures that multiple calls to rewind() do not alter state. */
$this->onIteration(false);
} catch (RuntimeException $e) {
$this->resumeOrThrow($e);
}
}
/**
* @see http://php.net/iterator.valid
* @return boolean
*/
public function valid()
{
return $this->iterator->valid();
}
/**
* Determines if an exception is a resumable error.
*
* @see https://github.com/mongodb/specifications/blob/master/source/change-streams/change-streams.rst#resumable-error
* @param RuntimeException $exception
* @return boolean
*/
private function isResumableError(RuntimeException $exception)
{
if ($exception instanceof ConnectionException) {
return true;
}
if (! $exception instanceof ServerException) {
return false;
}
if (server_supports_feature($this->iterator->getServer(), self::$wireVersionForResumableChangeStreamError)) {
return $exception->hasErrorLabel('ResumableChangeStreamError');
}
return in_array($exception->getCode(), self::$resumableErrorCodes);
}
/**
* Perform housekeeping after an iteration event.
*
* @param boolean $incrementKey Increment $key if there is a current result
* @throws ResumeTokenException
*/
private function onIteration($incrementKey)
{
/* If the cursorId is 0, the server has invalidated the cursor and we
* will never perform another getMore nor need to resume since any
* remaining results (up to and including the invalidate event) will
* have been received in the last response. Therefore, we can unset the
* resumeCallable. This will free any reference to Watch as well as the
* only reference to any implicit session created therein. */
if ((string) $this->getCursorId() === '0') {
$this->resumeCallable = null;
}
/* Return early if there is not a current result. Avoid any attempt to
* increment the iterator's key. */
if (! $this->valid()) {
return;
}
if ($incrementKey) {
$this->key++;
}
$this->hasAdvanced = true;
}
/**
* Recreates the ChangeStreamIterator after a resumable server error.
*
* @return void
*/
private function resume()
{
$this->iterator = call_user_func($this->resumeCallable, $this->getResumeToken(), $this->hasAdvanced);
$this->iterator->rewind();
$this->onIteration($this->hasAdvanced);
}
/**
* Either resumes after a resumable error or re-throws the exception.
*
* @param RuntimeException $exception
* @throws RuntimeException
*/
private function resumeOrThrow(RuntimeException $exception)
{
if ($this->isResumableError($exception)) {
$this->resume();
return;
}
throw $exception;
}
}
src/Operation/Explainable.php 0000666 00000001604 13645314021 0012234 0 ustar 00 options = $options;
}
/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return DatabaseInfoIterator
* @throws UnexpectedValueException if the command response was malformed
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
$cmd = ['listDatabases' => 1];
if (! empty($this->options['filter'])) {
$cmd['filter'] = (object) $this->options['filter'];
}
if (isset($this->options['maxTimeMS'])) {
$cmd['maxTimeMS'] = $this->options['maxTimeMS'];
}
$cursor = $server->executeReadCommand('admin', new Command($cmd), $this->createOptions());
$cursor->setTypeMap(['root' => 'array', 'document' => 'array']);
$result = current($cursor->toArray());
if (! isset($result['databases']) || ! is_array($result['databases'])) {
throw new UnexpectedValueException('listDatabases command did not return a "databases" array');
}
/* Return an Iterator instead of an array in case listDatabases is
* eventually changed to return a command cursor, like the collection
* and index enumeration commands. This makes the "totalSize" command
* field inaccessible, but users can manually invoke the command if they
* need that value.
*/
return new DatabaseInfoLegacyIterator($result['databases']);
}
/**
* Create options for executing the command.
*
* Note: read preference is intentionally omitted, as the spec requires that
* the command be executed on the primary.
*
* @see http://php.net/manual/en/mongodb-driver-server.executecommand.php
* @return array
*/
private function createOptions()
{
$options = [];
if (isset($this->options['session'])) {
$options['session'] = $this->options['session'];
}
return $options;
}
}
src/Operation/Explain.php 0000666 00000012151 13645314021 0011407 0 ustar 00 databaseName = $databaseName;
$this->explainable = $explainable;
$this->options = $options;
}
public function execute(Server $server)
{
if ($this->explainable instanceof Distinct && ! server_supports_feature($server, self::$wireVersionForDistinct)) {
throw UnsupportedException::explainNotSupported();
}
if ($this->isFindAndModify($this->explainable) && ! server_supports_feature($server, self::$wireVersionForFindAndModify)) {
throw UnsupportedException::explainNotSupported();
}
$cmd = ['explain' => $this->explainable->getCommandDocument($server)];
if (isset($this->options['verbosity'])) {
$cmd['verbosity'] = $this->options['verbosity'];
}
$cursor = $server->executeCommand($this->databaseName, new Command($cmd), $this->createOptions());
if (isset($this->options['typeMap'])) {
$cursor->setTypeMap($this->options['typeMap']);
}
return current($cursor->toArray());
}
/**
* Create options for executing the command.
*
* @see http://php.net/manual/en/mongodb-driver-server.executecommand.php
* @return array
*/
private function createOptions()
{
$options = [];
if (isset($this->options['readPreference'])) {
$options['readPreference'] = $this->options['readPreference'];
}
if (isset($this->options['session'])) {
$options['session'] = $this->options['session'];
}
return $options;
}
private function isFindAndModify($explainable)
{
if ($explainable instanceof FindAndModify || $explainable instanceof FindOneAndDelete || $explainable instanceof FindOneAndReplace || $explainable instanceof FindOneAndUpdate) {
return true;
}
return false;
}
}
src/Operation/MapReduce.php 0000666 00000044400 13645314021 0011656 0 ustar 00 isDefault()) {
unset($options['readConcern']);
}
if (isset($options['writeConcern']) && $options['writeConcern']->isDefault()) {
unset($options['writeConcern']);
}
// Handle deprecation of CodeWScope
if ($map->getScope() !== null) {
@trigger_error('Use of Javascript with scope in "$map" argument for MapReduce is deprecated. Put all scope variables in the "scope" option of the MapReduce operation.', E_USER_DEPRECATED);
}
if ($reduce->getScope() !== null) {
@trigger_error('Use of Javascript with scope in "$reduce" argument for MapReduce is deprecated. Put all scope variables in the "scope" option of the MapReduce operation.', E_USER_DEPRECATED);
}
if (isset($options['finalize']) && $options['finalize']->getScope() !== null) {
@trigger_error('Use of Javascript with scope in "finalize" option for MapReduce is deprecated. Put all scope variables in the "scope" option of the MapReduce operation.', E_USER_DEPRECATED);
}
$this->checkOutDeprecations($out);
$this->databaseName = (string) $databaseName;
$this->collectionName = (string) $collectionName;
$this->map = $map;
$this->reduce = $reduce;
$this->out = $out;
$this->options = $options;
}
/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return MapReduceResult
* @throws UnexpectedValueException if the command response was malformed
* @throws UnsupportedException if collation, read concern, or write concern is used and unsupported
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
if (isset($this->options['collation']) && ! server_supports_feature($server, self::$wireVersionForCollation)) {
throw UnsupportedException::collationNotSupported();
}
if (isset($this->options['readConcern']) && ! server_supports_feature($server, self::$wireVersionForReadConcern)) {
throw UnsupportedException::readConcernNotSupported();
}
if (isset($this->options['writeConcern']) && ! server_supports_feature($server, self::$wireVersionForWriteConcern)) {
throw UnsupportedException::writeConcernNotSupported();
}
$inTransaction = isset($this->options['session']) && $this->options['session']->isInTransaction();
if ($inTransaction) {
if (isset($this->options['readConcern'])) {
throw UnsupportedException::readConcernNotSupportedInTransaction();
}
if (isset($this->options['writeConcern'])) {
throw UnsupportedException::writeConcernNotSupportedInTransaction();
}
}
$hasOutputCollection = ! is_mapreduce_output_inline($this->out);
$command = $this->createCommand($server);
$options = $this->createOptions($hasOutputCollection);
/* If the mapReduce operation results in a write, use
* executeReadWriteCommand to ensure we're handling the writeConcern
* option.
* In other cases, we use executeCommand as this will prevent the
* mapReduce operation from being retried when retryReads is enabled.
* See https://github.com/mongodb/specifications/blob/master/source/retryable-reads/retryable-reads.rst#unsupported-read-operations. */
$cursor = $hasOutputCollection
? $server->executeReadWriteCommand($this->databaseName, $command, $options)
: $server->executeCommand($this->databaseName, $command, $options);
if (isset($this->options['typeMap']) && ! $hasOutputCollection) {
$cursor->setTypeMap(create_field_path_type_map($this->options['typeMap'], 'results.$'));
}
$result = current($cursor->toArray());
$getIterator = $this->createGetIteratorCallable($result, $server);
return new MapReduceResult($getIterator, $result);
}
/**
* @param string|array|object $out
* @return void
*/
private function checkOutDeprecations($out)
{
if (is_string($out)) {
return;
}
$out = (array) $out;
if (isset($out['nonAtomic']) && ! $out['nonAtomic']) {
@trigger_error('Specifying false for "out.nonAtomic" is deprecated.', E_USER_DEPRECATED);
}
if (isset($out['sharded']) && ! $out['sharded']) {
@trigger_error('Specifying false for "out.sharded" is deprecated.', E_USER_DEPRECATED);
}
}
/**
* Create the mapReduce command.
*
* @param Server $server
* @return Command
*/
private function createCommand(Server $server)
{
$cmd = [
'mapReduce' => $this->collectionName,
'map' => $this->map,
'reduce' => $this->reduce,
'out' => $this->out,
];
foreach (['finalize', 'jsMode', 'limit', 'maxTimeMS', 'verbose'] as $option) {
if (isset($this->options[$option])) {
$cmd[$option] = $this->options[$option];
}
}
foreach (['collation', 'query', 'scope', 'sort'] as $option) {
if (isset($this->options[$option])) {
$cmd[$option] = (object) $this->options[$option];
}
}
if (! empty($this->options['bypassDocumentValidation']) &&
server_supports_feature($server, self::$wireVersionForDocumentLevelValidation)
) {
$cmd['bypassDocumentValidation'] = $this->options['bypassDocumentValidation'];
}
return new Command($cmd);
}
/**
* Creates a callable for MapReduceResult::getIterator().
*
* @param stdClass $result
* @param Server $server
* @return callable
* @throws UnexpectedValueException if the command response was malformed
*/
private function createGetIteratorCallable(stdClass $result, Server $server)
{
// Inline results can be wrapped with an ArrayIterator
if (isset($result->results) && is_array($result->results)) {
$results = $result->results;
return function () use ($results) {
return new ArrayIterator($results);
};
}
if (isset($result->result) && (is_string($result->result) || is_object($result->result))) {
$options = isset($this->options['typeMap']) ? ['typeMap' => $this->options['typeMap']] : [];
$find = is_string($result->result)
? new Find($this->databaseName, $result->result, [], $options)
: new Find($result->result->db, $result->result->collection, [], $options);
return function () use ($find, $server) {
return $find->execute($server);
};
}
throw new UnexpectedValueException('mapReduce command did not return inline results or an output collection');
}
/**
* Create options for executing the command.
*
* @see http://php.net/manual/en/mongodb-driver-server.executereadcommand.php
* @see http://php.net/manual/en/mongodb-driver-server.executereadwritecommand.php
* @param boolean $hasOutputCollection
* @return array
*/
private function createOptions($hasOutputCollection)
{
$options = [];
if (isset($this->options['readConcern'])) {
$options['readConcern'] = $this->options['readConcern'];
}
if (! $hasOutputCollection && isset($this->options['readPreference'])) {
$options['readPreference'] = $this->options['readPreference'];
}
if (isset($this->options['session'])) {
$options['session'] = $this->options['session'];
}
if ($hasOutputCollection && isset($this->options['writeConcern'])) {
$options['writeConcern'] = $this->options['writeConcern'];
}
return $options;
}
}
src/Operation/CreateCollection.php 0000666 00000025075 13645314021 0013237 0 ustar 00 isDefault()) {
unset($options['writeConcern']);
}
if (isset($options['autoIndexId'])) {
trigger_error('The "autoIndexId" option is deprecated and will be removed in a future release', E_USER_DEPRECATED);
}
$this->databaseName = (string) $databaseName;
$this->collectionName = (string) $collectionName;
$this->options = $options;
}
/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return array|object Command result document
* @throws UnsupportedException if collation or write concern is used and unsupported
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
if (isset($this->options['collation']) && ! server_supports_feature($server, self::$wireVersionForCollation)) {
throw UnsupportedException::collationNotSupported();
}
if (isset($this->options['writeConcern']) && ! server_supports_feature($server, self::$wireVersionForWriteConcern)) {
throw UnsupportedException::writeConcernNotSupported();
}
$cursor = $server->executeWriteCommand($this->databaseName, $this->createCommand(), $this->createOptions());
if (isset($this->options['typeMap'])) {
$cursor->setTypeMap($this->options['typeMap']);
}
return current($cursor->toArray());
}
/**
* Create the create command.
*
* @return Command
*/
private function createCommand()
{
$cmd = ['create' => $this->collectionName];
foreach (['autoIndexId', 'capped', 'flags', 'max', 'maxTimeMS', 'size', 'validationAction', 'validationLevel'] as $option) {
if (isset($this->options[$option])) {
$cmd[$option] = $this->options[$option];
}
}
foreach (['collation', 'indexOptionDefaults', 'storageEngine', 'validator'] as $option) {
if (isset($this->options[$option])) {
$cmd[$option] = (object) $this->options[$option];
}
}
return new Command($cmd);
}
/**
* Create options for executing the command.
*
* @see http://php.net/manual/en/mongodb-driver-server.executewritecommand.php
* @return array
*/
private function createOptions()
{
$options = [];
if (isset($this->options['session'])) {
$options['session'] = $this->options['session'];
}
if (isset($this->options['writeConcern'])) {
$options['writeConcern'] = $this->options['writeConcern'];
}
return $options;
}
}
src/Operation/Executable.php 0000666 00000002046 13645314021 0012072 0 ustar 00 $document) {
if ($i !== $expectedIndex) {
throw new InvalidArgumentException(sprintf('$documents is not a list (unexpected index: "%s")', $i));
}
if (! is_array($document) && ! is_object($document)) {
throw InvalidArgumentException::invalidType(sprintf('$documents[%d]', $i), $document, 'array or object');
}
$expectedIndex += 1;
}
$options += ['ordered' => true];
if (isset($options['bypassDocumentValidation']) && ! is_bool($options['bypassDocumentValidation'])) {
throw InvalidArgumentException::invalidType('"bypassDocumentValidation" option', $options['bypassDocumentValidation'], 'boolean');
}
if (! is_bool($options['ordered'])) {
throw InvalidArgumentException::invalidType('"ordered" option', $options['ordered'], 'boolean');
}
if (isset($options['session']) && ! $options['session'] instanceof Session) {
throw InvalidArgumentException::invalidType('"session" option', $options['session'], Session::class);
}
if (isset($options['writeConcern']) && ! $options['writeConcern'] instanceof WriteConcern) {
throw InvalidArgumentException::invalidType('"writeConcern" option', $options['writeConcern'], WriteConcern::class);
}
if (isset($options['writeConcern']) && $options['writeConcern']->isDefault()) {
unset($options['writeConcern']);
}
$this->databaseName = (string) $databaseName;
$this->collectionName = (string) $collectionName;
$this->documents = $documents;
$this->options = $options;
}
/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return InsertManyResult
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
$inTransaction = isset($this->options['session']) && $this->options['session']->isInTransaction();
if ($inTransaction && isset($this->options['writeConcern'])) {
throw UnsupportedException::writeConcernNotSupportedInTransaction();
}
$options = ['ordered' => $this->options['ordered']];
if (! empty($this->options['bypassDocumentValidation']) &&
server_supports_feature($server, self::$wireVersionForDocumentLevelValidation)
) {
$options['bypassDocumentValidation'] = $this->options['bypassDocumentValidation'];
}
$bulk = new Bulk($options);
$insertedIds = [];
foreach ($this->documents as $i => $document) {
$insertedIds[$i] = $bulk->insert($document);
}
$writeResult = $server->executeBulkWrite($this->databaseName . '.' . $this->collectionName, $bulk, $this->createOptions());
return new InsertManyResult($writeResult, $insertedIds);
}
/**
* Create options for executing the bulk write.
*
* @see http://php.net/manual/en/mongodb-driver-server.executebulkwrite.php
* @return array
*/
private function createOptions()
{
$options = [];
if (isset($this->options['session'])) {
$options['session'] = $this->options['session'];
}
if (isset($this->options['writeConcern'])) {
$options['writeConcern'] = $this->options['writeConcern'];
}
return $options;
}
}
src/Operation/DropDatabase.php 0000666 00000010771 13645314021 0012346 0 ustar 00 isDefault()) {
unset($options['writeConcern']);
}
$this->databaseName = (string) $databaseName;
$this->options = $options;
}
/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return array|object Command result document
* @throws UnsupportedException if writeConcern is used and unsupported
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
if (isset($this->options['writeConcern']) && ! server_supports_feature($server, self::$wireVersionForWriteConcern)) {
throw UnsupportedException::writeConcernNotSupported();
}
$command = new Command(['dropDatabase' => 1]);
$cursor = $server->executeWriteCommand($this->databaseName, $command, $this->createOptions());
if (isset($this->options['typeMap'])) {
$cursor->setTypeMap($this->options['typeMap']);
}
return current($cursor->toArray());
}
/**
* Create options for executing the command.
*
* @see http://php.net/manual/en/mongodb-driver-server.executewritecommand.php
* @return array
*/
private function createOptions()
{
$options = [];
if (isset($this->options['session'])) {
$options['session'] = $this->options['session'];
}
if (isset($this->options['writeConcern'])) {
$options['writeConcern'] = $this->options['writeConcern'];
}
return $options;
}
}
src/Operation/ListCollections.php 0000666 00000010745 13645314021 0013130 0 ustar 00 databaseName = (string) $databaseName;
$this->options = $options;
}
/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return CollectionInfoIterator
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
return $this->executeCommand($server);
}
/**
* Create options for executing the command.
*
* Note: read preference is intentionally omitted, as the spec requires that
* the command be executed on the primary.
*
* @see http://php.net/manual/en/mongodb-driver-server.executecommand.php
* @return array
*/
private function createOptions()
{
$options = [];
if (isset($this->options['session'])) {
$options['session'] = $this->options['session'];
}
return $options;
}
/**
* Returns information for all collections in this database using the
* listCollections command.
*
* @param Server $server
* @return CollectionInfoCommandIterator
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
private function executeCommand(Server $server)
{
$cmd = ['listCollections' => 1];
if (! empty($this->options['filter'])) {
$cmd['filter'] = (object) $this->options['filter'];
}
if (isset($this->options['maxTimeMS'])) {
$cmd['maxTimeMS'] = $this->options['maxTimeMS'];
}
$cursor = $server->executeReadCommand($this->databaseName, new Command($cmd), $this->createOptions());
$cursor->setTypeMap(['root' => 'array', 'document' => 'array']);
return new CollectionInfoCommandIterator(new CachingIterator($cursor), $this->databaseName);
}
}
src/Operation/DatabaseCommand.php 0000666 00000010240 13645314021 0013007 0 ustar 00 databaseName = (string) $databaseName;
$this->command = $command instanceof Command ? $command : new Command($command);
$this->options = $options;
}
/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return Cursor
*/
public function execute(Server $server)
{
$cursor = $server->executeCommand($this->databaseName, $this->command, $this->createOptions());
if (isset($this->options['typeMap'])) {
$cursor->setTypeMap($this->options['typeMap']);
}
return $cursor;
}
/**
* Create options for executing the command.
*
* @see http://php.net/manual/en/mongodb-driver-server.executecommand.php
* @return array
*/
private function createOptions()
{
$options = [];
if (isset($this->options['readPreference'])) {
$options['readPreference'] = $this->options['readPreference'];
}
if (isset($this->options['session'])) {
$options['session'] = $this->options['session'];
}
return $options;
}
}
src/Operation/FindOneAndDelete.php 0000666 00000010512 13645314021 0013076 0 ustar 00 findAndModify = new FindAndModify(
$databaseName,
$collectionName,
['query' => $filter, 'remove' => true] + $options
);
}
/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return array|object|null
* @throws UnsupportedException if collation or write concern is used and unsupported
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
return $this->findAndModify->execute($server);
}
public function getCommandDocument(Server $server)
{
return $this->findAndModify->getCommandDocument($server);
}
}
src/Operation/DeleteOne.php 0000666 00000006027 13645314021 0011660 0 ustar 00 delete = new Delete($databaseName, $collectionName, $filter, 1, $options);
}
/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return DeleteResult
* @throws UnsupportedException if collation is used and unsupported
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
return $this->delete->execute($server);
}
public function getCommandDocument(Server $server)
{
return $this->delete->getCommandDocument($server);
}
}
src/Operation/DropCollection.php 0000666 00000013016 13645314021 0012730 0 ustar 00 isDefault()) {
unset($options['writeConcern']);
}
$this->databaseName = (string) $databaseName;
$this->collectionName = (string) $collectionName;
$this->options = $options;
}
/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return array|object Command result document
* @throws UnsupportedException if writeConcern is used and unsupported
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
if (isset($this->options['writeConcern']) && ! server_supports_feature($server, self::$wireVersionForWriteConcern)) {
throw UnsupportedException::writeConcernNotSupported();
}
$inTransaction = isset($this->options['session']) && $this->options['session']->isInTransaction();
if ($inTransaction && isset($this->options['writeConcern'])) {
throw UnsupportedException::writeConcernNotSupportedInTransaction();
}
$command = new Command(['drop' => $this->collectionName]);
try {
$cursor = $server->executeWriteCommand($this->databaseName, $command, $this->createOptions());
} catch (DriverRuntimeException $e) {
/* The server may return an error if the collection does not exist.
* Check for an error message (unfortunately, there isn't a code)
* and NOP instead of throwing.
*/
if ($e->getMessage() === self::$errorMessageNamespaceNotFound) {
return (object) ['ok' => 0, 'errmsg' => self::$errorMessageNamespaceNotFound];
}
throw $e;
}
if (isset($this->options['typeMap'])) {
$cursor->setTypeMap($this->options['typeMap']);
}
return current($cursor->toArray());
}
/**
* Create options for executing the command.
*
* @see http://php.net/manual/en/mongodb-driver-server.executewritecommand.php
* @return array
*/
private function createOptions()
{
$options = [];
if (isset($this->options['session'])) {
$options['session'] = $this->options['session'];
}
if (isset($this->options['writeConcern'])) {
$options['writeConcern'] = $this->options['writeConcern'];
}
return $options;
}
}
src/Operation/InsertOne.php 0000666 00000012536 13645314021 0011724 0 ustar 00 isDefault()) {
unset($options['writeConcern']);
}
$this->databaseName = (string) $databaseName;
$this->collectionName = (string) $collectionName;
$this->document = $document;
$this->options = $options;
}
/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return InsertOneResult
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
$options = [];
$inTransaction = isset($this->options['session']) && $this->options['session']->isInTransaction();
if (isset($this->options['writeConcern']) && $inTransaction) {
throw UnsupportedException::writeConcernNotSupportedInTransaction();
}
if (! empty($this->options['bypassDocumentValidation']) &&
server_supports_feature($server, self::$wireVersionForDocumentLevelValidation)
) {
$options['bypassDocumentValidation'] = $this->options['bypassDocumentValidation'];
}
$bulk = new Bulk($options);
$insertedId = $bulk->insert($this->document);
$writeResult = $server->executeBulkWrite($this->databaseName . '.' . $this->collectionName, $bulk, $this->createOptions());
return new InsertOneResult($writeResult, $insertedId);
}
/**
* Create options for executing the bulk write.
*
* @see http://php.net/manual/en/mongodb-driver-server.executebulkwrite.php
* @return array
*/
private function createOptions()
{
$options = [];
if (isset($this->options['session'])) {
$options['session'] = $this->options['session'];
}
if (isset($this->options['writeConcern'])) {
$options['writeConcern'] = $this->options['writeConcern'];
}
return $options;
}
}
src/Operation/FindOneAndUpdate.php 0000666 00000014724 13645314021 0013127 0 ustar 00 self::RETURN_DOCUMENT_BEFORE,
'upsert' => false,
];
if (isset($options['projection']) && ! is_array($options['projection']) && ! is_object($options['projection'])) {
throw InvalidArgumentException::invalidType('"projection" option', $options['projection'], 'array or object');
}
if (! is_integer($options['returnDocument'])) {
throw InvalidArgumentException::invalidType('"returnDocument" option', $options['returnDocument'], 'integer');
}
if ($options['returnDocument'] !== self::RETURN_DOCUMENT_AFTER &&
$options['returnDocument'] !== self::RETURN_DOCUMENT_BEFORE) {
throw new InvalidArgumentException('Invalid value for "returnDocument" option: ' . $options['returnDocument']);
}
if (isset($options['projection'])) {
$options['fields'] = $options['projection'];
}
$options['new'] = $options['returnDocument'] === self::RETURN_DOCUMENT_AFTER;
unset($options['projection'], $options['returnDocument']);
$this->findAndModify = new FindAndModify(
$databaseName,
$collectionName,
['query' => $filter, 'update' => $update] + $options
);
}
/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return array|object|null
* @throws UnsupportedException if collation or write concern is used and unsupported
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
return $this->findAndModify->execute($server);
}
public function getCommandDocument(Server $server)
{
return $this->findAndModify->getCommandDocument($server);
}
}
src/Operation/BulkWrite.php 0000666 00000037423 13645314021 0011730 0 ustar 00 [ $filter, $options ] ],
* [ 'deleteOne' => [ $filter, $options ] ],
* [ 'insertOne' => [ $document ] ],
* [ 'replaceOne' => [ $filter, $replacement, $options ] ],
* [ 'updateMany' => [ $filter, $update, $options ] ],
* [ 'updateOne' => [ $filter, $update, $options ] ],
* ]
*
* Arguments correspond to the respective Operation classes; however, the
* writeConcern option is specified for the top-level bulk write operation
* instead of each individual operation.
*
* Supported options for deleteMany and deleteOne operations:
*
* * collation (document): Collation specification.
*
* This is not supported for server versions < 3.4 and will result in an
* exception at execution time if used.
*
* Supported options for replaceOne, updateMany, and updateOne operations:
*
* * collation (document): Collation specification.
*
* This is not supported for server versions < 3.4 and will result in an
* exception at execution time if used.
*
* * upsert (boolean): When true, a new document is created if no document
* matches the query. The default is false.
*
* Supported options for updateMany and updateOne operations:
*
* * arrayFilters (document array): A set of filters specifying to which
* array elements an update should apply.
*
* This is not supported for server versions < 3.6 and will result in an
* exception at execution time if used.
*
* Supported options for the bulk write operation:
*
* * bypassDocumentValidation (boolean): If true, allows the write to
* circumvent document level validation. The default is false.
*
* For servers < 3.2, this option is ignored as document level validation
* is not available.
*
* * ordered (boolean): If true, when an insert fails, return without
* performing the remaining writes. If false, when a write fails,
* continue with the remaining writes, if any. The default is true.
*
* * session (MongoDB\Driver\Session): Client session.
*
* Sessions are not supported for server versions < 3.6.
*
* * writeConcern (MongoDB\Driver\WriteConcern): Write concern.
*
* @param string $databaseName Database name
* @param string $collectionName Collection name
* @param array[] $operations List of write operations
* @param array $options Command options
* @throws InvalidArgumentException for parameter/option parsing errors
*/
public function __construct($databaseName, $collectionName, array $operations, array $options = [])
{
if (empty($operations)) {
throw new InvalidArgumentException('$operations is empty');
}
$expectedIndex = 0;
foreach ($operations as $i => $operation) {
if ($i !== $expectedIndex) {
throw new InvalidArgumentException(sprintf('$operations is not a list (unexpected index: "%s")', $i));
}
if (! is_array($operation)) {
throw InvalidArgumentException::invalidType(sprintf('$operations[%d]', $i), $operation, 'array');
}
if (count($operation) !== 1) {
throw new InvalidArgumentException(sprintf('Expected one element in $operation[%d], actually: %d', $i, count($operation)));
}
$type = key($operation);
$args = current($operation);
if (! isset($args[0]) && ! array_key_exists(0, $args)) {
throw new InvalidArgumentException(sprintf('Missing first argument for $operations[%d]["%s"]', $i, $type));
}
if (! is_array($args[0]) && ! is_object($args[0])) {
throw InvalidArgumentException::invalidType(sprintf('$operations[%d]["%s"][0]', $i, $type), $args[0], 'array or object');
}
switch ($type) {
case self::INSERT_ONE:
break;
case self::DELETE_MANY:
case self::DELETE_ONE:
if (! isset($args[1])) {
$args[1] = [];
}
if (! is_array($args[1])) {
throw InvalidArgumentException::invalidType(sprintf('$operations[%d]["%s"][1]', $i, $type), $args[1], 'array');
}
$args[1]['limit'] = ($type === self::DELETE_ONE ? 1 : 0);
if (isset($args[1]['collation'])) {
$this->isCollationUsed = true;
if (! is_array($args[1]['collation']) && ! is_object($args[1]['collation'])) {
throw InvalidArgumentException::invalidType(sprintf('$operations[%d]["%s"][1]["collation"]', $i, $type), $args[1]['collation'], 'array or object');
}
}
$operations[$i][$type][1] = $args[1];
break;
case self::REPLACE_ONE:
if (! isset($args[1]) && ! array_key_exists(1, $args)) {
throw new InvalidArgumentException(sprintf('Missing second argument for $operations[%d]["%s"]', $i, $type));
}
if (! is_array($args[1]) && ! is_object($args[1])) {
throw InvalidArgumentException::invalidType(sprintf('$operations[%d]["%s"][1]', $i, $type), $args[1], 'array or object');
}
if (is_first_key_operator($args[1])) {
throw new InvalidArgumentException(sprintf('First key in $operations[%d]["%s"][1] is an update operator', $i, $type));
}
if (! isset($args[2])) {
$args[2] = [];
}
if (! is_array($args[2])) {
throw InvalidArgumentException::invalidType(sprintf('$operations[%d]["%s"][2]', $i, $type), $args[2], 'array');
}
$args[2]['multi'] = false;
$args[2] += ['upsert' => false];
if (isset($args[2]['collation'])) {
$this->isCollationUsed = true;
if (! is_array($args[2]['collation']) && ! is_object($args[2]['collation'])) {
throw InvalidArgumentException::invalidType(sprintf('$operations[%d]["%s"][2]["collation"]', $i, $type), $args[2]['collation'], 'array or object');
}
}
if (! is_bool($args[2]['upsert'])) {
throw InvalidArgumentException::invalidType(sprintf('$operations[%d]["%s"][2]["upsert"]', $i, $type), $args[2]['upsert'], 'boolean');
}
$operations[$i][$type][2] = $args[2];
break;
case self::UPDATE_MANY:
case self::UPDATE_ONE:
if (! isset($args[1]) && ! array_key_exists(1, $args)) {
throw new InvalidArgumentException(sprintf('Missing second argument for $operations[%d]["%s"]', $i, $type));
}
if (! is_array($args[1]) && ! is_object($args[1])) {
throw InvalidArgumentException::invalidType(sprintf('$operations[%d]["%s"][1]', $i, $type), $args[1], 'array or object');
}
if (! is_first_key_operator($args[1]) && ! is_pipeline($args[1])) {
throw new InvalidArgumentException(sprintf('First key in $operations[%d]["%s"][1] is neither an update operator nor a pipeline', $i, $type));
}
if (! isset($args[2])) {
$args[2] = [];
}
if (! is_array($args[2])) {
throw InvalidArgumentException::invalidType(sprintf('$operations[%d]["%s"][2]', $i, $type), $args[2], 'array');
}
$args[2]['multi'] = ($type === self::UPDATE_MANY);
$args[2] += ['upsert' => false];
if (isset($args[2]['arrayFilters'])) {
$this->isArrayFiltersUsed = true;
if (! is_array($args[2]['arrayFilters'])) {
throw InvalidArgumentException::invalidType(sprintf('$operations[%d]["%s"][2]["arrayFilters"]', $i, $type), $args[2]['arrayFilters'], 'array');
}
}
if (isset($args[2]['collation'])) {
$this->isCollationUsed = true;
if (! is_array($args[2]['collation']) && ! is_object($args[2]['collation'])) {
throw InvalidArgumentException::invalidType(sprintf('$operations[%d]["%s"][2]["collation"]', $i, $type), $args[2]['collation'], 'array or object');
}
}
if (! is_bool($args[2]['upsert'])) {
throw InvalidArgumentException::invalidType(sprintf('$operations[%d]["%s"][2]["upsert"]', $i, $type), $args[2]['upsert'], 'boolean');
}
$operations[$i][$type][2] = $args[2];
break;
default:
throw new InvalidArgumentException(sprintf('Unknown operation type "%s" in $operations[%d]', $type, $i));
}
$expectedIndex += 1;
}
$options += ['ordered' => true];
if (isset($options['bypassDocumentValidation']) && ! is_bool($options['bypassDocumentValidation'])) {
throw InvalidArgumentException::invalidType('"bypassDocumentValidation" option', $options['bypassDocumentValidation'], 'boolean');
}
if (! is_bool($options['ordered'])) {
throw InvalidArgumentException::invalidType('"ordered" option', $options['ordered'], 'boolean');
}
if (isset($options['session']) && ! $options['session'] instanceof Session) {
throw InvalidArgumentException::invalidType('"session" option', $options['session'], Session::class);
}
if (isset($options['writeConcern']) && ! $options['writeConcern'] instanceof WriteConcern) {
throw InvalidArgumentException::invalidType('"writeConcern" option', $options['writeConcern'], WriteConcern::class);
}
if (isset($options['writeConcern']) && $options['writeConcern']->isDefault()) {
unset($options['writeConcern']);
}
$this->databaseName = (string) $databaseName;
$this->collectionName = (string) $collectionName;
$this->operations = $operations;
$this->options = $options;
}
/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return BulkWriteResult
* @throws UnsupportedException if array filters or collation is used and unsupported
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
if ($this->isArrayFiltersUsed && ! server_supports_feature($server, self::$wireVersionForArrayFilters)) {
throw UnsupportedException::arrayFiltersNotSupported();
}
if ($this->isCollationUsed && ! server_supports_feature($server, self::$wireVersionForCollation)) {
throw UnsupportedException::collationNotSupported();
}
$inTransaction = isset($this->options['session']) && $this->options['session']->isInTransaction();
if ($inTransaction && isset($this->options['writeConcern'])) {
throw UnsupportedException::writeConcernNotSupportedInTransaction();
}
$options = ['ordered' => $this->options['ordered']];
if (! empty($this->options['bypassDocumentValidation']) &&
server_supports_feature($server, self::$wireVersionForDocumentLevelValidation)
) {
$options['bypassDocumentValidation'] = $this->options['bypassDocumentValidation'];
}
$bulk = new Bulk($options);
$insertedIds = [];
foreach ($this->operations as $i => $operation) {
$type = key($operation);
$args = current($operation);
switch ($type) {
case self::DELETE_MANY:
case self::DELETE_ONE:
$bulk->delete($args[0], $args[1]);
break;
case self::INSERT_ONE:
$insertedIds[$i] = $bulk->insert($args[0]);
break;
case self::REPLACE_ONE:
case self::UPDATE_MANY:
case self::UPDATE_ONE:
$bulk->update($args[0], $args[1], $args[2]);
}
}
$writeResult = $server->executeBulkWrite($this->databaseName . '.' . $this->collectionName, $bulk, $this->createOptions());
return new BulkWriteResult($writeResult, $insertedIds);
}
/**
* Create options for executing the bulk write.
*
* @see http://php.net/manual/en/mongodb-driver-server.executebulkwrite.php
* @return array
*/
private function createOptions()
{
$options = [];
if (isset($this->options['session'])) {
$options['session'] = $this->options['session'];
}
if (isset($this->options['writeConcern'])) {
$options['writeConcern'] = $this->options['writeConcern'];
}
return $options;
}
}
src/Operation/UpdateMany.php 0000666 00000010525 13645314021 0012061 0 ustar 00 update = new Update(
$databaseName,
$collectionName,
$filter,
$update,
['multi' => true] + $options
);
}
/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return UpdateResult
* @throws UnsupportedException if collation is used and unsupported
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
return $this->update->execute($server);
}
public function getCommandDocument(Server $server)
{
return $this->update->getCommandDocument($server);
}
}
src/Operation/Find.php 0000666 00000043420 13645314021 0010672 0 ustar 00 isDefault()) {
unset($options['readConcern']);
}
if (isset($options['snapshot'])) {
trigger_error('The "snapshot" option is deprecated and will be removed in a future release', E_USER_DEPRECATED);
}
if (isset($options['maxScan'])) {
trigger_error('The "maxScan" option is deprecated and will be removed in a future release', E_USER_DEPRECATED);
}
$this->databaseName = (string) $databaseName;
$this->collectionName = (string) $collectionName;
$this->filter = $filter;
$this->options = $options;
}
/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return Cursor
* @throws UnsupportedException if collation or read concern is used and unsupported
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
if (isset($this->options['collation']) && ! server_supports_feature($server, self::$wireVersionForCollation)) {
throw UnsupportedException::collationNotSupported();
}
if (isset($this->options['readConcern']) && ! server_supports_feature($server, self::$wireVersionForReadConcern)) {
throw UnsupportedException::readConcernNotSupported();
}
$inTransaction = isset($this->options['session']) && $this->options['session']->isInTransaction();
if ($inTransaction && isset($this->options['readConcern'])) {
throw UnsupportedException::readConcernNotSupportedInTransaction();
}
$cursor = $server->executeQuery($this->databaseName . '.' . $this->collectionName, new Query($this->filter, $this->createQueryOptions()), $this->createExecuteOptions());
if (isset($this->options['typeMap'])) {
$cursor->setTypeMap($this->options['typeMap']);
}
return $cursor;
}
public function getCommandDocument(Server $server)
{
return $this->createCommandDocument();
}
/**
* Construct a command document for Find
*/
private function createCommandDocument()
{
$cmd = ['find' => $this->collectionName, 'filter' => (object) $this->filter];
$options = $this->createQueryOptions();
if (empty($options)) {
return $cmd;
}
// maxAwaitTimeMS is a Query level option so should not be considered here
unset($options['maxAwaitTimeMS']);
$modifierFallback = [
['allowPartialResults', 'partial'],
['comment', '$comment'],
['hint', '$hint'],
['maxScan', '$maxScan'],
['max', '$max'],
['maxTimeMS', '$maxTimeMS'],
['min', '$min'],
['returnKey', '$returnKey'],
['showRecordId', '$showDiskLoc'],
['sort', '$orderby'],
['snapshot', '$snapshot'],
];
foreach ($modifierFallback as $modifier) {
if (! isset($options[$modifier[0]]) && isset($options['modifiers'][$modifier[1]])) {
$options[$modifier[0]] = $options['modifiers'][$modifier[1]];
}
}
unset($options['modifiers']);
return $cmd + $options;
}
/**
* Create options for executing the command.
*
* @see http://php.net/manual/en/mongodb-driver-server.executequery.php
* @return array
*/
private function createExecuteOptions()
{
$options = [];
if (isset($this->options['readPreference'])) {
$options['readPreference'] = $this->options['readPreference'];
}
if (isset($this->options['session'])) {
$options['session'] = $this->options['session'];
}
return $options;
}
/**
* Create options for the find query.
*
* Note that these are separate from the options for executing the command,
* which are created in createExecuteOptions().
*
* @return array
*/
private function createQueryOptions()
{
$options = [];
if (isset($this->options['cursorType'])) {
if ($this->options['cursorType'] === self::TAILABLE) {
$options['tailable'] = true;
}
if ($this->options['cursorType'] === self::TAILABLE_AWAIT) {
$options['tailable'] = true;
$options['awaitData'] = true;
}
}
foreach (['allowDiskUse', 'allowPartialResults', 'batchSize', 'comment', 'hint', 'limit', 'maxAwaitTimeMS', 'maxScan', 'maxTimeMS', 'noCursorTimeout', 'oplogReplay', 'projection', 'readConcern', 'returnKey', 'showRecordId', 'skip', 'snapshot', 'sort'] as $option) {
if (isset($this->options[$option])) {
$options[$option] = $this->options[$option];
}
}
foreach (['collation', 'max', 'min'] as $option) {
if (isset($this->options[$option])) {
$options[$option] = (object) $this->options[$option];
}
}
$modifiers = empty($this->options['modifiers']) ? [] : (array) $this->options['modifiers'];
if (! empty($modifiers)) {
$options['modifiers'] = $modifiers;
}
return $options;
}
}
src/Operation/Update.php 0000666 00000025656 13645314021 0011247 0 ustar 00 false,
'upsert' => false,
];
if (isset($options['arrayFilters']) && ! is_array($options['arrayFilters'])) {
throw InvalidArgumentException::invalidType('"arrayFilters" option', $options['arrayFilters'], 'array');
}
if (isset($options['bypassDocumentValidation']) && ! is_bool($options['bypassDocumentValidation'])) {
throw InvalidArgumentException::invalidType('"bypassDocumentValidation" option', $options['bypassDocumentValidation'], 'boolean');
}
if (isset($options['collation']) && ! is_array($options['collation']) && ! is_object($options['collation'])) {
throw InvalidArgumentException::invalidType('"collation" option', $options['collation'], 'array or object');
}
if (isset($options['hint']) && ! is_string($options['hint']) && ! is_array($options['hint']) && ! is_object($options['hint'])) {
throw InvalidArgumentException::invalidType('"hint" option', $options['hint'], ['string', 'array', 'object']);
}
if (! is_bool($options['multi'])) {
throw InvalidArgumentException::invalidType('"multi" option', $options['multi'], 'boolean');
}
if ($options['multi'] && ! is_first_key_operator($update) && ! is_pipeline($update)) {
throw new InvalidArgumentException('"multi" option cannot be true if $update is a replacement document');
}
if (isset($options['session']) && ! $options['session'] instanceof Session) {
throw InvalidArgumentException::invalidType('"session" option', $options['session'], Session::class);
}
if (! is_bool($options['upsert'])) {
throw InvalidArgumentException::invalidType('"upsert" option', $options['upsert'], 'boolean');
}
if (isset($options['writeConcern']) && ! $options['writeConcern'] instanceof WriteConcern) {
throw InvalidArgumentException::invalidType('"writeConcern" option', $options['writeConcern'], WriteConcern::class);
}
if (isset($options['writeConcern']) && $options['writeConcern']->isDefault()) {
unset($options['writeConcern']);
}
$this->databaseName = (string) $databaseName;
$this->collectionName = (string) $collectionName;
$this->filter = $filter;
$this->update = $update;
$this->options = $options;
}
/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return UpdateResult
* @throws UnsupportedException if array filters or collation is used and unsupported
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
if (isset($this->options['arrayFilters']) && ! server_supports_feature($server, self::$wireVersionForArrayFilters)) {
throw UnsupportedException::arrayFiltersNotSupported();
}
if (isset($this->options['collation']) && ! server_supports_feature($server, self::$wireVersionForCollation)) {
throw UnsupportedException::collationNotSupported();
}
/* Server versions >= 3.4.0 raise errors for unknown update
* options. For previous versions, the CRUD spec requires a client-side
* error. */
if (isset($this->options['hint']) && ! server_supports_feature($server, self::$wireVersionForHintServerSideError)) {
throw UnsupportedException::hintNotSupported();
}
$inTransaction = isset($this->options['session']) && $this->options['session']->isInTransaction();
if ($inTransaction && isset($this->options['writeConcern'])) {
throw UnsupportedException::writeConcernNotSupportedInTransaction();
}
$bulkOptions = [];
if (! empty($this->options['bypassDocumentValidation']) &&
server_supports_feature($server, self::$wireVersionForDocumentLevelValidation)
) {
$bulkOptions['bypassDocumentValidation'] = $this->options['bypassDocumentValidation'];
}
$bulk = new Bulk($bulkOptions);
$bulk->update($this->filter, $this->update, $this->createUpdateOptions());
$writeResult = $server->executeBulkWrite($this->databaseName . '.' . $this->collectionName, $bulk, $this->createExecuteOptions());
return new UpdateResult($writeResult);
}
public function getCommandDocument(Server $server)
{
$cmd = ['update' => $this->collectionName, 'updates' => [['q' => $this->filter, 'u' => $this->update] + $this->createUpdateOptions()]];
if (isset($this->options['writeConcern'])) {
$cmd['writeConcern'] = $this->options['writeConcern'];
}
if (! empty($this->options['bypassDocumentValidation']) &&
server_supports_feature($server, self::$wireVersionForDocumentLevelValidation)
) {
$cmd['bypassDocumentValidation'] = $this->options['bypassDocumentValidation'];
}
return $cmd;
}
/**
* Create options for executing the bulk write.
*
* @see http://php.net/manual/en/mongodb-driver-server.executebulkwrite.php
* @return array
*/
private function createExecuteOptions()
{
$options = [];
if (isset($this->options['session'])) {
$options['session'] = $this->options['session'];
}
if (isset($this->options['writeConcern'])) {
$options['writeConcern'] = $this->options['writeConcern'];
}
return $options;
}
/**
* Create options for the update command.
*
* Note that these options are different from the bulk write options, which
* are created in createExecuteOptions().
*
* @return array
*/
private function createUpdateOptions()
{
$updateOptions = [
'multi' => $this->options['multi'],
'upsert' => $this->options['upsert'],
];
foreach (['arrayFilters', 'hint'] as $option) {
if (isset($this->options[$option])) {
$updateOptions[$option] = $this->options[$option];
}
}
if (isset($this->options['collation'])) {
$updateOptions['collation'] = (object) $this->options['collation'];
}
return $updateOptions;
}
}
src/Operation/DropIndexes.php 0000666 00000013665 13645314021 0012246 0 ustar 00 isDefault()) {
unset($options['writeConcern']);
}
$this->databaseName = (string) $databaseName;
$this->collectionName = (string) $collectionName;
$this->indexName = $indexName;
$this->options = $options;
}
/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return array|object Command result document
* @throws UnsupportedException if writeConcern is used and unsupported
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
if (isset($this->options['writeConcern']) && ! server_supports_feature($server, self::$wireVersionForWriteConcern)) {
throw UnsupportedException::writeConcernNotSupported();
}
$inTransaction = isset($this->options['session']) && $this->options['session']->isInTransaction();
if ($inTransaction && isset($this->options['writeConcern'])) {
throw UnsupportedException::writeConcernNotSupportedInTransaction();
}
$cursor = $server->executeWriteCommand($this->databaseName, $this->createCommand(), $this->createOptions());
if (isset($this->options['typeMap'])) {
$cursor->setTypeMap($this->options['typeMap']);
}
return current($cursor->toArray());
}
/**
* Create the dropIndexes command.
*
* @return Command
*/
private function createCommand()
{
$cmd = [
'dropIndexes' => $this->collectionName,
'index' => $this->indexName,
];
if (isset($this->options['maxTimeMS'])) {
$cmd['maxTimeMS'] = $this->options['maxTimeMS'];
}
return new Command($cmd);
}
/**
* Create options for executing the command.
*
* @see http://php.net/manual/en/mongodb-driver-server.executewritecommand.php
* @return array
*/
private function createOptions()
{
$options = [];
if (isset($this->options['session'])) {
$options['session'] = $this->options['session'];
}
if (isset($this->options['writeConcern'])) {
$options['writeConcern'] = $this->options['writeConcern'];
}
return $options;
}
}
src/Operation/CountDocuments.php 0000666 00000013624 13645314021 0012767 0 ustar 00 databaseName = (string) $databaseName;
$this->collectionName = (string) $collectionName;
$this->filter = $filter;
$this->aggregateOptions = array_intersect_key($options, ['collation' => 1, 'hint' => 1, 'maxTimeMS' => 1, 'readConcern' => 1, 'readPreference' => 1, 'session' => 1]);
$this->countOptions = array_intersect_key($options, ['limit' => 1, 'skip' => 1]);
$this->aggregate = $this->createAggregate();
}
/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return integer
* @throws UnexpectedValueException if the command response was malformed
* @throws UnsupportedException if collation or read concern is used and unsupported
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
$cursor = $this->aggregate->execute($server);
$allResults = $cursor->toArray();
/* If there are no documents to count, the aggregation pipeline has no items to group, and
* hence the result is an empty array (PHPLIB-376) */
if (count($allResults) == 0) {
return 0;
}
$result = current($allResults);
if (! isset($result->n) || ! (is_integer($result->n) || is_float($result->n))) {
throw new UnexpectedValueException('count command did not return a numeric "n" value');
}
return (integer) $result->n;
}
/**
* @return Aggregate
*/
private function createAggregate()
{
$pipeline = [
['$match' => (object) $this->filter],
];
if (isset($this->countOptions['skip'])) {
$pipeline[] = ['$skip' => $this->countOptions['skip']];
}
if (isset($this->countOptions['limit'])) {
$pipeline[] = ['$limit' => $this->countOptions['limit']];
}
$pipeline[] = ['$group' => ['_id' => 1, 'n' => ['$sum' => 1]]];
return new Aggregate($this->databaseName, $this->collectionName, $pipeline, $this->aggregateOptions);
}
}
src/Operation/UpdateOne.php 0000666 00000010522 13645314021 0011673 0 ustar 00 update = new Update(
$databaseName,
$collectionName,
$filter,
$update,
['multi' => false] + $options
);
}
/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return UpdateResult
* @throws UnsupportedException if collation is used and unsupported
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
return $this->update->execute($server);
}
public function getCommandDocument(Server $server)
{
return $this->update->getCommandDocument($server);
}
}
src/Operation/DeleteMany.php 0000666 00000006030 13645314021 0012035 0 ustar 00 delete = new Delete($databaseName, $collectionName, $filter, 0, $options);
}
/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return DeleteResult
* @throws UnsupportedException if collation is used and unsupported
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
return $this->delete->execute($server);
}
public function getCommandDocument(Server $server)
{
return $this->delete->getCommandDocument($server);
}
}
src/Operation/ReplaceOne.php 0000666 00000010057 13645314021 0012027 0 ustar 00 update = new Update(
$databaseName,
$collectionName,
$filter,
$replacement,
['multi' => false] + $options
);
}
/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return UpdateResult
* @throws UnsupportedException if collation is used and unsupported
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
return $this->update->execute($server);
}
}
src/Operation/FindOne.php 0000666 00000011647 13645314021 0011342 0 ustar 00 find = new Find(
$databaseName,
$collectionName,
$filter,
['limit' => 1] + $options
);
}
/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return array|object|null
* @throws UnsupportedException if collation or read concern is used and unsupported
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
$cursor = $this->find->execute($server);
$document = current($cursor->toArray());
return $document === false ? null : $document;
}
public function getCommandDocument(Server $server)
{
return $this->find->getCommandDocument($server);
}
}
src/Operation/Distinct.php 0000666 00000020031 13645314021 0011564 0 ustar 00 isDefault()) {
unset($options['readConcern']);
}
$this->databaseName = (string) $databaseName;
$this->collectionName = (string) $collectionName;
$this->fieldName = (string) $fieldName;
$this->filter = $filter;
$this->options = $options;
}
/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return mixed[]
* @throws UnexpectedValueException if the command response was malformed
* @throws UnsupportedException if collation or read concern is used and unsupported
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
if (isset($this->options['collation']) && ! server_supports_feature($server, self::$wireVersionForCollation)) {
throw UnsupportedException::collationNotSupported();
}
if (isset($this->options['readConcern']) && ! server_supports_feature($server, self::$wireVersionForReadConcern)) {
throw UnsupportedException::readConcernNotSupported();
}
$inTransaction = isset($this->options['session']) && $this->options['session']->isInTransaction();
if ($inTransaction && isset($this->options['readConcern'])) {
throw UnsupportedException::readConcernNotSupportedInTransaction();
}
$cursor = $server->executeReadCommand($this->databaseName, new Command($this->createCommandDocument()), $this->createOptions());
if (isset($this->options['typeMap'])) {
$cursor->setTypeMap(create_field_path_type_map($this->options['typeMap'], 'values.$'));
}
$result = current($cursor->toArray());
if (! isset($result->values) || ! is_array($result->values)) {
throw new UnexpectedValueException('distinct command did not return a "values" array');
}
return $result->values;
}
public function getCommandDocument(Server $server)
{
return $this->createCommandDocument();
}
/**
* Create the distinct command document.
*
* @return array
*/
private function createCommandDocument()
{
$cmd = [
'distinct' => $this->collectionName,
'key' => $this->fieldName,
];
if (! empty($this->filter)) {
$cmd['query'] = (object) $this->filter;
}
if (isset($this->options['collation'])) {
$cmd['collation'] = (object) $this->options['collation'];
}
if (isset($this->options['maxTimeMS'])) {
$cmd['maxTimeMS'] = $this->options['maxTimeMS'];
}
return $cmd;
}
/**
* Create options for executing the command.
*
* @see http://php.net/manual/en/mongodb-driver-server.executereadcommand.php
* @return array
*/
private function createOptions()
{
$options = [];
if (isset($this->options['readConcern'])) {
$options['readConcern'] = $this->options['readConcern'];
}
if (isset($this->options['readPreference'])) {
$options['readPreference'] = $this->options['readPreference'];
}
if (isset($this->options['session'])) {
$options['session'] = $this->options['session'];
}
return $options;
}
}
src/Operation/Watch.php 0000666 00000040276 13645314021 0011066 0 ustar 00 self::FULL_DOCUMENT_DEFAULT,
'readPreference' => new ReadPreference(ReadPreference::RP_PRIMARY),
];
if (! is_string($options['fullDocument'])) {
throw InvalidArgumentException::invalidType('"fullDocument" option', $options['fullDocument'], 'string');
}
if (! $options['readPreference'] instanceof ReadPreference) {
throw InvalidArgumentException::invalidType('"readPreference" option', $options['readPreference'], ReadPreference::class);
}
if (isset($options['resumeAfter']) && ! is_array($options['resumeAfter']) && ! is_object($options['resumeAfter'])) {
throw InvalidArgumentException::invalidType('"resumeAfter" option', $options['resumeAfter'], 'array or object');
}
if (isset($options['startAfter']) && ! is_array($options['startAfter']) && ! is_object($options['startAfter'])) {
throw InvalidArgumentException::invalidType('"startAfter" option', $options['startAfter'], 'array or object');
}
if (isset($options['startAtOperationTime']) && ! $options['startAtOperationTime'] instanceof TimestampInterface) {
throw InvalidArgumentException::invalidType('"startAtOperationTime" option', $options['startAtOperationTime'], TimestampInterface::class);
}
/* In the absence of an explicit session, create one to ensure that the
* initial aggregation and any resume attempts can use the same session
* ("implicit from the user's perspective" per PHPLIB-342). Since this
* is filling in for an implicit session, we default "causalConsistency"
* to false. */
if (! isset($options['session'])) {
try {
$options['session'] = $manager->startSession(['causalConsistency' => false]);
} catch (RuntimeException $e) {
/* We can ignore the exception, as libmongoc likely cannot
* create its own session and there is no risk of a mismatch. */
}
}
$this->aggregateOptions = array_intersect_key($options, ['batchSize' => 1, 'collation' => 1, 'maxAwaitTimeMS' => 1, 'readConcern' => 1, 'readPreference' => 1, 'session' => 1, 'typeMap' => 1]);
$this->changeStreamOptions = array_intersect_key($options, ['fullDocument' => 1, 'resumeAfter' => 1, 'startAfter' => 1, 'startAtOperationTime' => 1]);
// Null database name implies a cluster-wide change stream
if ($databaseName === null) {
$databaseName = 'admin';
$this->changeStreamOptions['allChangesForCluster'] = true;
}
$this->manager = $manager;
$this->databaseName = (string) $databaseName;
$this->collectionName = isset($collectionName) ? (string) $collectionName : null;
$this->pipeline = $pipeline;
$this->aggregate = $this->createAggregate();
}
/** @internal */
final public function commandFailed(CommandFailedEvent $event)
{
}
/** @internal */
final public function commandStarted(CommandStartedEvent $event)
{
if ($event->getCommandName() !== 'aggregate') {
return;
}
$this->firstBatchSize = null;
$this->postBatchResumeToken = null;
}
/** @internal */
final public function commandSucceeded(CommandSucceededEvent $event)
{
if ($event->getCommandName() !== 'aggregate') {
return;
}
$reply = $event->getReply();
if (! isset($reply->cursor->firstBatch) || ! is_array($reply->cursor->firstBatch)) {
throw new UnexpectedValueException('aggregate command did not return a "cursor.firstBatch" array');
}
$this->firstBatchSize = count($reply->cursor->firstBatch);
if (isset($reply->cursor->postBatchResumeToken) && is_object($reply->cursor->postBatchResumeToken)) {
$this->postBatchResumeToken = $reply->cursor->postBatchResumeToken;
}
if ($this->shouldCaptureOperationTime($event->getServer()) &&
isset($reply->operationTime) && $reply->operationTime instanceof TimestampInterface) {
$this->operationTime = $reply->operationTime;
}
}
/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return ChangeStream
* @throws UnsupportedException if collation or read concern is used and unsupported
* @throws RuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
return new ChangeStream(
$this->createChangeStreamIterator($server),
function ($resumeToken, $hasAdvanced) {
return $this->resume($resumeToken, $hasAdvanced);
}
);
}
/**
* Create the aggregate command for a change stream.
*
* This method is also used to recreate the aggregate command when resuming.
*
* @return Aggregate
*/
private function createAggregate()
{
$pipeline = $this->pipeline;
array_unshift($pipeline, ['$changeStream' => (object) $this->changeStreamOptions]);
return new Aggregate($this->databaseName, $this->collectionName, $pipeline, $this->aggregateOptions);
}
/**
* Create a ChangeStreamIterator by executing the aggregate command.
*
* @param Server $server
* @return ChangeStreamIterator
*/
private function createChangeStreamIterator(Server $server)
{
return new ChangeStreamIterator(
$this->executeAggregate($server),
$this->firstBatchSize,
$this->getInitialResumeToken(),
$this->postBatchResumeToken
);
}
/**
* Execute the aggregate command.
*
* The command will be executed using APM so that we can capture data from
* its response (e.g. firstBatch size, postBatchResumeToken).
*
* @param Server $server
* @return Cursor
*/
private function executeAggregate(Server $server)
{
addSubscriber($this);
try {
return $this->aggregate->execute($server);
} finally {
removeSubscriber($this);
}
}
/**
* Return the initial resume token for creating the ChangeStreamIterator.
*
* @see https://github.com/mongodb/specifications/blob/master/source/change-streams/change-streams.rst#updating-the-cached-resume-token
* @return array|object|null
*/
private function getInitialResumeToken()
{
if ($this->firstBatchSize === 0 && isset($this->postBatchResumeToken)) {
return $this->postBatchResumeToken;
}
if (isset($this->changeStreamOptions['startAfter'])) {
return $this->changeStreamOptions['startAfter'];
}
if (isset($this->changeStreamOptions['resumeAfter'])) {
return $this->changeStreamOptions['resumeAfter'];
}
return null;
}
/**
* Resumes a change stream.
*
* @see https://github.com/mongodb/specifications/blob/master/source/change-streams/change-streams.rst#resume-process
* @param array|object|null $resumeToken
* @param bool $hasAdvanced
* @return ChangeStreamIterator
* @throws InvalidArgumentException
*/
private function resume($resumeToken = null, $hasAdvanced = false)
{
if (isset($resumeToken) && ! is_array($resumeToken) && ! is_object($resumeToken)) {
throw InvalidArgumentException::invalidType('$resumeToken', $resumeToken, 'array or object');
}
$this->hasResumed = true;
/* Select a new server using the original read preference. While watch
* is not usable within transactions, we still check if there is a
* pinned session. This is to avoid an ambiguous error message about
* running a command on the wrong server. */
$server = select_server($this->manager, $this->aggregateOptions);
$resumeOption = isset($this->changeStreamOptions['startAfter']) && ! $hasAdvanced ? 'startAfter' : 'resumeAfter';
unset($this->changeStreamOptions['resumeAfter']);
unset($this->changeStreamOptions['startAfter']);
unset($this->changeStreamOptions['startAtOperationTime']);
if ($resumeToken !== null) {
$this->changeStreamOptions[$resumeOption] = $resumeToken;
}
if ($resumeToken === null && $this->operationTime !== null) {
$this->changeStreamOptions['startAtOperationTime'] = $this->operationTime;
}
// Recreate the aggregate command and return a new ChangeStreamIterator
$this->aggregate = $this->createAggregate();
return $this->createChangeStreamIterator($server);
}
/**
* Determine whether to capture operation time from an aggregate response.
*
* @see https://github.com/mongodb/specifications/blob/master/source/change-streams/change-streams.rst#startatoperationtime
* @param Server $server
* @return boolean
*/
private function shouldCaptureOperationTime(Server $server)
{
if ($this->hasResumed) {
return false;
}
if (isset($this->changeStreamOptions['resumeAfter']) ||
isset($this->changeStreamOptions['startAfter']) ||
isset($this->changeStreamOptions['startAtOperationTime'])) {
return false;
}
if ($this->firstBatchSize > 0) {
return false;
}
if ($this->postBatchResumeToken !== null) {
return false;
}
if (! server_supports_feature($server, self::$wireVersionForStartAtOperationTime)) {
return false;
}
return true;
}
}
src/Operation/Aggregate.php 0000666 00000036631 13645314021 0011706 0 ustar 00 $operation) {
if ($i !== $expectedIndex) {
throw new InvalidArgumentException(sprintf('$pipeline is not a list (unexpected index: "%s")', $i));
}
if (! is_array($operation) && ! is_object($operation)) {
throw InvalidArgumentException::invalidType(sprintf('$pipeline[%d]', $i), $operation, 'array or object');
}
$expectedIndex += 1;
}
$options += [
'allowDiskUse' => false,
'useCursor' => true,
];
if (! is_bool($options['allowDiskUse'])) {
throw InvalidArgumentException::invalidType('"allowDiskUse" option', $options['allowDiskUse'], 'boolean');
}
if (isset($options['batchSize']) && ! is_integer($options['batchSize'])) {
throw InvalidArgumentException::invalidType('"batchSize" option', $options['batchSize'], 'integer');
}
if (isset($options['bypassDocumentValidation']) && ! is_bool($options['bypassDocumentValidation'])) {
throw InvalidArgumentException::invalidType('"bypassDocumentValidation" option', $options['bypassDocumentValidation'], 'boolean');
}
if (isset($options['collation']) && ! is_array($options['collation']) && ! is_object($options['collation'])) {
throw InvalidArgumentException::invalidType('"collation" option', $options['collation'], 'array or object');
}
if (isset($options['comment']) && ! is_string($options['comment'])) {
throw InvalidArgumentException::invalidType('"comment" option', $options['comment'], 'string');
}
if (isset($options['explain']) && ! is_bool($options['explain'])) {
throw InvalidArgumentException::invalidType('"explain" option', $options['explain'], 'boolean');
}
if (isset($options['hint']) && ! is_string($options['hint']) && ! is_array($options['hint']) && ! is_object($options['hint'])) {
throw InvalidArgumentException::invalidType('"hint" option', $options['hint'], 'string or array or object');
}
if (isset($options['maxAwaitTimeMS']) && ! is_integer($options['maxAwaitTimeMS'])) {
throw InvalidArgumentException::invalidType('"maxAwaitTimeMS" option', $options['maxAwaitTimeMS'], 'integer');
}
if (isset($options['maxTimeMS']) && ! is_integer($options['maxTimeMS'])) {
throw InvalidArgumentException::invalidType('"maxTimeMS" option', $options['maxTimeMS'], 'integer');
}
if (isset($options['readConcern']) && ! $options['readConcern'] instanceof ReadConcern) {
throw InvalidArgumentException::invalidType('"readConcern" option', $options['readConcern'], ReadConcern::class);
}
if (isset($options['readPreference']) && ! $options['readPreference'] instanceof ReadPreference) {
throw InvalidArgumentException::invalidType('"readPreference" option', $options['readPreference'], ReadPreference::class);
}
if (isset($options['session']) && ! $options['session'] instanceof Session) {
throw InvalidArgumentException::invalidType('"session" option', $options['session'], Session::class);
}
if (isset($options['typeMap']) && ! is_array($options['typeMap'])) {
throw InvalidArgumentException::invalidType('"typeMap" option', $options['typeMap'], 'array');
}
if (! is_bool($options['useCursor'])) {
throw InvalidArgumentException::invalidType('"useCursor" option', $options['useCursor'], 'boolean');
}
if (isset($options['writeConcern']) && ! $options['writeConcern'] instanceof WriteConcern) {
throw InvalidArgumentException::invalidType('"writeConcern" option', $options['writeConcern'], WriteConcern::class);
}
if (isset($options['batchSize']) && ! $options['useCursor']) {
throw new InvalidArgumentException('"batchSize" option should not be used if "useCursor" is false');
}
if (isset($options['readConcern']) && $options['readConcern']->isDefault()) {
unset($options['readConcern']);
}
if (isset($options['writeConcern']) && $options['writeConcern']->isDefault()) {
unset($options['writeConcern']);
}
if (! empty($options['explain'])) {
$options['useCursor'] = false;
}
$this->databaseName = (string) $databaseName;
$this->collectionName = isset($collectionName) ? (string) $collectionName : null;
$this->pipeline = $pipeline;
$this->options = $options;
}
/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return Traversable
* @throws UnexpectedValueException if the command response was malformed
* @throws UnsupportedException if collation, read concern, or write concern is used and unsupported
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
if (isset($this->options['collation']) && ! server_supports_feature($server, self::$wireVersionForCollation)) {
throw UnsupportedException::collationNotSupported();
}
if (isset($this->options['readConcern']) && ! server_supports_feature($server, self::$wireVersionForReadConcern)) {
throw UnsupportedException::readConcernNotSupported();
}
if (isset($this->options['writeConcern']) && ! server_supports_feature($server, self::$wireVersionForWriteConcern)) {
throw UnsupportedException::writeConcernNotSupported();
}
$inTransaction = isset($this->options['session']) && $this->options['session']->isInTransaction();
if ($inTransaction) {
if (isset($this->options['readConcern'])) {
throw UnsupportedException::readConcernNotSupportedInTransaction();
}
if (isset($this->options['writeConcern'])) {
throw UnsupportedException::writeConcernNotSupportedInTransaction();
}
}
$hasExplain = ! empty($this->options['explain']);
$hasWriteStage = is_last_pipeline_operator_write($this->pipeline);
$command = $this->createCommand($server, $hasWriteStage);
$options = $this->createOptions($hasWriteStage, $hasExplain);
$cursor = $hasWriteStage && ! $hasExplain
? $server->executeReadWriteCommand($this->databaseName, $command, $options)
: $server->executeReadCommand($this->databaseName, $command, $options);
if ($this->options['useCursor'] || $hasExplain) {
if (isset($this->options['typeMap'])) {
$cursor->setTypeMap($this->options['typeMap']);
}
return $cursor;
}
if (isset($this->options['typeMap'])) {
$cursor->setTypeMap(create_field_path_type_map($this->options['typeMap'], 'result.$'));
}
$result = current($cursor->toArray());
if (! isset($result->result) || ! is_array($result->result)) {
throw new UnexpectedValueException('aggregate command did not return a "result" array');
}
return new ArrayIterator($result->result);
}
/**
* Create the aggregate command.
*
* @param Server $server
* @param boolean $hasWriteStage
* @return Command
*/
private function createCommand(Server $server, $hasWriteStage)
{
$cmd = [
'aggregate' => $this->collectionName ?? 1,
'pipeline' => $this->pipeline,
];
$cmdOptions = [];
$cmd['allowDiskUse'] = $this->options['allowDiskUse'];
if (! empty($this->options['bypassDocumentValidation']) &&
server_supports_feature($server, self::$wireVersionForDocumentLevelValidation)
) {
$cmd['bypassDocumentValidation'] = $this->options['bypassDocumentValidation'];
}
foreach (['comment', 'explain', 'maxTimeMS'] as $option) {
if (isset($this->options[$option])) {
$cmd[$option] = $this->options[$option];
}
}
if (isset($this->options['collation'])) {
$cmd['collation'] = (object) $this->options['collation'];
}
if (isset($this->options['hint'])) {
$cmd['hint'] = is_array($this->options['hint']) ? (object) $this->options['hint'] : $this->options['hint'];
}
if (isset($this->options['maxAwaitTimeMS'])) {
$cmdOptions['maxAwaitTimeMS'] = $this->options['maxAwaitTimeMS'];
}
if ($this->options['useCursor']) {
/* Ignore batchSize if pipeline includes an $out or $merge stage, as
* no documents will be returned and sending a batchSize of zero
* could prevent the pipeline from executing at all. */
$cmd['cursor'] = isset($this->options["batchSize"]) && ! $hasWriteStage
? ['batchSize' => $this->options["batchSize"]]
: new stdClass();
}
return new Command($cmd, $cmdOptions);
}
/**
* Create options for executing the command.
*
* @see http://php.net/manual/en/mongodb-driver-server.executereadcommand.php
* @see http://php.net/manual/en/mongodb-driver-server.executereadwritecommand.php
* @param boolean $hasWriteStage
* @param boolean $hasExplain
* @return array
*/
private function createOptions($hasWriteStage, $hasExplain)
{
$options = [];
if (isset($this->options['readConcern'])) {
$options['readConcern'] = $this->options['readConcern'];
}
if (! $hasWriteStage && isset($this->options['readPreference'])) {
$options['readPreference'] = $this->options['readPreference'];
}
if (isset($this->options['session'])) {
$options['session'] = $this->options['session'];
}
if ($hasWriteStage && ! $hasExplain && isset($this->options['writeConcern'])) {
$options['writeConcern'] = $this->options['writeConcern'];
}
return $options;
}
}
src/Operation/ModifyCollection.php 0000666 00000011561 13645314021 0013256 0 ustar 00 isDefault()) {
unset($options['writeConcern']);
}
$this->databaseName = (string) $databaseName;
$this->collectionName = (string) $collectionName;
$this->collectionOptions = $collectionOptions;
$this->options = $options;
}
/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return array|object Command result document
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
if (isset($this->options['writeConcern']) && ! server_supports_feature($server, self::$wireVersionForWriteConcern)) {
throw UnsupportedException::writeConcernNotSupported();
}
$cursor = $server->executeWriteCommand($this->databaseName, new Command(['collMod' => $this->collectionName] + $this->collectionOptions), $this->createOptions());
if (isset($this->options['typeMap'])) {
$cursor->setTypeMap($this->options['typeMap']);
}
return current($cursor->toArray());
}
/**
* Create options for executing the command.
*
* @see http://php.net/manual/en/mongodb-driver-server.executereadwritecommand.php
* @return array
*/
private function createOptions()
{
$options = [];
if (isset($this->options['session'])) {
$options['session'] = $this->options['session'];
}
if (isset($this->options['writeConcern'])) {
$options['writeConcern'] = $this->options['writeConcern'];
}
return $options;
}
}
src/Operation/Count.php 0000666 00000021322 13645314021 0011077 0 ustar 00 isDefault()) {
unset($options['readConcern']);
}
$this->databaseName = (string) $databaseName;
$this->collectionName = (string) $collectionName;
$this->filter = $filter;
$this->options = $options;
}
/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return integer
* @throws UnexpectedValueException if the command response was malformed
* @throws UnsupportedException if collation or read concern is used and unsupported
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
if (isset($this->options['collation']) && ! server_supports_feature($server, self::$wireVersionForCollation)) {
throw UnsupportedException::collationNotSupported();
}
if (isset($this->options['readConcern']) && ! server_supports_feature($server, self::$wireVersionForReadConcern)) {
throw UnsupportedException::readConcernNotSupported();
}
$inTransaction = isset($this->options['session']) && $this->options['session']->isInTransaction();
if ($inTransaction && isset($this->options['readConcern'])) {
throw UnsupportedException::readConcernNotSupportedInTransaction();
}
$cursor = $server->executeReadCommand($this->databaseName, new Command($this->createCommandDocument()), $this->createOptions());
$result = current($cursor->toArray());
// Older server versions may return a float
if (! isset($result->n) || ! (is_integer($result->n) || is_float($result->n))) {
throw new UnexpectedValueException('count command did not return a numeric "n" value');
}
return (integer) $result->n;
}
public function getCommandDocument(Server $server)
{
return $this->createCommandDocument();
}
/**
* Create the count command document.
*
* @return array
*/
private function createCommandDocument()
{
$cmd = ['count' => $this->collectionName];
if (! empty($this->filter)) {
$cmd['query'] = (object) $this->filter;
}
if (isset($this->options['collation'])) {
$cmd['collation'] = (object) $this->options['collation'];
}
if (isset($this->options['hint'])) {
$cmd['hint'] = is_array($this->options['hint']) ? (object) $this->options['hint'] : $this->options['hint'];
}
foreach (['limit', 'maxTimeMS', 'skip'] as $option) {
if (isset($this->options[$option])) {
$cmd[$option] = $this->options[$option];
}
}
return $cmd;
}
/**
* Create options for executing the command.
*
* @see http://php.net/manual/en/mongodb-driver-server.executereadcommand.php
* @return array
*/
private function createOptions()
{
$options = [];
if (isset($this->options['readConcern'])) {
$options['readConcern'] = $this->options['readConcern'];
}
if (isset($this->options['readPreference'])) {
$options['readPreference'] = $this->options['readPreference'];
}
if (isset($this->options['session'])) {
$options['session'] = $this->options['session'];
}
return $options;
}
}
src/Operation/WithTransaction.php 0000666 00000010174 13645314021 0013133 0 ustar 00 callback = $callback;
$this->transactionOptions = $transactionOptions;
}
/**
* Execute the operation in the given session
*
* This helper takes care of retrying the commit operation or the entire
* transaction if an error occurs.
*
* If the commit fails because of an UnknownTransactionCommitResult error, the
* commit is retried without re-invoking the callback.
* If the commit fails because of a TransientTransactionError, the entire
* transaction will be retried. In this case, the callback will be invoked
* again. It is important that the logic inside the callback is idempotent.
*
* In case of failures, the commit or transaction are retried until 120 seconds
* from the initial call have elapsed. After that, no retries will happen and
* the helper will throw the last exception received from the driver.
*
* @see Client::startSession
*
* @param Session $session A session object as retrieved by Client::startSession
* @return void
* @throws RuntimeException for driver errors while committing the transaction
* @throws Exception for any other errors, including those thrown in the callback
*/
public function execute(Session $session)
{
$startTime = time();
while (true) {
$session->startTransaction($this->transactionOptions);
try {
call_user_func($this->callback, $session);
} catch (Throwable $e) {
if ($session->isInTransaction()) {
$session->abortTransaction();
}
if ($e instanceof RuntimeException &&
$e->hasErrorLabel('TransientTransactionError') &&
! $this->isTransactionTimeLimitExceeded($startTime)
) {
continue;
}
throw $e;
}
if (! $session->isInTransaction()) {
// Assume callback intentionally ended the transaction
return;
}
while (true) {
try {
$session->commitTransaction();
} catch (RuntimeException $e) {
if ($e->getCode() !== 50 /* MaxTimeMSExpired */ &&
$e->hasErrorLabel('UnknownTransactionCommitResult') &&
! $this->isTransactionTimeLimitExceeded($startTime)
) {
// Retry committing the transaction
continue;
}
if ($e->hasErrorLabel('TransientTransactionError') &&
! $this->isTransactionTimeLimitExceeded($startTime)
) {
// Restart the transaction, invoking the callback again
continue 2;
}
throw $e;
}
// Commit was successful
break;
}
// Transaction was successful
break;
}
}
/**
* Returns whether the time limit for retrying transactions in the convenient transaction API has passed
*
* @param int $startTime The time the transaction was started
* @return bool
*/
private function isTransactionTimeLimitExceeded($startTime)
{
return time() - $startTime >= 120;
}
}
src/Operation/FindOneAndReplace.php 0000666 00000014433 13645314021 0013255 0 ustar 00 self::RETURN_DOCUMENT_BEFORE,
'upsert' => false,
];
if (isset($options['projection']) && ! is_array($options['projection']) && ! is_object($options['projection'])) {
throw InvalidArgumentException::invalidType('"projection" option', $options['projection'], 'array or object');
}
if (! is_integer($options['returnDocument'])) {
throw InvalidArgumentException::invalidType('"returnDocument" option', $options['returnDocument'], 'integer');
}
if ($options['returnDocument'] !== self::RETURN_DOCUMENT_AFTER &&
$options['returnDocument'] !== self::RETURN_DOCUMENT_BEFORE) {
throw new InvalidArgumentException('Invalid value for "returnDocument" option: ' . $options['returnDocument']);
}
if (isset($options['projection'])) {
$options['fields'] = $options['projection'];
}
$options['new'] = $options['returnDocument'] === self::RETURN_DOCUMENT_AFTER;
unset($options['projection'], $options['returnDocument']);
$this->findAndModify = new FindAndModify(
$databaseName,
$collectionName,
['query' => $filter, 'update' => $replacement] + $options
);
}
/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return array|object|null
* @throws UnsupportedException if collation or write concern is used and unsupported
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
return $this->findAndModify->execute($server);
}
public function getCommandDocument(Server $server)
{
return $this->findAndModify->getCommandDocument($server);
}
}
src/Operation/ListIndexes.php 0000666 00000011607 13645314021 0012247 0 ustar 00 databaseName = (string) $databaseName;
$this->collectionName = (string) $collectionName;
$this->options = $options;
}
/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return IndexInfoIterator
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
return $this->executeCommand($server);
}
/**
* Create options for executing the command.
*
* Note: read preference is intentionally omitted, as the spec requires that
* the command be executed on the primary.
*
* @see http://php.net/manual/en/mongodb-driver-server.executecommand.php
* @return array
*/
private function createOptions()
{
$options = [];
if (isset($this->options['session'])) {
$options['session'] = $this->options['session'];
}
return $options;
}
/**
* Returns information for all indexes for this collection using the
* listIndexes command.
*
* @param Server $server
* @return IndexInfoIteratorIterator
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
private function executeCommand(Server $server)
{
$cmd = ['listIndexes' => $this->collectionName];
if (isset($this->options['maxTimeMS'])) {
$cmd['maxTimeMS'] = $this->options['maxTimeMS'];
}
try {
$cursor = $server->executeReadCommand($this->databaseName, new Command($cmd), $this->createOptions());
} catch (DriverRuntimeException $e) {
/* The server may return an error if the collection does not exist.
* Check for possible error codes (see: SERVER-20463) and return an
* empty iterator instead of throwing.
*/
if ($e->getCode() === self::$errorCodeNamespaceNotFound || $e->getCode() === self::$errorCodeDatabaseNotFound) {
return new IndexInfoIteratorIterator(new EmptyIterator());
}
throw $e;
}
$cursor->setTypeMap(['root' => 'array', 'document' => 'array']);
return new IndexInfoIteratorIterator(new CachingIterator($cursor), $this->databaseName . '.' . $this->collectionName);
}
}
src/Operation/FindAndModify.php 0000666 00000033171 13645314021 0012467 0 ustar 00 = 4.4. Using this option in
* other contexts will result in an exception at execution time.
*
* * maxTimeMS (integer): The maximum amount of time to allow the query to
* run.
*
* * new (boolean): When true, returns the modified document rather than
* the original. This option is ignored for remove operations. The
* The default is false.
*
* * query (document): Query by which to filter documents.
*
* * remove (boolean): When true, removes the matched document. This option
* cannot be true if the update option is set. The default is false.
*
* * session (MongoDB\Driver\Session): Client session.
*
* Sessions are not supported for server versions < 3.6.
*
* * sort (document): Determines which document the operation modifies if
* the query selects multiple documents.
*
* * typeMap (array): Type map for BSON deserialization.
*
* * update (document): Update or replacement to apply to the matched
* document. This option cannot be set if the remove option is true.
*
* * upsert (boolean): When true, a new document is created if no document
* matches the query. This option is ignored for remove operations. The
* default is false.
*
* * writeConcern (MongoDB\Driver\WriteConcern): Write concern.
*
* This is not supported for server versions < 3.2 and will result in an
* exception at execution time if used.
*
* @param string $databaseName Database name
* @param string $collectionName Collection name
* @param array $options Command options
* @throws InvalidArgumentException for parameter/option parsing errors
*/
public function __construct($databaseName, $collectionName, array $options)
{
$options += [
'new' => false,
'remove' => false,
'upsert' => false,
];
if (isset($options['arrayFilters']) && ! is_array($options['arrayFilters'])) {
throw InvalidArgumentException::invalidType('"arrayFilters" option', $options['arrayFilters'], 'array');
}
if (isset($options['bypassDocumentValidation']) && ! is_bool($options['bypassDocumentValidation'])) {
throw InvalidArgumentException::invalidType('"bypassDocumentValidation" option', $options['bypassDocumentValidation'], 'boolean');
}
if (isset($options['collation']) && ! is_array($options['collation']) && ! is_object($options['collation'])) {
throw InvalidArgumentException::invalidType('"collation" option', $options['collation'], 'array or object');
}
if (isset($options['fields']) && ! is_array($options['fields']) && ! is_object($options['fields'])) {
throw InvalidArgumentException::invalidType('"fields" option', $options['fields'], 'array or object');
}
if (isset($options['hint']) && ! is_string($options['hint']) && ! is_array($options['hint']) && ! is_object($options['hint'])) {
throw InvalidArgumentException::invalidType('"hint" option', $options['hint'], ['string', 'array', 'object']);
}
if (isset($options['maxTimeMS']) && ! is_integer($options['maxTimeMS'])) {
throw InvalidArgumentException::invalidType('"maxTimeMS" option', $options['maxTimeMS'], 'integer');
}
if (! is_bool($options['new'])) {
throw InvalidArgumentException::invalidType('"new" option', $options['new'], 'boolean');
}
if (isset($options['query']) && ! is_array($options['query']) && ! is_object($options['query'])) {
throw InvalidArgumentException::invalidType('"query" option', $options['query'], 'array or object');
}
if (! is_bool($options['remove'])) {
throw InvalidArgumentException::invalidType('"remove" option', $options['remove'], 'boolean');
}
if (isset($options['session']) && ! $options['session'] instanceof Session) {
throw InvalidArgumentException::invalidType('"session" option', $options['session'], Session::class);
}
if (isset($options['sort']) && ! is_array($options['sort']) && ! is_object($options['sort'])) {
throw InvalidArgumentException::invalidType('"sort" option', $options['sort'], 'array or object');
}
if (isset($options['typeMap']) && ! is_array($options['typeMap'])) {
throw InvalidArgumentException::invalidType('"typeMap" option', $options['typeMap'], 'array');
}
if (isset($options['update']) && ! is_array($options['update']) && ! is_object($options['update'])) {
throw InvalidArgumentException::invalidType('"update" option', $options['update'], 'array or object');
}
if (isset($options['writeConcern']) && ! $options['writeConcern'] instanceof WriteConcern) {
throw InvalidArgumentException::invalidType('"writeConcern" option', $options['writeConcern'], WriteConcern::class);
}
if (! is_bool($options['upsert'])) {
throw InvalidArgumentException::invalidType('"upsert" option', $options['upsert'], 'boolean');
}
if (! (isset($options['update']) xor $options['remove'])) {
throw new InvalidArgumentException('The "remove" option must be true or an "update" document must be specified, but not both');
}
if (isset($options['writeConcern']) && $options['writeConcern']->isDefault()) {
unset($options['writeConcern']);
}
$this->databaseName = (string) $databaseName;
$this->collectionName = (string) $collectionName;
$this->options = $options;
}
/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return array|object|null
* @throws UnexpectedValueException if the command response was malformed
* @throws UnsupportedException if array filters, collation, or write concern is used and unsupported
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
if (isset($this->options['arrayFilters']) && ! server_supports_feature($server, self::$wireVersionForArrayFilters)) {
throw UnsupportedException::arrayFiltersNotSupported();
}
if (isset($this->options['collation']) && ! server_supports_feature($server, self::$wireVersionForCollation)) {
throw UnsupportedException::collationNotSupported();
}
/* Server versions >= 4.1.10 raise errors for unknown findAndModify
* options (SERVER-40005), but the CRUD spec requires client-side errors
* for server versions < 4.2. For later versions, we'll rely on the
* server to either utilize the option or report its own error. */
if (isset($this->options['hint']) && ! $this->isHintSupported($server)) {
throw UnsupportedException::hintNotSupported();
}
if (isset($this->options['writeConcern']) && ! server_supports_feature($server, self::$wireVersionForWriteConcern)) {
throw UnsupportedException::writeConcernNotSupported();
}
$inTransaction = isset($this->options['session']) && $this->options['session']->isInTransaction();
if ($inTransaction && isset($this->options['writeConcern'])) {
throw UnsupportedException::writeConcernNotSupportedInTransaction();
}
$cursor = $server->executeWriteCommand($this->databaseName, new Command($this->createCommandDocument($server)), $this->createOptions());
if (isset($this->options['typeMap'])) {
$cursor->setTypeMap(create_field_path_type_map($this->options['typeMap'], 'value'));
}
$result = current($cursor->toArray());
return $result->value ?? null;
}
public function getCommandDocument(Server $server)
{
return $this->createCommandDocument($server);
}
/**
* Create the findAndModify command document.
*
* @param Server $server
* @return array
*/
private function createCommandDocument(Server $server)
{
$cmd = ['findAndModify' => $this->collectionName];
if ($this->options['remove']) {
$cmd['remove'] = true;
} else {
$cmd['new'] = $this->options['new'];
$cmd['upsert'] = $this->options['upsert'];
}
foreach (['collation', 'fields', 'query', 'sort'] as $option) {
if (isset($this->options[$option])) {
$cmd[$option] = (object) $this->options[$option];
}
}
if (isset($this->options['update'])) {
$cmd['update'] = is_pipeline($this->options['update'])
? $this->options['update']
: (object) $this->options['update'];
}
foreach (['arrayFilters', 'hint', 'maxTimeMS'] as $option) {
if (isset($this->options[$option])) {
$cmd[$option] = $this->options[$option];
}
}
if (! empty($this->options['bypassDocumentValidation']) &&
server_supports_feature($server, self::$wireVersionForDocumentLevelValidation)
) {
$cmd['bypassDocumentValidation'] = $this->options['bypassDocumentValidation'];
}
return $cmd;
}
/**
* Create options for executing the command.
*
* @see http://php.net/manual/en/mongodb-driver-server.executewritecommand.php
* @return array
*/
private function createOptions()
{
$options = [];
if (isset($this->options['session'])) {
$options['session'] = $this->options['session'];
}
if (isset($this->options['writeConcern'])) {
$options['writeConcern'] = $this->options['writeConcern'];
}
return $options;
}
private function isAcknowledgedWriteConcern() : bool
{
if (! isset($this->options['writeConcern'])) {
return true;
}
return $this->options['writeConcern']->getW() > 1 || $this->options['writeConcern']->getJournal();
}
private function isHintSupported(Server $server) : bool
{
$requiredWireVersion = $this->isAcknowledgedWriteConcern() ? self::$wireVersionForHintServerSideError : self::$wireVersionForHint;
return server_supports_feature($server, $requiredWireVersion);
}
}
src/Operation/Delete.php 0000666 00000017222 13645314021 0011215 0 ustar 00 isDefault()) {
unset($options['writeConcern']);
}
$this->databaseName = (string) $databaseName;
$this->collectionName = (string) $collectionName;
$this->filter = $filter;
$this->limit = $limit;
$this->options = $options;
}
/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return DeleteResult
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
if (isset($this->options['collation']) && ! server_supports_feature($server, self::$wireVersionForCollation)) {
throw UnsupportedException::collationNotSupported();
}
/* Server versions >= 3.4.0 raise errors for unknown update
* options. For previous versions, the CRUD spec requires a client-side
* error. */
if (isset($this->options['hint']) && ! server_supports_feature($server, self::$wireVersionForHintServerSideError)) {
throw UnsupportedException::hintNotSupported();
}
$inTransaction = isset($this->options['session']) && $this->options['session']->isInTransaction();
if ($inTransaction && isset($this->options['writeConcern'])) {
throw UnsupportedException::writeConcernNotSupportedInTransaction();
}
$bulk = new Bulk();
$bulk->delete($this->filter, $this->createDeleteOptions());
$writeResult = $server->executeBulkWrite($this->databaseName . '.' . $this->collectionName, $bulk, $this->createExecuteOptions());
return new DeleteResult($writeResult);
}
public function getCommandDocument(Server $server)
{
$cmd = ['delete' => $this->collectionName, 'deletes' => [['q' => $this->filter] + $this->createDeleteOptions()]];
if (isset($this->options['writeConcern'])) {
$cmd['writeConcern'] = $this->options['writeConcern'];
}
return $cmd;
}
/**
* Create options for the delete command.
*
* Note that these options are different from the bulk write options, which
* are created in createExecuteOptions().
*
* @return array
*/
private function createDeleteOptions()
{
$deleteOptions = ['limit' => $this->limit];
if (isset($this->options['collation'])) {
$deleteOptions['collation'] = (object) $this->options['collation'];
}
if (isset($this->options['hint'])) {
$deleteOptions['hint'] = $this->options['hint'];
}
return $deleteOptions;
}
/**
* Create options for executing the bulk write.
*
* @see http://php.net/manual/en/mongodb-driver-server.executebulkwrite.php
* @return array
*/
private function createExecuteOptions()
{
$options = [];
if (isset($this->options['session'])) {
$options['session'] = $this->options['session'];
}
if (isset($this->options['writeConcern'])) {
$options['writeConcern'] = $this->options['writeConcern'];
}
return $options;
}
}
src/Operation/EstimatedDocumentCount.php 0000666 00000006541 13645314021 0014444 0 ustar 00 databaseName = (string) $databaseName;
$this->collectionName = (string) $collectionName;
$this->options = array_intersect_key($options, ['maxTimeMS' => 1, 'readConcern' => 1, 'readPreference' => 1, 'session' => 1]);
$this->count = $this->createCount();
}
/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return integer
* @throws UnexpectedValueException if the command response was malformed
* @throws UnsupportedException if collation or read concern is used and unsupported
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
return $this->count->execute($server);
}
public function getCommandDocument(Server $server)
{
return $this->count->getCommandDocument($server);
}
/**
* @return Count
*/
private function createCount()
{
return new Count($this->databaseName, $this->collectionName, [], $this->options);
}
}
src/Operation/CreateIndexes.php 0000666 00000015436 13645314021 0012543 0 ustar 00 $index) {
if ($i !== $expectedIndex) {
throw new InvalidArgumentException(sprintf('$indexes is not a list (unexpected index: "%s")', $i));
}
if (! is_array($index)) {
throw InvalidArgumentException::invalidType(sprintf('$index[%d]', $i), $index, 'array');
}
if (! isset($index['ns'])) {
$index['ns'] = $databaseName . '.' . $collectionName;
}
if (isset($index['collation'])) {
$this->isCollationUsed = true;
}
$this->indexes[] = new IndexInput($index);
$expectedIndex += 1;
}
if (isset($options['maxTimeMS']) && ! is_integer($options['maxTimeMS'])) {
throw InvalidArgumentException::invalidType('"maxTimeMS" option', $options['maxTimeMS'], 'integer');
}
if (isset($options['session']) && ! $options['session'] instanceof Session) {
throw InvalidArgumentException::invalidType('"session" option', $options['session'], Session::class);
}
if (isset($options['writeConcern']) && ! $options['writeConcern'] instanceof WriteConcern) {
throw InvalidArgumentException::invalidType('"writeConcern" option', $options['writeConcern'], WriteConcern::class);
}
if (isset($options['writeConcern']) && $options['writeConcern']->isDefault()) {
unset($options['writeConcern']);
}
$this->databaseName = (string) $databaseName;
$this->collectionName = (string) $collectionName;
$this->options = $options;
}
/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return string[] The names of the created indexes
* @throws UnsupportedException if collation or write concern is used and unsupported
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
if ($this->isCollationUsed && ! server_supports_feature($server, self::$wireVersionForCollation)) {
throw UnsupportedException::collationNotSupported();
}
if (isset($this->options['writeConcern']) && ! server_supports_feature($server, self::$wireVersionForWriteConcern)) {
throw UnsupportedException::writeConcernNotSupported();
}
$inTransaction = isset($this->options['session']) && $this->options['session']->isInTransaction();
if ($inTransaction && isset($this->options['writeConcern'])) {
throw UnsupportedException::writeConcernNotSupportedInTransaction();
}
$this->executeCommand($server);
return array_map(function (IndexInput $index) {
return (string) $index;
}, $this->indexes);
}
/**
* Create options for executing the command.
*
* @see http://php.net/manual/en/mongodb-driver-server.executewritecommand.php
* @return array
*/
private function createOptions()
{
$options = [];
if (isset($this->options['session'])) {
$options['session'] = $this->options['session'];
}
if (isset($this->options['writeConcern'])) {
$options['writeConcern'] = $this->options['writeConcern'];
}
return $options;
}
/**
* Create one or more indexes for the collection using the createIndexes
* command.
*
* @param Server $server
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
private function executeCommand(Server $server)
{
$cmd = [
'createIndexes' => $this->collectionName,
'indexes' => $this->indexes,
];
if (isset($this->options['maxTimeMS'])) {
$cmd['maxTimeMS'] = $this->options['maxTimeMS'];
}
$server->executeWriteCommand($this->databaseName, new Command($cmd), $this->createOptions());
}
}
src/Model/BSONDocument.php 0000666 00000005503 13645314021 0011352 0 ustar 00 $value) {
$this[$key] = recursive_copy($value);
}
}
/**
* This overrides the parent constructor to allow property access of entries
* by default.
*
* @see http://php.net/arrayobject.construct
* @param array $input
* @param integer $flags
* @param string $iterator_class
*/
public function __construct($input = [], $flags = ArrayObject::ARRAY_AS_PROPS, $iterator_class = 'ArrayIterator')
{
parent::__construct($input, $flags, $iterator_class);
}
/**
* Factory method for var_export().
*
* @see http://php.net/oop5.magic#object.set-state
* @see http://php.net/var-export
* @param array $properties
* @return self
*/
public static function __set_state(array $properties)
{
$document = new static();
$document->exchangeArray($properties);
return $document;
}
/**
* Serialize the document to BSON.
*
* @see http://php.net/mongodb-bson-serializable.bsonserialize
* @return object
*/
public function bsonSerialize()
{
return (object) $this->getArrayCopy();
}
/**
* Unserialize the document to BSON.
*
* @see http://php.net/mongodb-bson-unserializable.bsonunserialize
* @param array $data Array data
*/
public function bsonUnserialize(array $data)
{
parent::__construct($data, ArrayObject::ARRAY_AS_PROPS);
}
/**
* Serialize the array to JSON.
*
* @see http://php.net/jsonserializable.jsonserialize
* @return object
*/
public function jsonSerialize()
{
return (object) $this->getArrayCopy();
}
}
src/Model/IndexInfo.php 0000666 00000013117 13645314021 0010775 0 ustar 00 info = $info;
}
/**
* Return the collection info as an array.
*
* @see http://php.net/oop5.magic#language.oop5.magic.debuginfo
* @return array
*/
public function __debugInfo()
{
return $this->info;
}
/**
* Return the index name to allow casting IndexInfo to string.
*
* @return string
*/
public function __toString()
{
return $this->getName();
}
/**
* Return the index key.
*
* @return array
*/
public function getKey()
{
return (array) $this->info['key'];
}
/**
* Return the index name.
*
* @return string
*/
public function getName()
{
return (string) $this->info['name'];
}
/**
* Return the index namespace (e.g. "db.collection").
*
* @return string
*/
public function getNamespace()
{
return (string) $this->info['ns'];
}
/**
* Return the index version.
*
* @return integer
*/
public function getVersion()
{
return (integer) $this->info['v'];
}
/**
* Return whether or not this index is of type 2dsphere.
*
* @return boolean
*/
public function is2dSphere()
{
return array_search('2dsphere', $this->getKey(), true) !== false;
}
/**
* Return whether or not this index is of type geoHaystack.
*
* @return boolean
*/
public function isGeoHaystack()
{
return array_search('geoHaystack', $this->getKey(), true) !== false;
}
/**
* Return whether this is a sparse index.
*
* @see http://docs.mongodb.org/manual/core/index-sparse/
* @return boolean
*/
public function isSparse()
{
return ! empty($this->info['sparse']);
}
/**
* Return whether or not this index is of type text.
*
* @return boolean
*/
public function isText()
{
return array_search('text', $this->getKey(), true) !== false;
}
/**
* Return whether this is a TTL index.
*
* @see http://docs.mongodb.org/manual/core/index-ttl/
* @return boolean
*/
public function isTtl()
{
return array_key_exists('expireAfterSeconds', $this->info);
}
/**
* Return whether this is a unique index.
*
* @see http://docs.mongodb.org/manual/core/index-unique/
* @return boolean
*/
public function isUnique()
{
return ! empty($this->info['unique']);
}
/**
* Check whether a field exists in the index information.
*
* @see http://php.net/arrayaccess.offsetexists
* @param mixed $key
* @return boolean
*/
public function offsetExists($key)
{
return array_key_exists($key, $this->info);
}
/**
* Return the field's value from the index information.
*
* This method satisfies the Enumerating Indexes specification's requirement
* that index fields be made accessible under their original names. It may
* also be used to access fields that do not have a helper method.
*
* @see http://php.net/arrayaccess.offsetget
* @see https://github.com/mongodb/specifications/blob/master/source/enumerate-indexes.rst#getting-full-index-information
* @param mixed $key
* @return mixed
*/
public function offsetGet($key)
{
return $this->info[$key];
}
/**
* Not supported.
*
* @see http://php.net/arrayaccess.offsetset
* @param mixed $key
* @param mixed $value
* @throws BadMethodCallException
*/
public function offsetSet($key, $value)
{
throw BadMethodCallException::classIsImmutable(self::class);
}
/**
* Not supported.
*
* @see http://php.net/arrayaccess.offsetunset
* @param mixed $key
* @throws BadMethodCallException
*/
public function offsetUnset($key)
{
throw BadMethodCallException::classIsImmutable(self::class);
}
}
src/Model/IndexInfoIteratorIterator.php 0000666 00000003726 13645314021 0014226 0 ustar 00 ns = $ns;
}
/**
* Return the current element as an IndexInfo instance.
*
* @see IndexInfoIterator::current()
* @see http://php.net/iterator.current
* @return IndexInfo
*/
public function current()
{
$info = parent::current();
if (! array_key_exists('ns', $info) && $this->ns !== null) {
$info['ns'] = $this->ns;
}
return new IndexInfo($info);
}
}
src/Model/IndexInput.php 0000666 00000006225 13645314021 0011203 0 ustar 00 $order) {
if (! is_int($order) && ! is_float($order) && ! is_string($order)) {
throw InvalidArgumentException::invalidType(sprintf('order value for "%s" field within "key" option', $fieldName), $order, 'numeric or string');
}
}
if (! isset($index['ns'])) {
throw new InvalidArgumentException('Required "ns" option is missing from index specification');
}
if (! is_string($index['ns'])) {
throw InvalidArgumentException::invalidType('"ns" option', $index['ns'], 'string');
}
if (! isset($index['name'])) {
$index['name'] = generate_index_name($index['key']);
}
if (! is_string($index['name'])) {
throw InvalidArgumentException::invalidType('"name" option', $index['name'], 'string');
}
$this->index = $index;
}
/**
* Return the index name.
*
* @return string
*/
public function __toString()
{
return $this->index['name'];
}
/**
* Serialize the index information to BSON for index creation.
*
* @see \MongoDB\Collection::createIndexes()
* @see http://php.net/mongodb-bson-serializable.bsonserialize
* @return array
*/
public function bsonSerialize()
{
return $this->index;
}
}
src/Model/BSONIterator.php 0000666 00000007610 13645314021 0011366 0 ustar 00 buffer = $data;
$this->bufferLength = strlen($data);
$this->options = $options;
}
/**
* @see http://php.net/iterator.current
* @return mixed
*/
public function current()
{
return $this->current;
}
/**
* @see http://php.net/iterator.key
* @return mixed
*/
public function key()
{
return $this->key;
}
/**
* @see http://php.net/iterator.next
* @return void
*/
public function next()
{
$this->key++;
$this->current = null;
$this->advance();
}
/**
* @see http://php.net/iterator.rewind
* @return void
*/
public function rewind()
{
$this->key = 0;
$this->position = 0;
$this->current = null;
$this->advance();
}
/**
* @see http://php.net/iterator.valid
* @return boolean
*/
public function valid()
{
return $this->current !== null;
}
private function advance()
{
if ($this->position === $this->bufferLength) {
return;
}
if (($this->bufferLength - $this->position) < self::$bsonSize) {
throw new UnexpectedValueException(sprintf('Expected at least %d bytes; %d remaining', self::$bsonSize, $this->bufferLength - $this->position));
}
list(,$documentLength) = unpack('V', substr($this->buffer, $this->position, self::$bsonSize));
if (($this->bufferLength - $this->position) < $documentLength) {
throw new UnexpectedValueException(sprintf('Expected %d bytes; %d remaining', $documentLength, $this->bufferLength - $this->position));
}
$this->current = toPHP(substr($this->buffer, $this->position, $documentLength), $this->options['typeMap']);
$this->position += $documentLength;
}
}
src/Model/DatabaseInfo.php 0000666 00000006323 13645314021 0011433 0 ustar 00 info = $info;
}
/**
* Return the collection info as an array.
*
* @see http://php.net/oop5.magic#language.oop5.magic.debuginfo
* @return array
*/
public function __debugInfo()
{
return $this->info;
}
/**
* Return the database name.
*
* @return string
*/
public function getName()
{
return (string) $this->info['name'];
}
/**
* Return the databases size on disk (in bytes).
*
* @return integer
*/
public function getSizeOnDisk()
{
/* The MongoDB server might return this number as an integer or float */
return (integer) $this->info['sizeOnDisk'];
}
/**
* Return whether the database is empty.
*
* @return boolean
*/
public function isEmpty()
{
return (boolean) $this->info['empty'];
}
/**
* Check whether a field exists in the database information.
*
* @see http://php.net/arrayaccess.offsetexists
* @param mixed $key
* @return boolean
*/
public function offsetExists($key)
{
return array_key_exists($key, $this->info);
}
/**
* Return the field's value from the database information.
*
* @see http://php.net/arrayaccess.offsetget
* @param mixed $key
* @return mixed
*/
public function offsetGet($key)
{
return $this->info[$key];
}
/**
* Not supported.
*
* @see http://php.net/arrayaccess.offsetset
* @param mixed $key
* @param mixed $value
* @throws BadMethodCallException
*/
public function offsetSet($key, $value)
{
throw BadMethodCallException::classIsImmutable(self::class);
}
/**
* Not supported.
*
* @see http://php.net/arrayaccess.offsetunset
* @param mixed $key
* @throws BadMethodCallException
*/
public function offsetUnset($key)
{
throw BadMethodCallException::classIsImmutable(self::class);
}
}
src/Model/CollectionInfo.php 0000666 00000007751 13645314021 0012030 0 ustar 00 info = $info;
}
/**
* Return the collection info as an array.
*
* @see http://php.net/oop5.magic#language.oop5.magic.debuginfo
* @return array
*/
public function __debugInfo()
{
return $this->info;
}
/**
* Return the maximum number of documents to keep in the capped collection.
*
* @return integer|null
*/
public function getCappedMax()
{
/* The MongoDB server might return this number as an integer or float */
return isset($this->info['options']['max']) ? (integer) $this->info['options']['max'] : null;
}
/**
* Return the maximum size (in bytes) of the capped collection.
*
* @return integer|null
*/
public function getCappedSize()
{
/* The MongoDB server might return this number as an integer or float */
return isset($this->info['options']['size']) ? (integer) $this->info['options']['size'] : null;
}
/**
* Return the collection name.
*
* @return string
*/
public function getName()
{
return (string) $this->info['name'];
}
/**
* Return the collection options.
*
* @return array
*/
public function getOptions()
{
return isset($this->info['options']) ? (array) $this->info['options'] : [];
}
/**
* Return whether the collection is a capped collection.
*
* @return boolean
*/
public function isCapped()
{
return ! empty($this->info['options']['capped']);
}
/**
* Check whether a field exists in the collection information.
*
* @see http://php.net/arrayaccess.offsetexists
* @param mixed $key
* @return boolean
*/
public function offsetExists($key)
{
return array_key_exists($key, $this->info);
}
/**
* Return the field's value from the collection information.
*
* @see http://php.net/arrayaccess.offsetget
* @param mixed $key
* @return mixed
*/
public function offsetGet($key)
{
return $this->info[$key];
}
/**
* Not supported.
*
* @see http://php.net/arrayaccess.offsetset
* @param mixed $key
* @param mixed $value
* @throws BadMethodCallException
*/
public function offsetSet($key, $value)
{
throw BadMethodCallException::classIsImmutable(self::class);
}
/**
* Not supported.
*
* @see http://php.net/arrayaccess.offsetunset
* @param mixed $key
* @throws BadMethodCallException
*/
public function offsetUnset($key)
{
throw BadMethodCallException::classIsImmutable(self::class);
}
}
src/Model/CollectionInfoCommandIterator.php 0000666 00000003672 13645314021 0015037 0 ustar 00 databaseName = $databaseName;
}
/**
* Return the current element as a CollectionInfo instance.
*
* @see CollectionInfoIterator::current()
* @see http://php.net/iterator.current
* @return CollectionInfo
*/
public function current()
{
$info = parent::current();
if ($this->databaseName !== null && isset($info['idIndex']) && ! isset($info['idIndex']['ns'])) {
$info['idIndex']['ns'] = $this->databaseName . '.' . $info['name'];
}
return new CollectionInfo($info);
}
}
src/Model/ChangeStreamIterator.php 0000666 00000022350 13645314021 0013164 0 ustar 00 batchSize = $firstBatchSize;
$this->isRewindNop = ($firstBatchSize === 0);
$this->postBatchResumeToken = $postBatchResumeToken;
$this->resumeToken = $initialResumeToken;
$this->server = $cursor->getServer();
}
/** @internal */
final public function commandFailed(CommandFailedEvent $event)
{
}
/** @internal */
final public function commandStarted(CommandStartedEvent $event)
{
if ($event->getCommandName() !== 'getMore') {
return;
}
$this->batchPosition = 0;
$this->batchSize = null;
$this->postBatchResumeToken = null;
}
/** @internal */
final public function commandSucceeded(CommandSucceededEvent $event)
{
if ($event->getCommandName() !== 'getMore') {
return;
}
$reply = $event->getReply();
if (! isset($reply->cursor->nextBatch) || ! is_array($reply->cursor->nextBatch)) {
throw new UnexpectedValueException('getMore command did not return a "cursor.nextBatch" array');
}
$this->batchSize = count($reply->cursor->nextBatch);
if (isset($reply->cursor->postBatchResumeToken) && is_object($reply->cursor->postBatchResumeToken)) {
$this->postBatchResumeToken = $reply->cursor->postBatchResumeToken;
}
}
/**
* @see https://php.net/iteratoriterator.current
* @return mixed
*/
public function current()
{
return $this->isValid ? parent::current() : null;
}
/**
* Returns the resume token for the iterator's current position.
*
* Null may be returned if no change documents have been iterated and the
* server did not include a postBatchResumeToken in its aggregate or getMore
* command response.
*
* @return array|object|null
*/
public function getResumeToken()
{
return $this->resumeToken;
}
/**
* Returns the server the cursor is running on.
*/
public function getServer() : Server
{
return $this->server;
}
/**
* @see https://php.net/iteratoriterator.key
* @return mixed
*/
public function key()
{
return $this->isValid ? parent::key() : null;
}
/**
* @see https://php.net/iteratoriterator.rewind
* @return void
*/
public function next()
{
/* Determine if advancing the iterator will execute a getMore command
* (i.e. we are already positioned at the end of the current batch). If
* so, rely on the APM callbacks to reset $batchPosition and update
* $batchSize. Otherwise, we can forgo APM and manually increment
* $batchPosition after calling next(). */
$getMore = $this->isAtEndOfBatch();
if ($getMore) {
addSubscriber($this);
}
try {
parent::next();
$this->onIteration(! $getMore);
} finally {
if ($getMore) {
removeSubscriber($this);
}
}
}
/**
* @see https://php.net/iteratoriterator.rewind
* @return void
*/
public function rewind()
{
if ($this->isRewindNop) {
return;
}
parent::rewind();
$this->onIteration(false);
}
/**
* @see https://php.net/iteratoriterator.valid
* @return boolean
*/
public function valid()
{
return $this->isValid;
}
/**
* Extracts the resume token (i.e. "_id" field) from a change document.
*
* @param array|object $document Change document
* @return array|object
* @throws InvalidArgumentException
* @throws ResumeTokenException if the resume token is not found or invalid
*/
private function extractResumeToken($document)
{
if (! is_array($document) && ! is_object($document)) {
throw InvalidArgumentException::invalidType('$document', $document, 'array or object');
}
if ($document instanceof Serializable) {
return $this->extractResumeToken($document->bsonSerialize());
}
$resumeToken = is_array($document)
? ($document['_id'] ?? null)
: ($document->_id ?? null);
if (! isset($resumeToken)) {
$this->isValid = false;
throw ResumeTokenException::notFound();
}
if (! is_array($resumeToken) && ! is_object($resumeToken)) {
$this->isValid = false;
throw ResumeTokenException::invalidType($resumeToken);
}
return $resumeToken;
}
/**
* Return whether the iterator is positioned at the end of the batch.
*
* @return boolean
*/
private function isAtEndOfBatch()
{
return $this->batchPosition + 1 >= $this->batchSize;
}
/**
* Perform housekeeping after an iteration event.
*
* @see https://github.com/mongodb/specifications/blob/master/source/change-streams/change-streams.rst#updating-the-cached-resume-token
* @param boolean $incrementBatchPosition
*/
private function onIteration($incrementBatchPosition)
{
$this->isValid = parent::valid();
/* Disable rewind()'s NOP behavior once we advance to a valid position.
* This will allow the driver to throw a LogicException if rewind() is
* called after the cursor has advanced past its first element. */
if ($this->isRewindNop && $this->isValid) {
$this->isRewindNop = false;
}
if ($incrementBatchPosition && $this->isValid) {
$this->batchPosition++;
}
/* If the iterator is positioned at the end of the batch, apply the
* postBatchResumeToken if it's available. This handles both the case
* where the current batch is empty (since onIteration() will be called
* after a successful getMore) and when the iterator has advanced to the
* last document in its current batch. Otherwise, extract a resume token
* from the current document if possible. */
if ($this->isAtEndOfBatch() && $this->postBatchResumeToken !== null) {
$this->resumeToken = $this->postBatchResumeToken;
} elseif ($this->isValid) {
$this->resumeToken = $this->extractResumeToken($this->current());
}
}
}
src/Model/DatabaseInfoLegacyIterator.php 0000666 00000004535 13645314021 0014275 0 ustar 00 databases = $databases;
}
/**
* Return the current element as a DatabaseInfo instance.
*
* @see DatabaseInfoIterator::current()
* @see http://php.net/iterator.current
* @return DatabaseInfo
*/
public function current()
{
return new DatabaseInfo(current($this->databases));
}
/**
* Return the key of the current element.
*
* @see http://php.net/iterator.key
* @return integer
*/
public function key()
{
return key($this->databases);
}
/**
* Move forward to next element.
*
* @see http://php.net/iterator.next
*/
public function next()
{
next($this->databases);
}
/**
* Rewind the Iterator to the first element.
*
* @see http://php.net/iterator.rewind
*/
public function rewind()
{
reset($this->databases);
}
/**
* Checks if current position is valid.
*
* @see http://php.net/iterator.valid
* @return boolean
*/
public function valid()
{
return key($this->databases) !== null;
}
}
src/Model/CachingIterator.php 0000666 00000007520 13645314021 0012161 0 ustar 00 iterator = new IteratorIterator($traversable);
$this->iterator->rewind();
$this->storeCurrentItem();
}
/**
* @see http://php.net/countable.count
* @return integer
*/
public function count()
{
$this->exhaustIterator();
return count($this->items);
}
/**
* @see http://php.net/iterator.current
* @return mixed
*/
public function current()
{
return current($this->items);
}
/**
* @see http://php.net/iterator.key
* @return mixed
*/
public function key()
{
return key($this->items);
}
/**
* @see http://php.net/iterator.next
* @return void
*/
public function next()
{
if (! $this->iteratorExhausted) {
$this->iteratorAdvanced = true;
$this->iterator->next();
$this->storeCurrentItem();
$this->iteratorExhausted = ! $this->iterator->valid();
}
next($this->items);
}
/**
* @see http://php.net/iterator.rewind
* @return void
*/
public function rewind()
{
/* If the iterator has advanced, exhaust it now so that future iteration
* can rely on the cache.
*/
if ($this->iteratorAdvanced) {
$this->exhaustIterator();
}
reset($this->items);
}
/**
* @see http://php.net/iterator.valid
* @return boolean
*/
public function valid()
{
return $this->key() !== null;
}
/**
* Ensures that the inner iterator is fully consumed and cached.
*/
private function exhaustIterator()
{
while (! $this->iteratorExhausted) {
$this->next();
}
}
/**
* Stores the current item in the cache.
*/
private function storeCurrentItem()
{
$key = $this->iterator->key();
if ($key === null) {
return;
}
$this->items[$key] = $this->iterator->current();
}
}
src/Model/IndexInfoIterator.php 0000666 00000001746 13645314021 0012514 0 ustar 00 $value) {
$this[$key] = recursive_copy($value);
}
}
/**
* Factory method for var_export().
*
* @see http://php.net/oop5.magic#object.set-state
* @see http://php.net/var-export
* @param array $properties
* @return self
*/
public static function __set_state(array $properties)
{
$array = new static();
$array->exchangeArray($properties);
return $array;
}
/**
* Serialize the array to BSON.
*
* The array data will be numerically reindexed to ensure that it is stored
* as a BSON array.
*
* @see http://php.net/mongodb-bson-serializable.bsonserialize
* @return array
*/
public function bsonSerialize()
{
return array_values($this->getArrayCopy());
}
/**
* Unserialize the document to BSON.
*
* @see http://php.net/mongodb-bson-unserializable.bsonunserialize
* @param array $data Array data
*/
public function bsonUnserialize(array $data)
{
self::__construct($data);
}
/**
* Serialize the array to JSON.
*
* The array data will be numerically reindexed to ensure that it is stored
* as a JSON array.
*
* @see http://php.net/jsonserializable.jsonserialize
* @return array
*/
public function jsonSerialize()
{
return array_values($this->getArrayCopy());
}
}
src/Model/DatabaseInfoIterator.php 0000666 00000001756 13645314021 0013152 0 ustar 00 writeResult = $writeResult;
$this->isAcknowledged = $writeResult->isAcknowledged();
}
/**
* Return the number of documents that were matched by the filter.
*
* This method should only be called if the write was acknowledged.
*
* @see UpdateResult::isAcknowledged()
* @return integer
* @throws BadMethodCallException is the write result is unacknowledged
*/
public function getMatchedCount()
{
if ($this->isAcknowledged) {
return $this->writeResult->getMatchedCount();
}
throw BadMethodCallException::unacknowledgedWriteResultAccess(__METHOD__);
}
/**
* Return the number of documents that were modified.
*
* This value is undefined (i.e. null) if the write executed as a legacy
* operation instead of command.
*
* This method should only be called if the write was acknowledged.
*
* @see UpdateResult::isAcknowledged()
* @return integer|null
* @throws BadMethodCallException is the write result is unacknowledged
*/
public function getModifiedCount()
{
if ($this->isAcknowledged) {
return $this->writeResult->getModifiedCount();
}
throw BadMethodCallException::unacknowledgedWriteResultAccess(__METHOD__);
}
/**
* Return the number of documents that were upserted.
*
* This method should only be called if the write was acknowledged.
*
* @see UpdateResult::isAcknowledged()
* @return integer
* @throws BadMethodCallException is the write result is unacknowledged
*/
public function getUpsertedCount()
{
if ($this->isAcknowledged) {
return $this->writeResult->getUpsertedCount();
}
throw BadMethodCallException::unacknowledgedWriteResultAccess(__METHOD__);
}
/**
* Return the ID of the document inserted by an upsert operation.
*
* If the document had an ID prior to upserting (i.e. the server did not
* need to generate an ID), this will contain its "_id". Any
* server-generated ID will be a MongoDB\BSON\ObjectId instance.
*
* This value is undefined (i.e. null) if an upsert did not take place.
*
* This method should only be called if the write was acknowledged.
*
* @see UpdateResult::isAcknowledged()
* @return mixed|null
* @throws BadMethodCallException is the write result is unacknowledged
*/
public function getUpsertedId()
{
if ($this->isAcknowledged) {
foreach ($this->writeResult->getUpsertedIds() as $id) {
return $id;
}
return null;
}
throw BadMethodCallException::unacknowledgedWriteResultAccess(__METHOD__);
}
/**
* Return whether this update was acknowledged by the server.
*
* If the update was not acknowledged, other fields from the WriteResult
* (e.g. matchedCount) will be undefined and their getter methods should not
* be invoked.
*
* @return boolean
*/
public function isAcknowledged()
{
return $this->isAcknowledged;
}
}
src/Client.php 0000666 00000032356 13645314021 0007276 0 ustar 00 BSONArray::class,
'document' => BSONDocument::class,
'root' => BSONDocument::class,
];
/** @var integer */
private static $wireVersionForReadConcern = 4;
/** @var integer */
private static $wireVersionForWritableCommandWriteConcern = 5;
/** @var string */
private static $handshakeSeparator = ' / ';
/** @var string|null */
private static $version;
/** @var Manager */
private $manager;
/** @var ReadConcern */
private $readConcern;
/** @var ReadPreference */
private $readPreference;
/** @var string */
private $uri;
/** @var array */
private $typeMap;
/** @var WriteConcern */
private $writeConcern;
/**
* Constructs a new Client instance.
*
* This is the preferred class for connecting to a MongoDB server or
* cluster of servers. It serves as a gateway for accessing individual
* databases and collections.
*
* Supported driver-specific options:
*
* * typeMap (array): Default type map for cursors and BSON documents.
*
* Other options are documented in MongoDB\Driver\Manager::__construct().
*
* @see http://docs.mongodb.org/manual/reference/connection-string/
* @see http://php.net/manual/en/mongodb-driver-manager.construct.php
* @see http://php.net/manual/en/mongodb.persistence.php#mongodb.persistence.typemaps
* @param string $uri MongoDB connection string
* @param array $uriOptions Additional connection string options
* @param array $driverOptions Driver-specific options
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverInvalidArgumentException for parameter/option parsing errors in the driver
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function __construct($uri = 'mongodb://127.0.0.1/', array $uriOptions = [], array $driverOptions = [])
{
$driverOptions += ['typeMap' => self::$defaultTypeMap];
if (! is_array($driverOptions['typeMap'])) {
throw InvalidArgumentException::invalidType('"typeMap" driver option', $driverOptions['typeMap'], 'array');
}
if (isset($driverOptions['autoEncryption']['keyVaultClient'])) {
if ($driverOptions['autoEncryption']['keyVaultClient'] instanceof self) {
$driverOptions['autoEncryption']['keyVaultClient'] = $driverOptions['autoEncryption']['keyVaultClient']->manager;
} elseif (! $driverOptions['autoEncryption']['keyVaultClient'] instanceof Manager) {
throw InvalidArgumentException::invalidType('"keyVaultClient" autoEncryption option', $driverOptions['autoEncryption']['keyVaultClient'], [self::class, Manager::class]);
}
}
$driverOptions['driver'] = $this->mergeDriverInfo($driverOptions['driver'] ?? []);
$this->uri = (string) $uri;
$this->typeMap = $driverOptions['typeMap'] ?? null;
unset($driverOptions['typeMap']);
$this->manager = new Manager($uri, $uriOptions, $driverOptions);
$this->readConcern = $this->manager->getReadConcern();
$this->readPreference = $this->manager->getReadPreference();
$this->writeConcern = $this->manager->getWriteConcern();
}
/**
* Return internal properties for debugging purposes.
*
* @see http://php.net/manual/en/language.oop5.magic.php#language.oop5.magic.debuginfo
* @return array
*/
public function __debugInfo()
{
return [
'manager' => $this->manager,
'uri' => $this->uri,
'typeMap' => $this->typeMap,
'writeConcern' => $this->writeConcern,
];
}
/**
* Select a database.
*
* Note: databases whose names contain special characters (e.g. "-") may
* be selected with complex syntax (e.g. $client->{"that-database"}) or
* {@link selectDatabase()}.
*
* @see http://php.net/oop5.overloading#object.get
* @see http://php.net/types.string#language.types.string.parsing.complex
* @param string $databaseName Name of the database to select
* @return Database
*/
public function __get($databaseName)
{
return $this->selectDatabase($databaseName);
}
/**
* Return the connection string (i.e. URI).
*
* @return string
*/
public function __toString()
{
return $this->uri;
}
/**
* Returns a ClientEncryption instance for explicit encryption and decryption
*
* @param array $options Encryption options
*
* @return ClientEncryption
*/
public function createClientEncryption(array $options)
{
if (isset($options['keyVaultClient'])) {
if ($options['keyVaultClient'] instanceof self) {
$options['keyVaultClient'] = $options['keyVaultClient']->manager;
} elseif (! $options['keyVaultClient'] instanceof Manager) {
throw InvalidArgumentException::invalidType('"keyVaultClient" option', $options['keyVaultClient'], [self::class, Manager::class]);
}
}
return $this->manager->createClientEncryption($options);
}
/**
* Drop a database.
*
* @see DropDatabase::__construct() for supported options
* @param string $databaseName Database name
* @param array $options Additional options
* @return array|object Command result document
* @throws UnsupportedException if options are unsupported on the selected server
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function dropDatabase($databaseName, array $options = [])
{
if (! isset($options['typeMap'])) {
$options['typeMap'] = $this->typeMap;
}
$server = select_server($this->manager, $options);
if (! isset($options['writeConcern']) && server_supports_feature($server, self::$wireVersionForWritableCommandWriteConcern) && ! is_in_transaction($options)) {
$options['writeConcern'] = $this->writeConcern;
}
$operation = new DropDatabase($databaseName, $options);
return $operation->execute($server);
}
/**
* Return the Manager.
*
* @return Manager
*/
public function getManager()
{
return $this->manager;
}
/**
* Return the read concern for this client.
*
* @see http://php.net/manual/en/mongodb-driver-readconcern.isdefault.php
* @return ReadConcern
*/
public function getReadConcern()
{
return $this->readConcern;
}
/**
* Return the read preference for this client.
*
* @return ReadPreference
*/
public function getReadPreference()
{
return $this->readPreference;
}
/**
* Return the type map for this client.
*
* @return array
*/
public function getTypeMap()
{
return $this->typeMap;
}
/**
* Return the write concern for this client.
*
* @see http://php.net/manual/en/mongodb-driver-writeconcern.isdefault.php
* @return WriteConcern
*/
public function getWriteConcern()
{
return $this->writeConcern;
}
/**
* List databases.
*
* @see ListDatabases::__construct() for supported options
* @param array $options
* @return DatabaseInfoIterator
* @throws UnexpectedValueException if the command response was malformed
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function listDatabases(array $options = [])
{
$operation = new ListDatabases($options);
$server = select_server($this->manager, $options);
return $operation->execute($server);
}
/**
* Select a collection.
*
* @see Collection::__construct() for supported options
* @param string $databaseName Name of the database containing the collection
* @param string $collectionName Name of the collection to select
* @param array $options Collection constructor options
* @return Collection
* @throws InvalidArgumentException for parameter/option parsing errors
*/
public function selectCollection($databaseName, $collectionName, array $options = [])
{
$options += ['typeMap' => $this->typeMap];
return new Collection($this->manager, $databaseName, $collectionName, $options);
}
/**
* Select a database.
*
* @see Database::__construct() for supported options
* @param string $databaseName Name of the database to select
* @param array $options Database constructor options
* @return Database
* @throws InvalidArgumentException for parameter/option parsing errors
*/
public function selectDatabase($databaseName, array $options = [])
{
$options += ['typeMap' => $this->typeMap];
return new Database($this->manager, $databaseName, $options);
}
/**
* Start a new client session.
*
* @see http://php.net/manual/en/mongodb-driver-manager.startsession.php
* @param array $options Session options
* @return Session
*/
public function startSession(array $options = [])
{
return $this->manager->startSession($options);
}
/**
* Create a change stream for watching changes to the cluster.
*
* @see Watch::__construct() for supported options
* @param array $pipeline List of pipeline operations
* @param array $options Command options
* @return ChangeStream
* @throws InvalidArgumentException for parameter/option parsing errors
*/
public function watch(array $pipeline = [], array $options = [])
{
if (! isset($options['readPreference']) && ! is_in_transaction($options)) {
$options['readPreference'] = $this->readPreference;
}
$server = select_server($this->manager, $options);
if (! isset($options['readConcern']) && server_supports_feature($server, self::$wireVersionForReadConcern) && ! is_in_transaction($options)) {
$options['readConcern'] = $this->readConcern;
}
if (! isset($options['typeMap'])) {
$options['typeMap'] = $this->typeMap;
}
$operation = new Watch($this->manager, null, null, $pipeline, $options);
return $operation->execute($server);
}
private static function getVersion() : string
{
if (self::$version === null) {
try {
self::$version = PrettyVersions::getVersion('mongodb/mongodb')->getPrettyVersion();
} catch (Throwable $t) {
return 'unknown';
}
}
return self::$version;
}
private function mergeDriverInfo(array $driver) : array
{
$mergedDriver = [
'name' => 'PHPLIB',
'version' => self::getVersion(),
];
if (isset($driver['name'])) {
if (! is_string($driver['name'])) {
throw InvalidArgumentException::invalidType('"name" handshake option', $driver['name'], 'string');
}
$mergedDriver['name'] .= self::$handshakeSeparator . $driver['name'];
}
if (isset($driver['version'])) {
if (! is_string($driver['version'])) {
throw InvalidArgumentException::invalidType('"version" handshake option', $driver['version'], 'string');
}
$mergedDriver['version'] .= self::$handshakeSeparator . $driver['version'];
}
if (isset($driver['platform'])) {
$mergedDriver['platform'] = $driver['platform'];
}
return $mergedDriver;
}
}
src/Database.php 0000666 00000045603 13645314021 0007563 0 ustar 00 BSONArray::class,
'document' => BSONDocument::class,
'root' => BSONDocument::class,
];
/** @var integer */
private static $wireVersionForReadConcern = 4;
/** @var integer */
private static $wireVersionForWritableCommandWriteConcern = 5;
/** @var integer */
private static $wireVersionForReadConcernWithWriteStage = 8;
/** @var string */
private $databaseName;
/** @var Manager */
private $manager;
/** @var ReadConcern */
private $readConcern;
/** @var ReadPreference */
private $readPreference;
/** @var array */
private $typeMap;
/** @var WriteConcern */
private $writeConcern;
/**
* Constructs new Database instance.
*
* This class provides methods for database-specific operations and serves
* as a gateway for accessing collections.
*
* Supported options:
*
* * readConcern (MongoDB\Driver\ReadConcern): The default read concern to
* use for database operations and selected collections. Defaults to the
* Manager's read concern.
*
* * readPreference (MongoDB\Driver\ReadPreference): The default read
* preference to use for database operations and selected collections.
* Defaults to the Manager's read preference.
*
* * typeMap (array): Default type map for cursors and BSON documents.
*
* * writeConcern (MongoDB\Driver\WriteConcern): The default write concern
* to use for database operations and selected collections. Defaults to
* the Manager's write concern.
*
* @param Manager $manager Manager instance from the driver
* @param string $databaseName Database name
* @param array $options Database options
* @throws InvalidArgumentException for parameter/option parsing errors
*/
public function __construct(Manager $manager, $databaseName, array $options = [])
{
if (strlen($databaseName) < 1) {
throw new InvalidArgumentException('$databaseName is invalid: ' . $databaseName);
}
if (isset($options['readConcern']) && ! $options['readConcern'] instanceof ReadConcern) {
throw InvalidArgumentException::invalidType('"readConcern" option', $options['readConcern'], ReadConcern::class);
}
if (isset($options['readPreference']) && ! $options['readPreference'] instanceof ReadPreference) {
throw InvalidArgumentException::invalidType('"readPreference" option', $options['readPreference'], ReadPreference::class);
}
if (isset($options['typeMap']) && ! is_array($options['typeMap'])) {
throw InvalidArgumentException::invalidType('"typeMap" option', $options['typeMap'], 'array');
}
if (isset($options['writeConcern']) && ! $options['writeConcern'] instanceof WriteConcern) {
throw InvalidArgumentException::invalidType('"writeConcern" option', $options['writeConcern'], WriteConcern::class);
}
$this->manager = $manager;
$this->databaseName = (string) $databaseName;
$this->readConcern = $options['readConcern'] ?? $this->manager->getReadConcern();
$this->readPreference = $options['readPreference'] ?? $this->manager->getReadPreference();
$this->typeMap = $options['typeMap'] ?? self::$defaultTypeMap;
$this->writeConcern = $options['writeConcern'] ?? $this->manager->getWriteConcern();
}
/**
* Return internal properties for debugging purposes.
*
* @see http://php.net/manual/en/language.oop5.magic.php#language.oop5.magic.debuginfo
* @return array
*/
public function __debugInfo()
{
return [
'databaseName' => $this->databaseName,
'manager' => $this->manager,
'readConcern' => $this->readConcern,
'readPreference' => $this->readPreference,
'typeMap' => $this->typeMap,
'writeConcern' => $this->writeConcern,
];
}
/**
* Select a collection within this database.
*
* Note: collections whose names contain special characters (e.g. ".") may
* be selected with complex syntax (e.g. $database->{"system.profile"}) or
* {@link selectCollection()}.
*
* @see http://php.net/oop5.overloading#object.get
* @see http://php.net/types.string#language.types.string.parsing.complex
* @param string $collectionName Name of the collection to select
* @return Collection
*/
public function __get($collectionName)
{
return $this->selectCollection($collectionName);
}
/**
* Return the database name.
*
* @return string
*/
public function __toString()
{
return $this->databaseName;
}
/**
* Runs an aggregation framework pipeline on the database for pipeline
* stages that do not require an underlying collection, such as $currentOp
* and $listLocalSessions. Requires MongoDB >= 3.6
*
* @see Aggregate::__construct() for supported options
* @param array $pipeline List of pipeline operations
* @param array $options Command options
* @return Traversable
* @throws UnexpectedValueException if the command response was malformed
* @throws UnsupportedException if options are not supported by the selected server
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function aggregate(array $pipeline, array $options = [])
{
$hasWriteStage = is_last_pipeline_operator_write($pipeline);
if (! isset($options['readPreference']) && ! is_in_transaction($options)) {
$options['readPreference'] = $this->readPreference;
}
if ($hasWriteStage) {
$options['readPreference'] = new ReadPreference(ReadPreference::RP_PRIMARY);
}
$server = select_server($this->manager, $options);
/* MongoDB 4.2 and later supports a read concern when an $out stage is
* being used, but earlier versions do not.
*
* A read concern is also not compatible with transactions.
*/
if (! isset($options['readConcern']) &&
server_supports_feature($server, self::$wireVersionForReadConcern) &&
! is_in_transaction($options) &&
( ! $hasWriteStage || server_supports_feature($server, self::$wireVersionForReadConcernWithWriteStage))
) {
$options['readConcern'] = $this->readConcern;
}
if (! isset($options['typeMap'])) {
$options['typeMap'] = $this->typeMap;
}
if ($hasWriteStage &&
! isset($options['writeConcern']) &&
server_supports_feature($server, self::$wireVersionForWritableCommandWriteConcern) &&
! is_in_transaction($options)) {
$options['writeConcern'] = $this->writeConcern;
}
$operation = new Aggregate($this->databaseName, null, $pipeline, $options);
return $operation->execute($server);
}
/**
* Execute a command on this database.
*
* @see DatabaseCommand::__construct() for supported options
* @param array|object $command Command document
* @param array $options Options for command execution
* @return Cursor
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function command($command, array $options = [])
{
if (! isset($options['readPreference']) && ! is_in_transaction($options)) {
$options['readPreference'] = $this->readPreference;
}
if (! isset($options['typeMap'])) {
$options['typeMap'] = $this->typeMap;
}
$operation = new DatabaseCommand($this->databaseName, $command, $options);
$server = select_server($this->manager, $options);
return $operation->execute($server);
}
/**
* Create a new collection explicitly.
*
* @see CreateCollection::__construct() for supported options
* @param string $collectionName
* @param array $options
* @return array|object Command result document
* @throws UnsupportedException if options are not supported by the selected server
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function createCollection($collectionName, array $options = [])
{
if (! isset($options['typeMap'])) {
$options['typeMap'] = $this->typeMap;
}
$server = select_server($this->manager, $options);
if (! isset($options['writeConcern']) && server_supports_feature($server, self::$wireVersionForWritableCommandWriteConcern) && ! is_in_transaction($options)) {
$options['writeConcern'] = $this->writeConcern;
}
$operation = new CreateCollection($this->databaseName, $collectionName, $options);
return $operation->execute($server);
}
/**
* Drop this database.
*
* @see DropDatabase::__construct() for supported options
* @param array $options Additional options
* @return array|object Command result document
* @throws UnsupportedException if options are unsupported on the selected server
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function drop(array $options = [])
{
if (! isset($options['typeMap'])) {
$options['typeMap'] = $this->typeMap;
}
$server = select_server($this->manager, $options);
if (! isset($options['writeConcern']) && server_supports_feature($server, self::$wireVersionForWritableCommandWriteConcern) && ! is_in_transaction($options)) {
$options['writeConcern'] = $this->writeConcern;
}
$operation = new DropDatabase($this->databaseName, $options);
return $operation->execute($server);
}
/**
* Drop a collection within this database.
*
* @see DropCollection::__construct() for supported options
* @param string $collectionName Collection name
* @param array $options Additional options
* @return array|object Command result document
* @throws UnsupportedException if options are unsupported on the selected server
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function dropCollection($collectionName, array $options = [])
{
if (! isset($options['typeMap'])) {
$options['typeMap'] = $this->typeMap;
}
$server = select_server($this->manager, $options);
if (! isset($options['writeConcern']) && server_supports_feature($server, self::$wireVersionForWritableCommandWriteConcern) && ! is_in_transaction($options)) {
$options['writeConcern'] = $this->writeConcern;
}
$operation = new DropCollection($this->databaseName, $collectionName, $options);
return $operation->execute($server);
}
/**
* Returns the database name.
*
* @return string
*/
public function getDatabaseName()
{
return $this->databaseName;
}
/**
* Return the Manager.
*
* @return Manager
*/
public function getManager()
{
return $this->manager;
}
/**
* Return the read concern for this database.
*
* @see http://php.net/manual/en/mongodb-driver-readconcern.isdefault.php
* @return ReadConcern
*/
public function getReadConcern()
{
return $this->readConcern;
}
/**
* Return the read preference for this database.
*
* @return ReadPreference
*/
public function getReadPreference()
{
return $this->readPreference;
}
/**
* Return the type map for this database.
*
* @return array
*/
public function getTypeMap()
{
return $this->typeMap;
}
/**
* Return the write concern for this database.
*
* @see http://php.net/manual/en/mongodb-driver-writeconcern.isdefault.php
* @return WriteConcern
*/
public function getWriteConcern()
{
return $this->writeConcern;
}
/**
* Returns information for all collections in this database.
*
* @see ListCollections::__construct() for supported options
* @param array $options
* @return CollectionInfoIterator
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function listCollections(array $options = [])
{
$operation = new ListCollections($this->databaseName, $options);
$server = select_server($this->manager, $options);
return $operation->execute($server);
}
/**
* Modifies a collection or view.
*
* @see ModifyCollection::__construct() for supported options
* @param string $collectionName Collection or view to modify
* @param array $collectionOptions Collection or view options to assign
* @param array $options Command options
* @return array|object
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function modifyCollection($collectionName, array $collectionOptions, array $options = [])
{
if (! isset($options['typeMap'])) {
$options['typeMap'] = $this->typeMap;
}
$server = select_server($this->manager, $options);
if (! isset($options['writeConcern']) && server_supports_feature($server, self::$wireVersionForWritableCommandWriteConcern) && ! is_in_transaction($options)) {
$options['writeConcern'] = $this->writeConcern;
}
$operation = new ModifyCollection($this->databaseName, $collectionName, $collectionOptions, $options);
return $operation->execute($server);
}
/**
* Select a collection within this database.
*
* @see Collection::__construct() for supported options
* @param string $collectionName Name of the collection to select
* @param array $options Collection constructor options
* @return Collection
* @throws InvalidArgumentException for parameter/option parsing errors
*/
public function selectCollection($collectionName, array $options = [])
{
$options += [
'readConcern' => $this->readConcern,
'readPreference' => $this->readPreference,
'typeMap' => $this->typeMap,
'writeConcern' => $this->writeConcern,
];
return new Collection($this->manager, $this->databaseName, $collectionName, $options);
}
/**
* Select a GridFS bucket within this database.
*
* @see Bucket::__construct() for supported options
* @param array $options Bucket constructor options
* @return Bucket
* @throws InvalidArgumentException for parameter/option parsing errors
*/
public function selectGridFSBucket(array $options = [])
{
$options += [
'readConcern' => $this->readConcern,
'readPreference' => $this->readPreference,
'typeMap' => $this->typeMap,
'writeConcern' => $this->writeConcern,
];
return new Bucket($this->manager, $this->databaseName, $options);
}
/**
* Create a change stream for watching changes to the database.
*
* @see Watch::__construct() for supported options
* @param array $pipeline List of pipeline operations
* @param array $options Command options
* @return ChangeStream
* @throws InvalidArgumentException for parameter/option parsing errors
*/
public function watch(array $pipeline = [], array $options = [])
{
if (! isset($options['readPreference']) && ! is_in_transaction($options)) {
$options['readPreference'] = $this->readPreference;
}
$server = select_server($this->manager, $options);
if (! isset($options['readConcern']) && server_supports_feature($server, self::$wireVersionForReadConcern) && ! is_in_transaction($options)) {
$options['readConcern'] = $this->readConcern;
}
if (! isset($options['typeMap'])) {
$options['typeMap'] = $this->typeMap;
}
$operation = new Watch($this->manager, $this->databaseName, null, $pipeline, $options);
return $operation->execute($server);
}
/**
* Get a clone of this database with different options.
*
* @see Database::__construct() for supported options
* @param array $options Database constructor options
* @return Database
* @throws InvalidArgumentException for parameter/option parsing errors
*/
public function withOptions(array $options = [])
{
$options += [
'readConcern' => $this->readConcern,
'readPreference' => $this->readPreference,
'typeMap' => $this->typeMap,
'writeConcern' => $this->writeConcern,
];
return new Database($this->manager, $this->databaseName, $options);
}
}
src/Collection.php 0000666 00000131360 13645314021 0010146 0 ustar 00 BSONArray::class,
'document' => BSONDocument::class,
'root' => BSONDocument::class,
];
/** @var integer */
private static $wireVersionForFindAndModifyWriteConcern = 4;
/** @var integer */
private static $wireVersionForReadConcern = 4;
/** @var integer */
private static $wireVersionForWritableCommandWriteConcern = 5;
/** @var integer */
private static $wireVersionForReadConcernWithWriteStage = 8;
/** @var string */
private $collectionName;
/** @var string */
private $databaseName;
/** @var Manager */
private $manager;
/** @var ReadConcern */
private $readConcern;
/** @var ReadPreference */
private $readPreference;
/** @var array */
private $typeMap;
/** @var WriteConcern */
private $writeConcern;
/**
* Constructs new Collection instance.
*
* This class provides methods for collection-specific operations, such as
* CRUD (i.e. create, read, update, and delete) and index management.
*
* Supported options:
*
* * readConcern (MongoDB\Driver\ReadConcern): The default read concern to
* use for collection operations. Defaults to the Manager's read concern.
*
* * readPreference (MongoDB\Driver\ReadPreference): The default read
* preference to use for collection operations. Defaults to the Manager's
* read preference.
*
* * typeMap (array): Default type map for cursors and BSON documents.
*
* * writeConcern (MongoDB\Driver\WriteConcern): The default write concern
* to use for collection operations. Defaults to the Manager's write
* concern.
*
* @param Manager $manager Manager instance from the driver
* @param string $databaseName Database name
* @param string $collectionName Collection name
* @param array $options Collection options
* @throws InvalidArgumentException for parameter/option parsing errors
*/
public function __construct(Manager $manager, $databaseName, $collectionName, array $options = [])
{
if (strlen($databaseName) < 1) {
throw new InvalidArgumentException('$databaseName is invalid: ' . $databaseName);
}
if (strlen($collectionName) < 1) {
throw new InvalidArgumentException('$collectionName is invalid: ' . $collectionName);
}
if (isset($options['readConcern']) && ! $options['readConcern'] instanceof ReadConcern) {
throw InvalidArgumentException::invalidType('"readConcern" option', $options['readConcern'], ReadConcern::class);
}
if (isset($options['readPreference']) && ! $options['readPreference'] instanceof ReadPreference) {
throw InvalidArgumentException::invalidType('"readPreference" option', $options['readPreference'], ReadPreference::class);
}
if (isset($options['typeMap']) && ! is_array($options['typeMap'])) {
throw InvalidArgumentException::invalidType('"typeMap" option', $options['typeMap'], 'array');
}
if (isset($options['writeConcern']) && ! $options['writeConcern'] instanceof WriteConcern) {
throw InvalidArgumentException::invalidType('"writeConcern" option', $options['writeConcern'], WriteConcern::class);
}
$this->manager = $manager;
$this->databaseName = (string) $databaseName;
$this->collectionName = (string) $collectionName;
$this->readConcern = $options['readConcern'] ?? $this->manager->getReadConcern();
$this->readPreference = $options['readPreference'] ?? $this->manager->getReadPreference();
$this->typeMap = $options['typeMap'] ?? self::$defaultTypeMap;
$this->writeConcern = $options['writeConcern'] ?? $this->manager->getWriteConcern();
}
/**
* Return internal properties for debugging purposes.
*
* @see http://php.net/manual/en/language.oop5.magic.php#language.oop5.magic.debuginfo
* @return array
*/
public function __debugInfo()
{
return [
'collectionName' => $this->collectionName,
'databaseName' => $this->databaseName,
'manager' => $this->manager,
'readConcern' => $this->readConcern,
'readPreference' => $this->readPreference,
'typeMap' => $this->typeMap,
'writeConcern' => $this->writeConcern,
];
}
/**
* Return the collection namespace (e.g. "db.collection").
*
* @see https://docs.mongodb.org/manual/faq/developers/#faq-dev-namespace
* @return string
*/
public function __toString()
{
return $this->databaseName . '.' . $this->collectionName;
}
/**
* Executes an aggregation framework pipeline on the collection.
*
* Note: this method's return value depends on the MongoDB server version
* and the "useCursor" option. If "useCursor" is true, a Cursor will be
* returned; otherwise, an ArrayIterator is returned, which wraps the
* "result" array from the command response document.
*
* @see Aggregate::__construct() for supported options
* @param array $pipeline List of pipeline operations
* @param array $options Command options
* @return Traversable
* @throws UnexpectedValueException if the command response was malformed
* @throws UnsupportedException if options are not supported by the selected server
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function aggregate(array $pipeline, array $options = [])
{
$hasWriteStage = is_last_pipeline_operator_write($pipeline);
if (! isset($options['readPreference']) && ! is_in_transaction($options)) {
$options['readPreference'] = $this->readPreference;
}
if ($hasWriteStage) {
$options['readPreference'] = new ReadPreference(ReadPreference::RP_PRIMARY);
}
$server = select_server($this->manager, $options);
/* MongoDB 4.2 and later supports a read concern when an $out stage is
* being used, but earlier versions do not.
*
* A read concern is also not compatible with transactions.
*/
if (! isset($options['readConcern']) &&
server_supports_feature($server, self::$wireVersionForReadConcern) &&
! is_in_transaction($options) &&
( ! $hasWriteStage || server_supports_feature($server, self::$wireVersionForReadConcernWithWriteStage))
) {
$options['readConcern'] = $this->readConcern;
}
if (! isset($options['typeMap'])) {
$options['typeMap'] = $this->typeMap;
}
if ($hasWriteStage &&
! isset($options['writeConcern']) &&
server_supports_feature($server, self::$wireVersionForWritableCommandWriteConcern) &&
! is_in_transaction($options)) {
$options['writeConcern'] = $this->writeConcern;
}
$operation = new Aggregate($this->databaseName, $this->collectionName, $pipeline, $options);
return $operation->execute($server);
}
/**
* Executes multiple write operations.
*
* @see BulkWrite::__construct() for supported options
* @param array[] $operations List of write operations
* @param array $options Command options
* @return BulkWriteResult
* @throws UnsupportedException if options are not supported by the selected server
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function bulkWrite(array $operations, array $options = [])
{
if (! isset($options['writeConcern']) && ! is_in_transaction($options)) {
$options['writeConcern'] = $this->writeConcern;
}
$operation = new BulkWrite($this->databaseName, $this->collectionName, $operations, $options);
$server = select_server($this->manager, $options);
return $operation->execute($server);
}
/**
* Gets the number of documents matching the filter.
*
* @see Count::__construct() for supported options
* @param array|object $filter Query by which to filter documents
* @param array $options Command options
* @return integer
* @throws UnexpectedValueException if the command response was malformed
* @throws UnsupportedException if options are not supported by the selected server
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*
* @deprecated 1.4
*/
public function count($filter = [], array $options = [])
{
if (! isset($options['readPreference']) && ! is_in_transaction($options)) {
$options['readPreference'] = $this->readPreference;
}
$server = select_server($this->manager, $options);
if (! isset($options['readConcern']) && server_supports_feature($server, self::$wireVersionForReadConcern) && ! is_in_transaction($options)) {
$options['readConcern'] = $this->readConcern;
}
$operation = new Count($this->databaseName, $this->collectionName, $filter, $options);
return $operation->execute($server);
}
/**
* Gets the number of documents matching the filter.
*
* @see CountDocuments::__construct() for supported options
* @param array|object $filter Query by which to filter documents
* @param array $options Command options
* @return integer
* @throws UnexpectedValueException if the command response was malformed
* @throws UnsupportedException if options are not supported by the selected server
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function countDocuments($filter = [], array $options = [])
{
if (! isset($options['readPreference']) && ! is_in_transaction($options)) {
$options['readPreference'] = $this->readPreference;
}
$server = select_server($this->manager, $options);
if (! isset($options['readConcern']) && server_supports_feature($server, self::$wireVersionForReadConcern) && ! is_in_transaction($options)) {
$options['readConcern'] = $this->readConcern;
}
$operation = new CountDocuments($this->databaseName, $this->collectionName, $filter, $options);
return $operation->execute($server);
}
/**
* Create a single index for the collection.
*
* @see Collection::createIndexes()
* @see CreateIndexes::__construct() for supported command options
* @param array|object $key Document containing fields mapped to values,
* which denote order or an index type
* @param array $options Index and command options
* @return string The name of the created index
* @throws UnsupportedException if options are not supported by the selected server
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function createIndex($key, array $options = [])
{
$commandOptionKeys = ['maxTimeMS' => 1, 'session' => 1, 'writeConcern' => 1];
$indexOptions = array_diff_key($options, $commandOptionKeys);
$commandOptions = array_intersect_key($options, $commandOptionKeys);
return current($this->createIndexes([['key' => $key] + $indexOptions], $commandOptions));
}
/**
* Create one or more indexes for the collection.
*
* Each element in the $indexes array must have a "key" document, which
* contains fields mapped to an order or type. Other options may follow.
* For example:
*
* $indexes = [
* // Create a unique index on the "username" field
* [ 'key' => [ 'username' => 1 ], 'unique' => true ],
* // Create a 2dsphere index on the "loc" field with a custom name
* [ 'key' => [ 'loc' => '2dsphere' ], 'name' => 'geo' ],
* ];
*
* If the "name" option is unspecified, a name will be generated from the
* "key" document.
*
* @see http://docs.mongodb.org/manual/reference/command/createIndexes/
* @see http://docs.mongodb.org/manual/reference/method/db.collection.createIndex/
* @see CreateIndexes::__construct() for supported command options
* @param array[] $indexes List of index specifications
* @param array $options Command options
* @return string[] The names of the created indexes
* @throws UnsupportedException if options are not supported by the selected server
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function createIndexes(array $indexes, array $options = [])
{
$server = select_server($this->manager, $options);
if (! isset($options['writeConcern']) && server_supports_feature($server, self::$wireVersionForWritableCommandWriteConcern) && ! is_in_transaction($options)) {
$options['writeConcern'] = $this->writeConcern;
}
$operation = new CreateIndexes($this->databaseName, $this->collectionName, $indexes, $options);
return $operation->execute($server);
}
/**
* Deletes all documents matching the filter.
*
* @see DeleteMany::__construct() for supported options
* @see http://docs.mongodb.org/manual/reference/command/delete/
* @param array|object $filter Query by which to delete documents
* @param array $options Command options
* @return DeleteResult
* @throws UnsupportedException if options are not supported by the selected server
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function deleteMany($filter, array $options = [])
{
if (! isset($options['writeConcern']) && ! is_in_transaction($options)) {
$options['writeConcern'] = $this->writeConcern;
}
$operation = new DeleteMany($this->databaseName, $this->collectionName, $filter, $options);
$server = select_server($this->manager, $options);
return $operation->execute($server);
}
/**
* Deletes at most one document matching the filter.
*
* @see DeleteOne::__construct() for supported options
* @see http://docs.mongodb.org/manual/reference/command/delete/
* @param array|object $filter Query by which to delete documents
* @param array $options Command options
* @return DeleteResult
* @throws UnsupportedException if options are not supported by the selected server
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function deleteOne($filter, array $options = [])
{
if (! isset($options['writeConcern']) && ! is_in_transaction($options)) {
$options['writeConcern'] = $this->writeConcern;
}
$operation = new DeleteOne($this->databaseName, $this->collectionName, $filter, $options);
$server = select_server($this->manager, $options);
return $operation->execute($server);
}
/**
* Finds the distinct values for a specified field across the collection.
*
* @see Distinct::__construct() for supported options
* @param string $fieldName Field for which to return distinct values
* @param array|object $filter Query by which to filter documents
* @param array $options Command options
* @return mixed[]
* @throws UnexpectedValueException if the command response was malformed
* @throws UnsupportedException if options are not supported by the selected server
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function distinct($fieldName, $filter = [], array $options = [])
{
if (! isset($options['readPreference']) && ! is_in_transaction($options)) {
$options['readPreference'] = $this->readPreference;
}
if (! isset($options['typeMap'])) {
$options['typeMap'] = $this->typeMap;
}
$server = select_server($this->manager, $options);
if (! isset($options['readConcern']) && server_supports_feature($server, self::$wireVersionForReadConcern) && ! is_in_transaction($options)) {
$options['readConcern'] = $this->readConcern;
}
$operation = new Distinct($this->databaseName, $this->collectionName, $fieldName, $filter, $options);
return $operation->execute($server);
}
/**
* Drop this collection.
*
* @see DropCollection::__construct() for supported options
* @param array $options Additional options
* @return array|object Command result document
* @throws UnsupportedException if options are not supported by the selected server
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function drop(array $options = [])
{
if (! isset($options['typeMap'])) {
$options['typeMap'] = $this->typeMap;
}
$server = select_server($this->manager, $options);
if (! isset($options['writeConcern']) && server_supports_feature($server, self::$wireVersionForWritableCommandWriteConcern) && ! is_in_transaction($options)) {
$options['writeConcern'] = $this->writeConcern;
}
$operation = new DropCollection($this->databaseName, $this->collectionName, $options);
return $operation->execute($server);
}
/**
* Drop a single index in the collection.
*
* @see DropIndexes::__construct() for supported options
* @param string|IndexInfo $indexName Index name or model object
* @param array $options Additional options
* @return array|object Command result document
* @throws UnsupportedException if options are not supported by the selected server
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function dropIndex($indexName, array $options = [])
{
$indexName = (string) $indexName;
if ($indexName === '*') {
throw new InvalidArgumentException('dropIndexes() must be used to drop multiple indexes');
}
if (! isset($options['typeMap'])) {
$options['typeMap'] = $this->typeMap;
}
$server = select_server($this->manager, $options);
if (! isset($options['writeConcern']) && server_supports_feature($server, self::$wireVersionForWritableCommandWriteConcern) && ! is_in_transaction($options)) {
$options['writeConcern'] = $this->writeConcern;
}
$operation = new DropIndexes($this->databaseName, $this->collectionName, $indexName, $options);
return $operation->execute($server);
}
/**
* Drop all indexes in the collection.
*
* @see DropIndexes::__construct() for supported options
* @param array $options Additional options
* @return array|object Command result document
* @throws UnsupportedException if options are not supported by the selected server
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function dropIndexes(array $options = [])
{
if (! isset($options['typeMap'])) {
$options['typeMap'] = $this->typeMap;
}
$server = select_server($this->manager, $options);
if (! isset($options['writeConcern']) && server_supports_feature($server, self::$wireVersionForWritableCommandWriteConcern) && ! is_in_transaction($options)) {
$options['writeConcern'] = $this->writeConcern;
}
$operation = new DropIndexes($this->databaseName, $this->collectionName, '*', $options);
return $operation->execute($server);
}
/**
* Gets an estimated number of documents in the collection using the collection metadata.
*
* @see EstimatedDocumentCount::__construct() for supported options
* @param array $options Command options
* @return integer
* @throws UnexpectedValueException if the command response was malformed
* @throws UnsupportedException if options are not supported by the selected server
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function estimatedDocumentCount(array $options = [])
{
if (! isset($options['readPreference']) && ! is_in_transaction($options)) {
$options['readPreference'] = $this->readPreference;
}
$server = select_server($this->manager, $options);
if (! isset($options['readConcern']) && server_supports_feature($server, self::$wireVersionForReadConcern) && ! is_in_transaction($options)) {
$options['readConcern'] = $this->readConcern;
}
$operation = new EstimatedDocumentCount($this->databaseName, $this->collectionName, $options);
return $operation->execute($server);
}
/**
* Explains explainable commands.
*
* @see Explain::__construct() for supported options
* @see http://docs.mongodb.org/manual/reference/command/explain/
* @param Explainable $explainable Command on which to run explain
* @param array $options Additional options
* @return array|object
* @throws UnsupportedException if explainable or options are not supported by the selected server
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function explain(Explainable $explainable, array $options = [])
{
if (! isset($options['readPreference']) && ! is_in_transaction($options)) {
$options['readPreference'] = $this->readPreference;
}
if (! isset($options['typeMap'])) {
$options['typeMap'] = $this->typeMap;
}
$server = select_server($this->manager, $options);
$operation = new Explain($this->databaseName, $explainable, $options);
return $operation->execute($server);
}
/**
* Finds documents matching the query.
*
* @see Find::__construct() for supported options
* @see http://docs.mongodb.org/manual/core/read-operations-introduction/
* @param array|object $filter Query by which to filter documents
* @param array $options Additional options
* @return Cursor
* @throws UnsupportedException if options are not supported by the selected server
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function find($filter = [], array $options = [])
{
if (! isset($options['readPreference']) && ! is_in_transaction($options)) {
$options['readPreference'] = $this->readPreference;
}
$server = select_server($this->manager, $options);
if (! isset($options['readConcern']) && server_supports_feature($server, self::$wireVersionForReadConcern) && ! is_in_transaction($options)) {
$options['readConcern'] = $this->readConcern;
}
if (! isset($options['typeMap'])) {
$options['typeMap'] = $this->typeMap;
}
$operation = new Find($this->databaseName, $this->collectionName, $filter, $options);
return $operation->execute($server);
}
/**
* Finds a single document matching the query.
*
* @see FindOne::__construct() for supported options
* @see http://docs.mongodb.org/manual/core/read-operations-introduction/
* @param array|object $filter Query by which to filter documents
* @param array $options Additional options
* @return array|object|null
* @throws UnsupportedException if options are not supported by the selected server
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function findOne($filter = [], array $options = [])
{
if (! isset($options['readPreference']) && ! is_in_transaction($options)) {
$options['readPreference'] = $this->readPreference;
}
$server = select_server($this->manager, $options);
if (! isset($options['readConcern']) && server_supports_feature($server, self::$wireVersionForReadConcern) && ! is_in_transaction($options)) {
$options['readConcern'] = $this->readConcern;
}
if (! isset($options['typeMap'])) {
$options['typeMap'] = $this->typeMap;
}
$operation = new FindOne($this->databaseName, $this->collectionName, $filter, $options);
return $operation->execute($server);
}
/**
* Finds a single document and deletes it, returning the original.
*
* The document to return may be null if no document matched the filter.
*
* @see FindOneAndDelete::__construct() for supported options
* @see http://docs.mongodb.org/manual/reference/command/findAndModify/
* @param array|object $filter Query by which to filter documents
* @param array $options Command options
* @return array|object|null
* @throws UnexpectedValueException if the command response was malformed
* @throws UnsupportedException if options are not supported by the selected server
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function findOneAndDelete($filter, array $options = [])
{
$server = select_server($this->manager, $options);
if (! isset($options['writeConcern']) && server_supports_feature($server, self::$wireVersionForFindAndModifyWriteConcern) && ! is_in_transaction($options)) {
$options['writeConcern'] = $this->writeConcern;
}
if (! isset($options['typeMap'])) {
$options['typeMap'] = $this->typeMap;
}
$operation = new FindOneAndDelete($this->databaseName, $this->collectionName, $filter, $options);
return $operation->execute($server);
}
/**
* Finds a single document and replaces it, returning either the original or
* the replaced document.
*
* The document to return may be null if no document matched the filter. By
* default, the original document is returned. Specify
* FindOneAndReplace::RETURN_DOCUMENT_AFTER for the "returnDocument" option
* to return the updated document.
*
* @see FindOneAndReplace::__construct() for supported options
* @see http://docs.mongodb.org/manual/reference/command/findAndModify/
* @param array|object $filter Query by which to filter documents
* @param array|object $replacement Replacement document
* @param array $options Command options
* @return array|object|null
* @throws UnexpectedValueException if the command response was malformed
* @throws UnsupportedException if options are not supported by the selected server
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function findOneAndReplace($filter, $replacement, array $options = [])
{
$server = select_server($this->manager, $options);
if (! isset($options['writeConcern']) && server_supports_feature($server, self::$wireVersionForFindAndModifyWriteConcern) && ! is_in_transaction($options)) {
$options['writeConcern'] = $this->writeConcern;
}
if (! isset($options['typeMap'])) {
$options['typeMap'] = $this->typeMap;
}
$operation = new FindOneAndReplace($this->databaseName, $this->collectionName, $filter, $replacement, $options);
return $operation->execute($server);
}
/**
* Finds a single document and updates it, returning either the original or
* the updated document.
*
* The document to return may be null if no document matched the filter. By
* default, the original document is returned. Specify
* FindOneAndUpdate::RETURN_DOCUMENT_AFTER for the "returnDocument" option
* to return the updated document.
*
* @see FindOneAndReplace::__construct() for supported options
* @see http://docs.mongodb.org/manual/reference/command/findAndModify/
* @param array|object $filter Query by which to filter documents
* @param array|object $update Update to apply to the matched document
* @param array $options Command options
* @return array|object|null
* @throws UnexpectedValueException if the command response was malformed
* @throws UnsupportedException if options are not supported by the selected server
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function findOneAndUpdate($filter, $update, array $options = [])
{
$server = select_server($this->manager, $options);
if (! isset($options['writeConcern']) && server_supports_feature($server, self::$wireVersionForFindAndModifyWriteConcern) && ! is_in_transaction($options)) {
$options['writeConcern'] = $this->writeConcern;
}
if (! isset($options['typeMap'])) {
$options['typeMap'] = $this->typeMap;
}
$operation = new FindOneAndUpdate($this->databaseName, $this->collectionName, $filter, $update, $options);
return $operation->execute($server);
}
/**
* Return the collection name.
*
* @return string
*/
public function getCollectionName()
{
return $this->collectionName;
}
/**
* Return the database name.
*
* @return string
*/
public function getDatabaseName()
{
return $this->databaseName;
}
/**
* Return the Manager.
*
* @return Manager
*/
public function getManager()
{
return $this->manager;
}
/**
* Return the collection namespace.
*
* @see https://docs.mongodb.org/manual/reference/glossary/#term-namespace
* @return string
*/
public function getNamespace()
{
return $this->databaseName . '.' . $this->collectionName;
}
/**
* Return the read concern for this collection.
*
* @see http://php.net/manual/en/mongodb-driver-readconcern.isdefault.php
* @return ReadConcern
*/
public function getReadConcern()
{
return $this->readConcern;
}
/**
* Return the read preference for this collection.
*
* @return ReadPreference
*/
public function getReadPreference()
{
return $this->readPreference;
}
/**
* Return the type map for this collection.
*
* @return array
*/
public function getTypeMap()
{
return $this->typeMap;
}
/**
* Return the write concern for this collection.
*
* @see http://php.net/manual/en/mongodb-driver-writeconcern.isdefault.php
* @return WriteConcern
*/
public function getWriteConcern()
{
return $this->writeConcern;
}
/**
* Inserts multiple documents.
*
* @see InsertMany::__construct() for supported options
* @see http://docs.mongodb.org/manual/reference/command/insert/
* @param array[]|object[] $documents The documents to insert
* @param array $options Command options
* @return InsertManyResult
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function insertMany(array $documents, array $options = [])
{
if (! isset($options['writeConcern']) && ! is_in_transaction($options)) {
$options['writeConcern'] = $this->writeConcern;
}
$operation = new InsertMany($this->databaseName, $this->collectionName, $documents, $options);
$server = select_server($this->manager, $options);
return $operation->execute($server);
}
/**
* Inserts one document.
*
* @see InsertOne::__construct() for supported options
* @see http://docs.mongodb.org/manual/reference/command/insert/
* @param array|object $document The document to insert
* @param array $options Command options
* @return InsertOneResult
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function insertOne($document, array $options = [])
{
if (! isset($options['writeConcern']) && ! is_in_transaction($options)) {
$options['writeConcern'] = $this->writeConcern;
}
$operation = new InsertOne($this->databaseName, $this->collectionName, $document, $options);
$server = select_server($this->manager, $options);
return $operation->execute($server);
}
/**
* Returns information for all indexes for the collection.
*
* @see ListIndexes::__construct() for supported options
* @param array $options
* @return IndexInfoIterator
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function listIndexes(array $options = [])
{
$operation = new ListIndexes($this->databaseName, $this->collectionName, $options);
$server = select_server($this->manager, $options);
return $operation->execute($server);
}
/**
* Executes a map-reduce aggregation on the collection.
*
* @see MapReduce::__construct() for supported options
* @see http://docs.mongodb.org/manual/reference/command/mapReduce/
* @param JavascriptInterface $map Map function
* @param JavascriptInterface $reduce Reduce function
* @param string|array|object $out Output specification
* @param array $options Command options
* @return MapReduceResult
* @throws UnsupportedException if options are not supported by the selected server
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
* @throws UnexpectedValueException if the command response was malformed
*/
public function mapReduce(JavascriptInterface $map, JavascriptInterface $reduce, $out, array $options = [])
{
$hasOutputCollection = ! is_mapreduce_output_inline($out);
if (! isset($options['readPreference']) && ! is_in_transaction($options)) {
$options['readPreference'] = $this->readPreference;
}
// Check if the out option is inline because we will want to coerce a primary read preference if not
if ($hasOutputCollection) {
$options['readPreference'] = new ReadPreference(ReadPreference::RP_PRIMARY);
}
$server = select_server($this->manager, $options);
/* A "majority" read concern is not compatible with inline output, so
* avoid providing the Collection's read concern if it would conflict.
*
* A read concern is also not compatible with transactions.
*/
if (! isset($options['readConcern']) && ! ($hasOutputCollection && $this->readConcern->getLevel() === ReadConcern::MAJORITY) && server_supports_feature($server, self::$wireVersionForReadConcern) && ! is_in_transaction($options)) {
$options['readConcern'] = $this->readConcern;
}
if (! isset($options['typeMap'])) {
$options['typeMap'] = $this->typeMap;
}
if (! isset($options['writeConcern']) && server_supports_feature($server, self::$wireVersionForWritableCommandWriteConcern) && ! is_in_transaction($options)) {
$options['writeConcern'] = $this->writeConcern;
}
$operation = new MapReduce($this->databaseName, $this->collectionName, $map, $reduce, $out, $options);
return $operation->execute($server);
}
/**
* Replaces at most one document matching the filter.
*
* @see ReplaceOne::__construct() for supported options
* @see http://docs.mongodb.org/manual/reference/command/update/
* @param array|object $filter Query by which to filter documents
* @param array|object $replacement Replacement document
* @param array $options Command options
* @return UpdateResult
* @throws UnsupportedException if options are not supported by the selected server
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function replaceOne($filter, $replacement, array $options = [])
{
if (! isset($options['writeConcern']) && ! is_in_transaction($options)) {
$options['writeConcern'] = $this->writeConcern;
}
$operation = new ReplaceOne($this->databaseName, $this->collectionName, $filter, $replacement, $options);
$server = select_server($this->manager, $options);
return $operation->execute($server);
}
/**
* Updates all documents matching the filter.
*
* @see UpdateMany::__construct() for supported options
* @see http://docs.mongodb.org/manual/reference/command/update/
* @param array|object $filter Query by which to filter documents
* @param array|object $update Update to apply to the matched documents
* @param array $options Command options
* @return UpdateResult
* @throws UnsupportedException if options are not supported by the selected server
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function updateMany($filter, $update, array $options = [])
{
if (! isset($options['writeConcern']) && ! is_in_transaction($options)) {
$options['writeConcern'] = $this->writeConcern;
}
$operation = new UpdateMany($this->databaseName, $this->collectionName, $filter, $update, $options);
$server = select_server($this->manager, $options);
return $operation->execute($server);
}
/**
* Updates at most one document matching the filter.
*
* @see UpdateOne::__construct() for supported options
* @see http://docs.mongodb.org/manual/reference/command/update/
* @param array|object $filter Query by which to filter documents
* @param array|object $update Update to apply to the matched document
* @param array $options Command options
* @return UpdateResult
* @throws UnsupportedException if options are not supported by the selected server
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function updateOne($filter, $update, array $options = [])
{
if (! isset($options['writeConcern']) && ! is_in_transaction($options)) {
$options['writeConcern'] = $this->writeConcern;
}
$operation = new UpdateOne($this->databaseName, $this->collectionName, $filter, $update, $options);
$server = select_server($this->manager, $options);
return $operation->execute($server);
}
/**
* Create a change stream for watching changes to the collection.
*
* @see Watch::__construct() for supported options
* @param array $pipeline List of pipeline operations
* @param array $options Command options
* @return ChangeStream
* @throws InvalidArgumentException for parameter/option parsing errors
*/
public function watch(array $pipeline = [], array $options = [])
{
if (! isset($options['readPreference']) && ! is_in_transaction($options)) {
$options['readPreference'] = $this->readPreference;
}
$server = select_server($this->manager, $options);
/* Although change streams require a newer version of the server than
* read concerns, perform the usual wire version check before inheriting
* the collection's read concern. In the event that the server is too
* old, this makes it more likely that users will encounter an error
* related to change streams being unsupported instead of an
* UnsupportedException regarding use of the "readConcern" option from
* the Aggregate operation class. */
if (! isset($options['readConcern']) && server_supports_feature($server, self::$wireVersionForReadConcern) && ! is_in_transaction($options)) {
$options['readConcern'] = $this->readConcern;
}
if (! isset($options['typeMap'])) {
$options['typeMap'] = $this->typeMap;
}
$operation = new Watch($this->manager, $this->databaseName, $this->collectionName, $pipeline, $options);
return $operation->execute($server);
}
/**
* Get a clone of this collection with different options.
*
* @see Collection::__construct() for supported options
* @param array $options Collection constructor options
* @return Collection
* @throws InvalidArgumentException for parameter/option parsing errors
*/
public function withOptions(array $options = [])
{
$options += [
'readConcern' => $this->readConcern,
'readPreference' => $this->readPreference,
'typeMap' => $this->typeMap,
'writeConcern' => $this->writeConcern,
];
return new Collection($this->manager, $this->databaseName, $this->collectionName, $options);
}
}
src/functions.php 0000666 00000027431 13645314021 0010066 0 ustar 00 bsonSerialize();
}
if (is_object($document)) {
$document = get_object_vars($document);
}
if (! is_array($document)) {
throw InvalidArgumentException::invalidType('$document', $document, 'array or object');
}
$name = '';
foreach ($document as $field => $type) {
$name .= ($name != '' ? '_' : '') . $field . '_' . $type;
}
return $name;
}
/**
* Return whether the first key in the document starts with a "$" character.
*
* This is used for differentiating update and replacement documents.
*
* @internal
* @param array|object $document Update or replacement document
* @return boolean
* @throws InvalidArgumentException
*/
function is_first_key_operator($document)
{
if ($document instanceof Serializable) {
$document = $document->bsonSerialize();
}
if (is_object($document)) {
$document = get_object_vars($document);
}
if (! is_array($document)) {
throw InvalidArgumentException::invalidType('$document', $document, 'array or object');
}
reset($document);
$firstKey = (string) key($document);
return isset($firstKey[0]) && $firstKey[0] === '$';
}
/**
* Returns whether an update specification is a valid aggregation pipeline.
*
* @internal
* @param mixed $pipeline
* @return boolean
*/
function is_pipeline($pipeline)
{
if (! is_array($pipeline)) {
return false;
}
if ($pipeline === []) {
return false;
}
$expectedKey = 0;
foreach ($pipeline as $key => $stage) {
if (! is_array($stage) && ! is_object($stage)) {
return false;
}
if ($expectedKey !== $key) {
return false;
}
$expectedKey++;
$stage = (array) $stage;
reset($stage);
$key = key($stage);
if (! isset($key[0]) || $key[0] !== '$') {
return false;
}
}
return true;
}
/**
* Returns whether we are currently in a transaction.
*
* @internal
* @param array $options Command options
* @return boolean
*/
function is_in_transaction(array $options)
{
if (isset($options['session']) && $options['session'] instanceof Session && $options['session']->isInTransaction()) {
return true;
}
return false;
}
/**
* Return whether the aggregation pipeline ends with an $out or $merge operator.
*
* This is used for determining whether the aggregation pipeline must be
* executed against a primary server.
*
* @internal
* @param array $pipeline List of pipeline operations
* @return boolean
*/
function is_last_pipeline_operator_write(array $pipeline)
{
$lastOp = end($pipeline);
if ($lastOp === false) {
return false;
}
$lastOp = (array) $lastOp;
return in_array(key($lastOp), ['$out', '$merge'], true);
}
/**
* Return whether the "out" option for a mapReduce operation is "inline".
*
* This is used to determine if a mapReduce command requires a primary.
*
* @internal
* @see https://docs.mongodb.com/manual/reference/command/mapReduce/#output-inline
* @param string|array|object $out Output specification
* @return boolean
* @throws InvalidArgumentException
*/
function is_mapreduce_output_inline($out)
{
if (! is_array($out) && ! is_object($out)) {
return false;
}
if ($out instanceof Serializable) {
$out = $out->bsonSerialize();
}
if (is_object($out)) {
$out = get_object_vars($out);
}
if (! is_array($out)) {
throw InvalidArgumentException::invalidType('$out', $out, 'array or object');
}
reset($out);
return key($out) === 'inline';
}
/**
* Return whether the server supports a particular feature.
*
* @internal
* @param Server $server Server to check
* @param integer $feature Feature constant (i.e. wire protocol version)
* @return boolean
*/
function server_supports_feature(Server $server, $feature)
{
$info = $server->getInfo();
$maxWireVersion = isset($info['maxWireVersion']) ? (integer) $info['maxWireVersion'] : 0;
$minWireVersion = isset($info['minWireVersion']) ? (integer) $info['minWireVersion'] : 0;
return $minWireVersion <= $feature && $maxWireVersion >= $feature;
}
function is_string_array($input)
{
if (! is_array($input)) {
return false;
}
foreach ($input as $item) {
if (! is_string($item)) {
return false;
}
}
return true;
}
/**
* Performs a deep copy of a value.
*
* This function will clone objects and recursively copy values within arrays.
*
* @internal
* @see https://bugs.php.net/bug.php?id=49664
* @param mixed $element Value to be copied
* @return mixed
* @throws ReflectionException
*/
function recursive_copy($element)
{
if (is_array($element)) {
foreach ($element as $key => $value) {
$element[$key] = recursive_copy($value);
}
return $element;
}
if (! is_object($element)) {
return $element;
}
if (! (new ReflectionClass($element))->isCloneable()) {
return $element;
}
return clone $element;
}
/**
* Creates a type map to apply to a field type
*
* This is used in the Aggregate, Distinct, and FindAndModify operations to
* apply the root-level type map to the document that will be returned. It also
* replaces the root type with object for consistency within these operations
*
* An existing type map for the given field path will not be overwritten
*
* @internal
* @param array $typeMap The existing typeMap
* @param string $fieldPath The field path to apply the root type to
* @return array
*/
function create_field_path_type_map(array $typeMap, $fieldPath)
{
// If some field paths already exist, we prefix them with the field path we are assuming as the new root
if (isset($typeMap['fieldPaths']) && is_array($typeMap['fieldPaths'])) {
$fieldPaths = $typeMap['fieldPaths'];
$typeMap['fieldPaths'] = [];
foreach ($fieldPaths as $existingFieldPath => $type) {
$typeMap['fieldPaths'][$fieldPath . '.' . $existingFieldPath] = $type;
}
}
// If a root typemap was set, apply this to the field object
if (isset($typeMap['root'])) {
$typeMap['fieldPaths'][$fieldPath] = $typeMap['root'];
}
/* Special case if we want to convert an array, in which case we need to
* ensure that the field containing the array is exposed as an array,
* instead of the type given in the type map's array key. */
if (substr($fieldPath, -2, 2) === '.$') {
$typeMap['fieldPaths'][substr($fieldPath, 0, -2)] = 'array';
}
$typeMap['root'] = 'object';
return $typeMap;
}
/**
* Execute a callback within a transaction in the given session
*
* This helper takes care of retrying the commit operation or the entire
* transaction if an error occurs.
*
* If the commit fails because of an UnknownTransactionCommitResult error, the
* commit is retried without re-invoking the callback.
* If the commit fails because of a TransientTransactionError, the entire
* transaction will be retried. In this case, the callback will be invoked
* again. It is important that the logic inside the callback is idempotent.
*
* In case of failures, the commit or transaction are retried until 120 seconds
* from the initial call have elapsed. After that, no retries will happen and
* the helper will throw the last exception received from the driver.
*
* @see Client::startSession
* @see Session::startTransaction for supported transaction options
*
* @param Session $session A session object as retrieved by Client::startSession
* @param callable $callback A callback that will be invoked within the transaction
* @param array $transactionOptions Additional options that are passed to Session::startTransaction
* @return void
* @throws RuntimeException for driver errors while committing the transaction
* @throws Exception for any other errors, including those thrown in the callback
*/
function with_transaction(Session $session, callable $callback, array $transactionOptions = [])
{
$operation = new WithTransaction($callback, $transactionOptions);
$operation->execute($session);
}
/**
* Returns the session option if it is set and valid.
*
* @internal
* @param array $options
* @return Session|null
*/
function extract_session_from_options(array $options)
{
if (! isset($options['session']) || ! $options['session'] instanceof Session) {
return null;
}
return $options['session'];
}
/**
* Returns the readPreference option if it is set and valid.
*
* @internal
* @param array $options
* @return ReadPreference|null
*/
function extract_read_preference_from_options(array $options)
{
if (! isset($options['readPreference']) || ! $options['readPreference'] instanceof ReadPreference) {
return null;
}
return $options['readPreference'];
}
/**
* Performs server selection, respecting the readPreference and session options
* (if given)
*
* @internal
* @return Server
*/
function select_server(Manager $manager, array $options)
{
$session = extract_session_from_options($options);
if ($session instanceof Session && $session->getServer() !== null) {
return $session->getServer();
}
$readPreference = extract_read_preference_from_options($options);
if (! $readPreference instanceof ReadPreference) {
// TODO: PHPLIB-476: Read transaction read preference once PHPC-1439 is implemented
$readPreference = new ReadPreference(ReadPreference::RP_PRIMARY);
}
return $manager->selectServer($readPreference);
}
src/MapReduceResult.php 0000666 00000005565 13645314021 0011126 0 ustar 00 getIterator = $getIterator;
$this->executionTimeMS = isset($result->timeMillis) ? (integer) $result->timeMillis : 0;
$this->counts = isset($result->counts) ? (array) $result->counts : [];
$this->timing = isset($result->timing) ? (array) $result->timing : [];
}
/**
* Returns various count statistics from the mapReduce command.
*
* @return array
*/
public function getCounts()
{
return $this->counts;
}
/**
* Return the command execution time in milliseconds.
*
* @return integer
*/
public function getExecutionTimeMS()
{
return (integer) $this->executionTimeMS;
}
/**
* Return the mapReduce results as a Traversable.
*
* @see http://php.net/iteratoraggregate.getiterator
* @return Traversable
*/
public function getIterator()
{
return call_user_func($this->getIterator);
}
/**
* Returns various timing statistics from the mapReduce command.
*
* Note: timing statistics are only available if the mapReduce command's
* "verbose" option was true; otherwise, an empty array will be returned.
*
* @return array
*/
public function getTiming()
{
return $this->timing;
}
}
src/Exception/Exception.php 0000666 00000001351 13645314021 0011743 0 ustar 00 writeResult = $writeResult;
$this->isAcknowledged = $writeResult->isAcknowledged();
}
/**
* Return the number of documents that were deleted.
*
* This method should only be called if the write was acknowledged.
*
* @see DeleteResult::isAcknowledged()
* @return integer
* @throws BadMethodCallException is the write result is unacknowledged
*/
public function getDeletedCount()
{
if ($this->isAcknowledged) {
return $this->writeResult->getDeletedCount();
}
throw BadMethodCallException::unacknowledgedWriteResultAccess(__METHOD__);
}
/**
* Return whether this delete was acknowledged by the server.
*
* If the delete was not acknowledged, other fields from the WriteResult
* (e.g. deletedCount) will be undefined.
*
* @return boolean
*/
public function isAcknowledged()
{
return $this->isAcknowledged;
}
}
docs/reference/bson.txt 0000666 00000020057 13645314021 0011143 0 ustar 00 ====
BSON
====
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Overview
--------
MongoDB stores data records as BSON documents. BSON is a binary representation
of :term:`JSON` documents, though it contains more data types than JSON. For the
BSON spec, see `bsonspec.org `_.
By default, the |php-library| returns BSON documents as
:phpclass:`MongoDB\\Model\\BSONDocument` objects and BSON arrays as
:phpclass:`MongoDB\\Model\\BSONArray` objects, respectively.
BSON Classes
------------
.. phpclass:: MongoDB\\Model\\BSONArray
This class extends PHP's :php:`ArrayObject ` class. It also
implements PHP's :php:`JsonSerializable ` interface and the
driver's :php:`MongoDB\\BSON\\Serializable ` and
:php:`MongoDB\\BSON\\Unserializable `
interfaces.
By default, the library will deserialize BSON arrays as instances of this
class. During BSON and JSON serialization, instances of this class will
serialize as an array type (:php:`array_values() ` is used
internally to numerically reindex the array).
.. phpclass:: MongoDB\\Model\\BSONDocument
This class extends PHP's :php:`ArrayObject ` class. It also
implements PHP's :php:`JsonSerializable ` interface and the
driver's :php:`MongoDB\\BSON\\Serializable ` and
:php:`MongoDB\\BSON\\Unserializable `
interfaces.
By default, the library will deserialize BSON documents as instances of this
class. During BSON and JSON serialization, instances of this class will
serialize as a document type (:php:`object casting
` is used internally).
.. _php-type-map:
Type Maps
---------
Most methods that read data from MongoDB support a ``typeMap`` option, which
allows control over how BSON is converted to PHP. Additionally,
the :phpclass:`MongoDB\\Client`, :phpclass:`MongoDB\\Database`, and
:phpclass:`MongoDB\\Collection` classes accept a ``typeMap`` option, which can
be used to specify a default type map to apply to any supporting methods and
selected classes (e.g. :phpmethod:`MongoDB\\Client::selectDatabase()`).
The :phpclass:`MongoDB\\Client`, :phpclass:`MongoDB\\Database`, and
:phpclass:`MongoDB\\Collection` classes use the following type map by
default:
.. code-block:: php
[
'array' => 'MongoDB\Model\BSONArray',
'document' => 'MongoDB\Model\BSONDocument',
'root' => 'MongoDB\Model\BSONDocument',
]
The type map above will convert BSON documents and arrays to
:phpclass:`MongoDB\\Model\\BSONDocument` and
:phpclass:`MongoDB\\Model\\BSONArray` objects, respectively. The ``root`` and
``document`` keys are used to distinguish the top-level BSON document from
embedded documents, respectively.
A type map may specify any class that implements
:php:`MongoDB\\BSON\\Unserializable ` as well as
``"array"``, ``"stdClass``", and ``"object"`` (``"stdClass``" and ``"object"``
are aliases of one another).
.. seealso:: :php:`Deserialization from BSON ` in the PHP manual
``Persistable`` Classes
-----------------------
The driver's :php:`persistence specification ` outlines how
classes implementing its :php:`MongoDB\\BSON\\Persistable
` interface are serialized to and deserialized from
BSON. The :php:`Persistable ` interface is analogous
to PHP's :php:`Serializable interface `.
The driver automatically handles serialization and deserialization for classes
implementing the :php:`Persistable ` interface without
requiring the use of the ``typeMap`` option. This is done by encoding the name
of the PHP class in a special property within the BSON document.
.. note::
When deserializing a PHP variable from BSON, the encoded class name of a
:php:`Persistable ` object will override any class
specified in the type map, but it will not override ``"array"`` and
``"stdClass"`` or ``"object"``. This is discussed in the
:php:`persistence specification ` but it bears
repeating.
Consider the following class definition:
.. code-block:: php
id = new MongoDB\BSON\ObjectId;
$this->name = (string) $name;
$this->createdAt = new MongoDB\BSON\UTCDateTime;
}
function bsonSerialize()
{
return [
'_id' => $this->id,
'name' => $this->name,
'createdAt' => $this->createdAt,
];
}
function bsonUnserialize(array $data)
{
$this->id = $data['_id'];
$this->name = $data['name'];
$this->createdAt = $data['createdAt'];
}
}
The following example constructs a ``Person`` object, inserts it into the
database, and reads it back as an object of the same type:
.. code-block:: php
test->persons;
$result = $collection->insertOne(new Person('Bob'));
$person = $collection->findOne(['_id' => $result->getInsertedId()]);
var_dump($person);
The output would then resemble:
.. code-block:: none
object(Person)#18 (3) {
["id":"Person":private]=>
object(MongoDB\BSON\ObjectId)#15 (1) {
["oid"]=>
string(24) "56fad2c36118fd2e9820cfc1"
}
["name":"Person":private]=>
string(3) "Bob"
["createdAt":"Person":private]=>
object(MongoDB\BSON\UTCDateTime)#17 (1) {
["milliseconds"]=>
int(1459278531218)
}
}
The same document in the MongoDB shell might display as:
.. code-block:: js
{
"_id" : ObjectId("56fad2c36118fd2e9820cfc1"),
"__pclass" : BinData(128,"UGVyc29u"),
"name" : "Bob",
"createdAt" : ISODate("2016-03-29T19:08:51.218Z")
}
.. note::
:php:`MongoDB\\BSON\\Persistable ` may only be used
for root and embedded BSON documents. It may not be used for BSON arrays.
Emulating the Legacy Driver
---------------------------
The legacy :php:`mongo extension ` returned both BSON documents and
arrays as PHP arrays. While PHP arrays are convenient to work with, this
behavior was problematic:
- Different BSON types could deserialize to the same PHP value (e.g.
``{"0": "foo"}`` and ``["foo"]``), which made it impossible to infer the
original BSON type.
- Numerically-indexed PHP arrays would be serialized as BSON documents if there
was a gap in their key sequence. Such gaps were easily caused by unsetting a
key to remove an element and forgetting to numerically reindex the array.
The |php-library|'s :phpclass:`BSONDocument ` and
:phpclass:`BSONArray ` classes address these concerns
by preserving the BSON type information during serialization and
deserialization; however, some users may still prefer the legacy behavior. If
desired, you can use the ``typeMap`` option to have the library return
everything as a PHP array:
.. code-block:: php
[
'array' => 'array',
'document' => 'array',
'root' => 'array',
],
]
);
$document = $client->test->zips->findOne(['_id' => '94301']);
var_dump($document);
The above example would output something similar to:
.. code-block:: php
array(5) {
["_id"]=>
string(5) "94301"
["city"]=>
string(9) "PALO ALTO"
["loc"]=>
array(2) {
[0]=>
float(-122.149685)
[1]=>
float(37.444324)
}
["pop"]=>
int(15965)
["state"]=>
string(2) "CA"
}
docs/reference/exception-classes.txt 0000666 00000011510 13645314021 0013625 0 ustar 00 =================
Exception Classes
=================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
MongoDB\\Exception\\BadMethodCallException
------------------------------------------
.. phpclass:: MongoDB\\Exception\\BadMethodCallException
This exception is thrown when an unsupported method is invoked on an object.
For example, using an unacknowledged write concern with
:phpmethod:`MongoDB\\Collection::insertMany()` will return a
:phpclass:`MongoDB\\InsertManyResult` object. It is a logical error to call
:phpmethod:`MongoDB\\InsertManyResult::getInsertedCount()`, since the number
of inserted documents can only be determined from the response of an
acknowledged write operation.
This class extends PHP's :php:`BadMethodCallException
` class and implements the library's
:phpclass:`Exception ` interface.
----
MongoDB\\Exception\\InvalidArgumentException
--------------------------------------------
.. phpclass:: MongoDB\\Exception\\InvalidArgumentException
Thrown for errors related to the parsing of parameters or options within the
library.
This class extends the driver's :php:`InvalidArgumentException
` class and implements the
library's :phpclass:`Exception ` interface.
----
MongoDB\\Exception\\UnexpectedValueException
--------------------------------------------
.. phpclass:: MongoDB\\Exception\\UnexpectedValueException
This exception is thrown when a command response from the server is
malformed or not what the library expected. This exception means that an
assertion in some operation, which abstracts a database command, has failed.
It may indicate a corrupted BSON response or bug in the server, driver, or
library.
This class extends the driver's :php:`UnexpectedValueException
` class and implements the
library's :phpclass:`Exception ` interface.
----
MongoDB\\Exception\\UnsupportedException
----------------------------------------
.. phpclass:: MongoDB\\Exception\\UnsupportedException
This exception is thrown if an option is used and not supported by the
selected server. It is used sparingly in cases where silently ignoring the
unsupported option might otherwise lead to unexpected behavior.
For example, the ``collation`` option for
:phpmethod:`MongoDB\\Collection::deleteOne()` is only supported by
MongoDB 3.4+. Since collation determines how a document is matched, silently
ignoring the option for an older server version could result in an
unintended document being deleted.
This class extends the library's :phpclass:`RuntimeException
` class.
.. note::
Unlike :phpclass:`InvalidArgumentException
`, which may be thrown when
an operation's parameters and options are parsed during construction, the
selected server is not known until an operation is executed.
----
MongoDB\\GridFS\\Exception\\CorruptFileException
------------------------------------------------
.. phpclass:: MongoDB\\GridFS\\Exception\\CorruptFileException
This exception is thrown if a GridFS file's metadata or chunk documents
contain unexpected or invalid data.
When selecting a GridFS file, this may be thrown if a metadata field has an
incorrect type or its value is out of range (e.g. negative ``length``). When
reading a GridFS file, this may be thrown if a chunk's index is out of
sequence or its binary data's length out of range.
This class extends the library's :phpclass:`RuntimeException
` class.
----
MongoDB\\GridFS\\Exception\\FileNotFoundException
-------------------------------------------------
.. phpclass:: MongoDB\\GridFS\\Exception\\FileNotFoundException
This exception is thrown if no GridFS file was found for the selection
criteria (e.g. ``id``, ``filename``).
This class extends the library's :phpclass:`RuntimeException
` class.
----
MongoDB\\Exception\\Exception
-----------------------------
.. phpclass:: MongoDB\\Exception\\Exception
This interface extends the driver's :php:`Exception
` interface and is implemented by all
exception classes within the library.
----
MongoDB\\Exception\\RuntimeException
------------------------------------
.. phpclass:: MongoDB\\Exception\\RuntimeException
This class extends the driver's :php:`RuntimeException
` class, which in turn extends
PHP's :php:`RuntimeException ` class.
docs/reference/functions.txt 0000666 00000000337 13645314021 0012211 0 ustar 00 =========
Functions
=========
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
.. toctree::
:titlesonly:
/reference/function/with_transaction
docs/reference/class/MongoDBCollection.txt 0000666 00000010145 13645314021 0014605 0 ustar 00 =========================
MongoDB\\Collection Class
=========================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpclass:: MongoDB\\Collection
Provides methods for common operations on collections and documents,
including CRUD operations and index management.
You can construct collections directly using the driver's
:php:`MongoDB\\Driver\\Manager ` class or
select a collection from the library's :phpclass:`MongoDB\\Client` or
:phpclass:`MongoDB\\Database` classes. A collection may also be cloned from
an existing :phpclass:`MongoDB\\Collection` object via the
:phpmethod:`withOptions() ` method.
:phpclass:`MongoDB\\Collection` supports the :php:`readConcern
`, :php:`readPreference
`, :php:`typeMap
`,
and :php:`writeConcern ` options. If you omit an
option, the collection inherits the value from the :php:`Manager
` constructor argument or the :phpclass:`Client
` or :phpclass:`Database ` object used to
select the collection.
Operations within the :phpclass:`MongoDB\\Collection` class inherit the
collection's options.
Type Map Limitations
--------------------
The :manual:`aggregate ` (when not using a
cursor), :manual:`distinct `, and
:manual:`findAndModify ` helpers do not
support a ``typeMap`` option due to a driver limitation. The
:phpmethod:`aggregate() `,
:phpmethod:`distinct() `,
:phpmethod:`findOneAndReplace() `,
:phpmethod:`findOneAndUpdate() `, and
:phpmethod:`findOneAndDelete() `
methods return BSON documents as `stdClass` objects and BSON arrays as
arrays.
Methods
-------
.. toctree::
:titlesonly:
/reference/method/MongoDBCollection__construct
/reference/method/MongoDBCollection-aggregate
/reference/method/MongoDBCollection-bulkWrite
/reference/method/MongoDBCollection-count
/reference/method/MongoDBCollection-countDocuments
/reference/method/MongoDBCollection-createIndex
/reference/method/MongoDBCollection-createIndexes
/reference/method/MongoDBCollection-deleteMany
/reference/method/MongoDBCollection-deleteOne
/reference/method/MongoDBCollection-distinct
/reference/method/MongoDBCollection-drop
/reference/method/MongoDBCollection-dropIndex
/reference/method/MongoDBCollection-dropIndexes
/reference/method/MongoDBCollection-estimatedDocumentCount
/reference/method/MongoDBCollection-explain
/reference/method/MongoDBCollection-find
/reference/method/MongoDBCollection-findOne
/reference/method/MongoDBCollection-findOneAndDelete
/reference/method/MongoDBCollection-findOneAndReplace
/reference/method/MongoDBCollection-findOneAndUpdate
/reference/method/MongoDBCollection-getCollectionName
/reference/method/MongoDBCollection-getDatabaseName
/reference/method/MongoDBCollection-getManager
/reference/method/MongoDBCollection-getNamespace
/reference/method/MongoDBCollection-getReadConcern
/reference/method/MongoDBCollection-getReadPreference
/reference/method/MongoDBCollection-getTypeMap
/reference/method/MongoDBCollection-getWriteConcern
/reference/method/MongoDBCollection-insertMany
/reference/method/MongoDBCollection-insertOne
/reference/method/MongoDBCollection-listIndexes
/reference/method/MongoDBCollection-mapReduce
/reference/method/MongoDBCollection-replaceOne
/reference/method/MongoDBCollection-updateMany
/reference/method/MongoDBCollection-updateOne
/reference/method/MongoDBCollection-watch
/reference/method/MongoDBCollection-withOptions
docs/reference/class/MongoDBClient.txt 0000666 00000002565 13645314021 0013737 0 ustar 00 =====================
MongoDB\\Client Class
=====================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpclass:: MongoDB\\Client
This class serves as an entry point for the |php-library|. It is the
preferred class for connecting to a MongoDB server or cluster of servers and
acts as a gateway for accessing individual databases and collections.
:phpclass:`MongoDB\\Client` is analogous to the driver's
:php:`MongoDB\\Driver\\Manager ` class, which it
`composes `_.
Methods
-------
.. toctree::
:titlesonly:
/reference/method/MongoDBClient__construct
/reference/method/MongoDBClient__get
/reference/method/MongoDBClient-createClientEncryption
/reference/method/MongoDBClient-dropDatabase
/reference/method/MongoDBClient-getManager
/reference/method/MongoDBClient-getReadConcern
/reference/method/MongoDBClient-getReadPreference
/reference/method/MongoDBClient-getTypeMap
/reference/method/MongoDBClient-getWriteConcern
/reference/method/MongoDBClient-listDatabases
/reference/method/MongoDBClient-selectCollection
/reference/method/MongoDBClient-selectDatabase
/reference/method/MongoDBClient-startSession
/reference/method/MongoDBClient-watch
docs/reference/class/MongoDBDatabase.txt 0000666 00000004520 13645314021 0014216 0 ustar 00 =======================
MongoDB\\Database Class
=======================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpclass:: MongoDB\\Database
Provides methods for common operations on a database, such as executing
database commands and managing collections.
You can construct a database directly using the driver's
:php:`MongoDB\\Driver\\Manager ` class or
select a database from the library's :phpclass:`MongoDB\\Client` class. A
database may also be cloned from an existing :phpclass:`MongoDB\\Database`
object via the :phpmethod:`withOptions() `
method.
:phpclass:`MongoDB\\Database` supports the :php:`readConcern
`, :php:`readPreference
`, :php:`typeMap
`,
and :php:`writeConcern ` options. If you omit an
option, the database inherits the value from the :php:`Manager
` constructor argument or the :phpclass:`Client
` object used to select the database.
Operations within the :phpclass:`MongoDB\\Database` class inherit the
Database's options.
Methods
-------
.. toctree::
:titlesonly:
/reference/method/MongoDBDatabase__construct
/reference/method/MongoDBDatabase__get
/reference/method/MongoDBDatabase-aggregate
/reference/method/MongoDBDatabase-command
/reference/method/MongoDBDatabase-createCollection
/reference/method/MongoDBDatabase-drop
/reference/method/MongoDBDatabase-dropCollection
/reference/method/MongoDBDatabase-getDatabaseName
/reference/method/MongoDBDatabase-getManager
/reference/method/MongoDBDatabase-getReadConcern
/reference/method/MongoDBDatabase-getReadPreference
/reference/method/MongoDBDatabase-getTypeMap
/reference/method/MongoDBDatabase-getWriteConcern
/reference/method/MongoDBDatabase-listCollections
/reference/method/MongoDBDatabase-modifyCollection
/reference/method/MongoDBDatabase-selectCollection
/reference/method/MongoDBDatabase-selectGridFSBucket
/reference/method/MongoDBDatabase-watch
/reference/method/MongoDBDatabase-withOptions
docs/reference/class/MongoDBGridFSBucket.txt 0000666 00000004432 13645314021 0014770 0 ustar 00 =============================
MongoDB\\GridFS\\Bucket Class
=============================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpclass:: MongoDB\\GridFS\\Bucket
:manual:`GridFS ` is a specification for storing and retrieving
files in MongoDB. GridFS uses two collections to store files. One collection
stores the file chunks (e.g. ``fs.chunks``), and the other stores file
metadata (e.g. ``fs.files``). The :phpclass:`MongoDB\\GridFS\\Bucket` class
provides an interface around these collections for working with the files as
PHP :php:`Streams `.
You can construct a GridFS bucket using the driver's
:php:`Manager ` class, or select a bucket from
the library's :phpclass:`MongoDB\\Database` class via the
:phpmethod:`selectGridFSBucket() `
method.
Methods
-------
.. toctree::
:titlesonly:
/reference/method/MongoDBGridFSBucket__construct
/reference/method/MongoDBGridFSBucket-delete
/reference/method/MongoDBGridFSBucket-downloadToStream
/reference/method/MongoDBGridFSBucket-downloadToStreamByName
/reference/method/MongoDBGridFSBucket-drop
/reference/method/MongoDBGridFSBucket-find
/reference/method/MongoDBGridFSBucket-findOne
/reference/method/MongoDBGridFSBucket-getBucketName
/reference/method/MongoDBGridFSBucket-getChunksCollection
/reference/method/MongoDBGridFSBucket-getChunkSizeBytes
/reference/method/MongoDBGridFSBucket-getDatabaseName
/reference/method/MongoDBGridFSBucket-getFileDocumentForStream
/reference/method/MongoDBGridFSBucket-getFileIdForStream
/reference/method/MongoDBGridFSBucket-getFilesCollection
/reference/method/MongoDBGridFSBucket-getReadConcern
/reference/method/MongoDBGridFSBucket-getReadPreference
/reference/method/MongoDBGridFSBucket-getTypeMap
/reference/method/MongoDBGridFSBucket-getWriteConcern
/reference/method/MongoDBGridFSBucket-openDownloadStream
/reference/method/MongoDBGridFSBucket-openDownloadStreamByName
/reference/method/MongoDBGridFSBucket-openUploadStream
/reference/method/MongoDBGridFSBucket-rename
/reference/method/MongoDBGridFSBucket-uploadFromStream
docs/reference/method/MongoDBGridFSBucket-getReadPreference.txt 0000666 00000002444 13645314021 0020514 0 ustar 00 ============================================
MongoDB\\GridFS\\Bucket::getReadPreference()
============================================
.. versionadded:: 1.2
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\GridFS\\Bucket::getReadPreference()
Returns the read preference for this GridFS bucket.
.. code-block:: php
function getReadPreference(): MongoDB\Driver\ReadPreference
Return Values
-------------
A :php:`MongoDB\\Driver\\ReadPreference `
object.
Example
-------
.. code-block:: php
selectDatabase('test');
$bucket = $database->selectGridFSBucket([
'readPreference' => new MongoDB\Driver\ReadPreference('primaryPreferred'),
]);
var_dump($bucket->getReadPreference());
The output would then resemble::
object(MongoDB\Driver\ReadPreference)#3 (1) {
["mode"]=>
string(16) "primaryPreferred"
}
See Also
--------
- :manual:`Read Preference ` in the MongoDB manual
- :phpmethod:`MongoDB\\Client::getReadPreference()`
- :phpmethod:`MongoDB\\Collection::getReadPreference()`
- :phpmethod:`MongoDB\\Database::getReadPreference()`
docs/reference/method/MongoDBChangeStream-rewind.txt 0000666 00000003073 13645314021 0016516 0 ustar 00 ===============================
MongoDB\\ChangeStream::rewind()
===============================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\ChangeStream::rewind()
Rewinds the change stream and attempts to load the first event.
.. code-block:: php
function rewind(): void
This method should be called at the start of change stream iteration.
.. note::
Rewinding the change stream does not guarantee that there will be a
current event to access. You should still call
:phpmethod:`MongoDB\\ChangeStream::valid()` to check for a current event
at each step of iteration. After initially rewinding the change stream,
:phpmethod:`MongoDB\\ChangeStream::next()` should be used to iterate
further.
Errors/Exceptions
-----------------
:php:`MongoDB\\Driver\\Exception\\LogicException
` if this method is called after a call
to :phpmethod:`MongoDB\\ChangeStream::next()` (i.e. the underlying
:php:`MongoDB\\Driver\\Cursor ` has already been
advanced).
.. include:: /includes/extracts/error-driver-runtimeexception.rst
See Also
--------
- :phpmethod:`MongoDB\\Client::watch()`
- :phpmethod:`MongoDB\\Collection::watch()`
- :phpmethod:`MongoDB\\Database::watch()`
- :php:`Iterator::rewind() `
- :ref:`Tailable Cursor Iteration `
- :manual:`Change Streams ` documentation in the MongoDB manual
docs/reference/method/MongoDBDatabase-selectCollection.txt 0000666 00000003552 13645314021 0017666 0 ustar 00 =====================================
MongoDB\\Database::selectCollection()
=====================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Database::selectCollection()
Selects a collection within the database.
.. code-block:: php
function selectCollection($collectionName, array $options = []): MongoDB\Collection
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBDatabase-method-selectCollection-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBDatabase-method-selectCollection-option.rst
Return Values
-------------
A :phpclass:`MongoDB\\Collection` object.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-invalidargumentexception.rst
Behavior
--------
The selected collection inherits options such as read preference and type
mapping from the :phpclass:`Database ` object. Options may be
overridden via the ``$options`` parameter.
Example
-------
The following example selects the ``users`` collection in the ``test`` database:
.. code-block:: php
test;
$collection = $db->selectCollection('users');
The following example selects the ``users`` collection in the ``test``
database with a custom read preference:
.. code-block:: php
test;
$users = $db->selectCollection(
'users',
[
'readPreference' => new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY),
]
);
See Also
--------
- :phpmethod:`MongoDB\\Database::__get()`
- :phpmethod:`MongoDB\\Client::selectCollection()`
- :phpmethod:`MongoDB\\Collection::__construct()`
docs/reference/method/MongoDBInsertOneResult-getInsertedCount.txt 0000666 00000001632 13645314021 0021257 0 ustar 00 ============================================
MongoDB\\InsertOneResult::getInsertedCount()
============================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\InsertOneResult::getInsertedCount()
Return the number of documents that were inserted.
.. code-block:: php
function getInsertedCount(): integer
This method should only be called if the write was acknowledged.
Return Values
-------------
The number of documents that were inserted. This should be ``1`` for an
acknowledged insert operation.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-badmethodcallexception-write-result.rst
See Also
--------
- :php:`MongoDB\\Driver\\WriteResult::getInsertedCount()
`
docs/reference/method/MongoDBGridFSBucket-rename.txt 0000666 00000002207 13645314021 0016406 0 ustar 00 =================================
MongoDB\\GridFS\\Bucket::rename()
=================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\GridFS\\Bucket::rename()
Selects a GridFS file by its ``_id`` and alters its ``filename``.
.. code-block:: php
function rename($id, $newFilename): void
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBGridFSBucket-method-rename-param.rst
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-gridfs-filenotfoundexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Examples
--------
.. code-block:: php
test->selectGridFSBucket();
$stream = fopen('php://temp', 'w+b');
fwrite($stream, "foobar");
rewind($stream);
$id = $bucket->uploadFromStream('a', $stream);
$bucket->rename($id, 'b');
var_dump(stream_get_contents($bucket->openDownloadStreamByName('b')));
The output would then resemble::
string(6) "foobar"
docs/reference/method/MongoDBCollection-updateMany.txt 0000666 00000004271 13645314021 0017070 0 ustar 00 =================================
MongoDB\\Collection::updateMany()
=================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::updateMany()
Update all documents that match the filter criteria.
.. code-block:: php
function updateMany($filter, $update, array $options = []): MongoDB\UpdateResult
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-updateMany-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-updateMany-option.rst
Return Values
-------------
A :phpclass:`MongoDB\\UpdateResult` object, which encapsulates a
:php:`MongoDB\\Driver\\WriteResult ` object.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-unsupportedexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-bulkwriteexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Behavior
--------
.. include:: /includes/extracts/note-bson-comparison.rst
.. include:: /includes/extracts/bulkwriteexception-result.rst
Examples
--------
The following example updates all of the documents with the ``borough`` of
``"Queens"`` by setting the ``active`` field to ``true``:
.. code-block:: php
$collection = (new MongoDB\Client)->test->restaurants;
$updateResult = $collection->updateMany(
[ 'borough' => 'Queens' ],
[ '$set' => [ 'active' => 'True' ]]
);
printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());
The output would then resemble::
Matched 5656 document(s)
Modified 5656 document(s)
See Also
--------
- :phpmethod:`MongoDB\\Collection::replaceOne()`
- :phpmethod:`MongoDB\\Collection::updateOne()`
- :phpmethod:`MongoDB\\Collection::bulkWrite()`
- :doc:`/tutorial/crud`
- :manual:`update ` command reference in the MongoDB
manual
docs/reference/method/MongoDBGridFSBucket-openDownloadStream.txt 0000666 00000002771 13645314021 0020752 0 ustar 00 =============================================
MongoDB\\GridFS\\Bucket::openDownloadStream()
=============================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\GridFS\\Bucket::openDownloadStream()
Selects a GridFS file by its ``_id`` and opens it as a readable stream.
.. code-block:: php
function openDownloadStream($id): resource
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBGridFSBucket-method-openDownloadStream-param.rst
Return Values
-------------
A readable stream resource.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-gridfs-filenotfoundexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Examples
--------
.. code-block:: php
test->selectGridFSBucket();
$uploadStream = fopen('php://temp', 'w+b');
fwrite($uploadStream, "foobar");
rewind($uploadStream);
$id = $bucket->uploadFromStream('filename', $uploadStream);
$downloadStream = $bucket->openDownloadStream($id);
var_dump(stream_get_contents($downloadStream));
The output would then resemble::
string(6) "foobar"
See Also
--------
- :phpmethod:`MongoDB\\GridFS\\Bucket::downloadToStream()`
- :phpmethod:`MongoDB\\GridFS\\Bucket::downloadToStreamByName()`
- :phpmethod:`MongoDB\\GridFS\\Bucket::openDownloadStreamByName()`
docs/reference/method/MongoDBDatabase-command.txt 0000666 00000007060 13645314021 0016007 0 ustar 00 ============================
MongoDB\\Database::command()
============================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Database::command()
Execute a :manual:`command ` on the database.
.. code-block:: php
function command($command, array $options = []): MongoDB\Driver\Cursor
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBDatabase-method-command-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBDatabase-method-command-option.rst
Return Values
-------------
A :php:`MongoDB\\Driver\\Cursor ` object.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Example
-------
The following example executes an :manual:`isMaster
` command, which returns a cursor with a single
result document:
.. code-block:: php
test;
$cursor = $database->command(['isMaster' => 1]);
var_dump($c->toArray()[0]);
The output would resemble::
object(MongoDB\Model\BSONDocument)#11 (1) {
["storage":"ArrayObject":private]=>
array(8) {
["ismaster"]=>
bool(true)
["maxBsonObjectSize"]=>
int(16777216)
["maxMessageSizeBytes"]=>
int(48000000)
["maxWriteBatchSize"]=>
int(1000)
["localTime"]=>
object(MongoDB\BSON\UTCDateTime)#3 (1) {
["milliseconds"]=>
string(13) "1477608046464"
}
["maxWireVersion"]=>
int(4)
["minWireVersion"]=>
int(0)
["ok"]=>
float(1)
}
}
The following example executes a :manual:`listCollections
` command, which returns a cursor with
multiple result documents:
.. code-block:: php
test;
$cursor = $database->command(['isMaster' => 1]);
var_dump($c->toArray());
The output would resemble::
array(3) {
[0]=>
object(MongoDB\Model\BSONDocument)#11 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["name"]=>
string(11) "restaurants"
["options"]=>
object(MongoDB\Model\BSONDocument)#3 (1) {
["storage":"ArrayObject":private]=>
array(0) {
}
}
}
}
[1]=>
object(MongoDB\Model\BSONDocument)#13 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["name"]=>
string(5) "users"
["options"]=>
object(MongoDB\Model\BSONDocument)#12 (1) {
["storage":"ArrayObject":private]=>
array(0) {
}
}
}
}
[2]=>
object(MongoDB\Model\BSONDocument)#15 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["name"]=>
string(6) "restos"
["options"]=>
object(MongoDB\Model\BSONDocument)#14 (1) {
["storage":"ArrayObject":private]=>
array(0) {
}
}
}
}
}
See Also
--------
- :doc:`/tutorial/commands`
- :manual:`Database Commands ` in the MongoDB manual
- :php:`MongoDB\\Driver\\Cursor `
- :php:`MongoDB\\Driver\\Manager::executeCommand()
`
docs/reference/method/MongoDBGridFSBucket-downloadToStreamByName.txt 0000666 00000003411 13645314021 0021517 0 ustar 00 =================================================
MongoDB\\GridFS\\Bucket::downloadToStreamByName()
=================================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\GridFS\\Bucket::downloadToStreamByName()
Selects a GridFS file by its ``filename`` and copies its contents to a
writable stream.
.. code-block:: php
function downloadToStreamByName($filename, $destination, array $options = []): void
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBGridFSBucket-method-downloadToStreamByName-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBGridFSBucket-method-downloadToStreamByName-option.rst
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-gridfs-filenotfoundexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Examples
--------
.. code-block:: php
test->selectGridFSBucket();
$stream = fopen('php://temp', 'w+b');
fwrite($stream, "foobar");
rewind($stream);
$bucket->uploadFromStream('filename', $stream);
$destination = fopen('php://temp', 'w+b');
$bucket->downloadToStreamByName('filename', $destination);
var_dump(stream_get_contents($destination, -1, 0));
The output would then resemble::
string(6) "foobar"
See Also
--------
- :phpmethod:`MongoDB\\GridFS\\Bucket::downloadToStream()`
- :phpmethod:`MongoDB\\GridFS\\Bucket::openDownloadStream()`
- :phpmethod:`MongoDB\\GridFS\\Bucket::openDownloadStreamByName()`
docs/reference/method/MongoDBClient-dropDatabase.txt 0000666 00000003270 13645314021 0016473 0 ustar 00 ===============================
MongoDB\\Client::dropDatabase()
===============================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Client::dropDatabase()
Drop a database on the server.
.. code-block:: php
function dropDatabase($databaseName, array $options []): array|object
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBClient-method-dropDatabase-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBClient-method-dropDatabase-option.rst
Return Values
-------------
An array or object with the result document of the :manual:`dropDatabase
` command. The return type will depend on the
``typeMap`` option.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-unsupportedexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Example
-------
The following example drops the ``test`` database:
.. code-block:: php
dropDatabase('test');
var_dump($result);
The output would then resemble::
object(MongoDB\Model\BSONDocument)#8 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["dropped"]=>
string(4) "test"
["ok"]=>
float(1)
}
}
See Also
--------
- :phpmethod:`MongoDB\\Database::drop()`
- :manual:`dropDatabase ` command reference in
the MongoDB manual
docs/reference/method/MongoDBGridFSBucket-getBucketName.txt 0000666 00000001274 13645314021 0017660 0 ustar 00 ========================================
MongoDB\\GridFS\\Bucket::getBucketName()
========================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\GridFS\\Bucket::getBucketName()
Returns the name of this bucket.
.. code-block:: php
function getBucketName(): string
Return Values
-------------
The name of this bucket as a string.
Examples
--------
.. code-block:: php
test->selectGridFSBucket();
var_dump($bucket->getBucketName());
The output would then resemble::
string(2) "fs"
docs/reference/method/MongoDBModelCollectionInfo-getCappedSize.txt 0000666 00000002572 13645314021 0021307 0 ustar 00 ===============================================
MongoDB\\Model\\CollectionInfo::getCappedSize()
===============================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Model\\CollectionInfo::getCappedSize()
Return the size limit for the capped collection in bytes. This correlates
with the ``size`` option for
:phpmethod:`MongoDB\\Database::createCollection()`.
.. code-block:: php
function getCappedSize(): integer|null
Return Values
-------------
The size limit for the capped collection in bytes. If the collection is not
capped, ``null`` will be returned.
Examples
--------
.. code-block:: php
'foo',
'options' => [
'capped' => true,
'size' => 1048576,
]
]);
var_dump($info->getCappedSize());
The output would then resemble::
int(1048576)
See Also
--------
- :phpmethod:`MongoDB\\Model\\CollectionInfo::getCappedMax()`
- :phpmethod:`MongoDB\\Model\\CollectionInfo::isCapped()`
- :phpmethod:`MongoDB\\Database::createCollection()`
- :manual:`Capped Collections ` in the MongoDB manual
- :manual:`listCollections ` command
reference in the MongoDB manual
docs/reference/method/MongoDBGridFSBucket-getDatabaseName.txt 0000666 00000001373 13645314021 0020147 0 ustar 00 ==========================================
MongoDB\\GridFS\\Bucket::getDatabaseName()
==========================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\GridFS\\Bucket::getDatabaseName()
Returns the name of the database containing this bucket.
.. code-block:: php
function getDatabaseName(): string
Return Values
-------------
The name of the database containing this bucket as a string.
Examples
--------
.. code-block:: php
test->selectGridFSBucket();
var_dump($bucket->getDatabaseName());
The output would then resemble::
string(4) "test"
docs/reference/method/MongoDBCollection-getManager.txt 0000666 00000001333 13645314021 0017027 0 ustar 00 =================================
MongoDB\\Collection::getManager()
=================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::getManager()
Accessor for the
:php:`MongoDB\\Driver\\Manager ` used by this
:phpclass:`Collection `.
.. code-block:: php
function getManager(): MongoDB\Manager
Return Values
-------------
A :php:`MongoDB\\Driver\\Manager ` object.
See Also
--------
- :phpmethod:`MongoDB\\Client::getManager()`
- :phpmethod:`MongoDB\\Database::getManager()`
docs/reference/method/MongoDBInsertManyResult-getInsertedCount.txt 0000666 00000001543 13645314021 0021443 0 ustar 00 =============================================
MongoDB\\InsertManyResult::getInsertedCount()
=============================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\InsertManyResult::getInsertedCount()
Return the number of documents that were inserted.
.. code-block:: php
function getInsertedCount(): integer
This method should only be called if the write was acknowledged.
Return Values
-------------
The number of documents that were inserted.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-badmethodcallexception-write-result.rst
See Also
--------
- :php:`MongoDB\\Driver\\WriteResult::getInsertedCount()
`
docs/reference/method/MongoDBChangeStream-current.txt 0000666 00000006170 13645314021 0016711 0 ustar 00 ================================
MongoDB\\ChangeStream::current()
================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\ChangeStream::current()
Returns the current event in the change stream.
.. code-block:: php
function current(): array|object|null
The structure of each event document will vary based on the operation type.
See :manual:`Change Events ` in the MongoDB manual
for more information.
Return Values
-------------
An array or object for the current event in the change stream, or ``null`` if
there is no current event (i.e. :phpmethod:`MongoDB\\ChangeStream::valid()`
returns ``false``). The return type will depend on the ``typeMap`` option for
:phpmethod:`MongoDB\\Collection::watch()`.
Examples
--------
This example reports events while iterating a change stream.
.. code-block:: php
test->inventory;
$changeStream = $collection->watch();
for ($changeStream->rewind(); true; $changeStream->next()) {
if ( ! $changeStream->valid()) {
continue;
}
$event = $changeStream->current();
$ns = sprintf('%s.%s', $event['ns']['db'], $event['ns']['coll']);
$id = json_encode($event['documentKey']['_id']);
switch ($event['operationType']) {
case 'delete':
printf("Deleted document in %s with _id: %s\n\n", $ns, $id);
break;
case 'insert':
printf("Inserted new document in %s\n", $ns);
echo json_encode($event['fullDocument']), "\n\n";
break;
case 'replace':
printf("Replaced new document in %s with _id: %s\n", $ns, $id);
echo json_encode($event['fullDocument']), "\n\n";
break;
case 'update':
printf("Updated document in %s with _id: %s\n", $ns, $id);
echo json_encode($event['updateDescription']), "\n\n";
break;
}
}
Assuming that a document was inserted, updated, and deleted while the above
script was iterating the change stream, the output would then resemble:
.. code-block:: none
Inserted new document in test.inventory
{"_id":{"$oid":"5a81fc0d6118fd1af1790d32"},"name":"Widget","quantity":5}
Updated document in test.inventory with _id: {"$oid":"5a81fc0d6118fd1af1790d32"}
{"updatedFields":{"quantity":4},"removedFields":[]}
Deleted document in test.inventory with _id: {"$oid":"5a81fc0d6118fd1af1790d32"}
See Also
--------
- :phpmethod:`MongoDB\\Client::watch()`
- :phpmethod:`MongoDB\\Collection::watch()`
- :phpmethod:`MongoDB\\Database::watch()`
- :php:`Iterator::current() `
- :ref:`Tailable Cursor Iteration `
- :manual:`Change Streams ` documentation in the MongoDB manual
- :manual:`Change Events ` documentation in the
MongoDB manual docs/reference/method/MongoDBModelCollectionInfo-isCapped.txt 0000666 00000002266 13645314021 0020310 0 ustar 00 ==========================================
MongoDB\\Model\\CollectionInfo::isCapped()
==========================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Model\\CollectionInfo::isCapped()
Return whether the collection is a :manual:`capped collection
`.
.. code-block:: php
function isCapped(): boolean
Return Values
-------------
A boolean indicating whether the collection is a capped collection.
Examples
--------
.. code-block:: php
'foo',
'options' => [
'capped' => true,
'size' => 1048576,
]
]);
var_dump($info->isCapped());
The output would then resemble::
bool(true)
See Also
--------
- :phpmethod:`MongoDB\\Model\\CollectionInfo::getCappedMax()`
- :phpmethod:`MongoDB\\Model\\CollectionInfo::getCappedSize()`
- :manual:`Capped Collections ` in the MongoDB manual
- :manual:`listCollections ` command
reference in the MongoDB manual
docs/reference/method/MongoDBDatabase-modifyCollection.txt 0000666 00000003374 13645314021 0017700 0 ustar 00 =====================================
MongoDB\\Database::modifyCollection()
=====================================
.. versionadded:: 1.4
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Database::modifyCollection()
Modifies a collection or view according to the specified
``$collectionOptions``.
.. code-block:: php
function modifyCollection($collectionName, array $collectionOptions, array $options = []): array|object
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBDatabase-method-modifyCollection-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBDatabase-method-modifyCollection-option.rst
Return Values
-------------
An array or object with the result document of the :manual:`collMod
` command.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Example
-------
The following example changes the expiration time of a TTL collection in the
``test`` database:
.. code-block:: php
test;
$result = $db->modifyCollection('users', [
'keyPattern' => ['lastAccess' => 1],
'expireAfterSeconds' => 1000
]);
var_dump($result);
The output would then resemble::
object(stdClass)#2779 {
["expireAfterSeconds_old"]=>
int(3)
["expireAfterSeconds_new"]=>
int(1000)
["ok"]=>
float(1)
}
See Also
--------
- :manual:`collMod ` command reference in the MongoDB
manual
docs/reference/method/MongoDBGridFSBucket-getFileIdForStream.txt 0000666 00000002773 13645314021 0020626 0 ustar 00 =============================================
MongoDB\\GridFS\\Bucket::getFileIdForStream()
=============================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\GridFS\\Bucket::getFileIdForStream()
Gets the file document's ID of the GridFS file associated with a stream.
.. code-block:: php
function getFileIdForStream($stream): mixed
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBGridFSBucket-method-getFileIdForStream-param.rst
Return Values
-------------
The ``_id`` field of the metadata document associated with the GridFS stream.
The return type will depend on the bucket's ``typeMap`` option.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-gridfs-corruptfileexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Examples
--------
.. code-block:: php
test->selectGridFSBucket();
$stream = $bucket->openUploadStream('filename');
$id = $bucket->getFileIdForStream($stream);
var_dump($id);
fclose($stream);
The output would then resemble::
object(MongoDB\BSON\ObjectId)#3005 (1) {
["oid"]=>
string(24) "5acfb37d7e21e83cdb3e1583"
}
See Also
--------
- :phpmethod:`MongoDB\\GridFS\\Bucket::getFileDocumentForStream()`
docs/reference/method/MongoDBGridFSBucket-drop.txt 0000666 00000001477 13645314021 0016113 0 ustar 00 ===============================
MongoDB\\GridFS\\Bucket::drop()
===============================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\GridFS\\Bucket::drop()
Drops the files and chunks collections associated with this GridFS bucket.
.. code-block:: php
function drop(): void
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Examples
--------
.. code-block:: php
test;
$bucket = $database->selectGridFSBucket();
$stream = fopen('php://temp', 'w+b');
fwrite($stream, "foobar");
rewind($stream);
$bucket->uploadFromStream('filename', $stream);
$bucket->drop();
docs/reference/method/MongoDBCollection-getDatabaseName.txt 0000666 00000001666 13645314021 0017773 0 ustar 00 ======================================
MongoDB\\Collection::getDatabaseName()
======================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::getDatabaseName()
Returns the name of the database containing this collection.
.. code-block:: php
function getDatabaseName(): string
Return Values
-------------
The name of the database containing this collection as a string.
Example
-------
The following returns the database name for the ``zips`` collection in the
``test`` database.
.. code-block:: php
test->zips;
echo $collection->getDatabaseName();
The output would then resemble::
test
See Also
--------
- :phpmethod:`MongoDB\\Collection::getCollectionName()`
- :phpmethod:`MongoDB\\Collection::getNamespace()`
docs/reference/method/MongoDBDatabase__construct.txt 0000666 00000002454 13645314021 0016640 0 ustar 00 ================================
MongoDB\\Database::__construct()
================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Database::__construct()
Constructs a new :phpclass:`Database ` instance.
.. code-block:: php
function __construct(MongoDB\Driver\Manager $manager, $databaseName, array $options = [])
This constructor has the following parameters:
.. include:: /includes/apiargs/MongoDBDatabase-method-construct-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBDatabase-method-construct-option.rst
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-invalidargumentexception.rst
Behavior
--------
If you construct a Database explicitly, the Database inherits any options from
the :php:`MongoDB\\Driver\\Manager ` object. If
you select the Database from a :phpclass:`Client ` object, the
Database inherits its options from that object.
See Also
--------
- :phpmethod:`MongoDB\\Database::withOptions()`
- :phpmethod:`MongoDB\\Client::selectDatabase()`
- :phpmethod:`MongoDB\\Client::__get()`
docs/reference/method/MongoDBModelCollectionInfo-getOptions.txt 0000666 00000002233 13645314021 0020705 0 ustar 00 ============================================
MongoDB\\Model\\CollectionInfo::getOptions()
============================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Model\\CollectionInfo::getOptions()
Return the collection options. This correlates with the options for
:phpmethod:`MongoDB\\Database::createCollection()`, but may include
additional fields set by the server.
.. code-block:: php
function getOptions(): array
Return Values
-------------
The collection options.
Examples
--------
.. code-block:: php
'foo',
'options' => [
'capped' => true,
'size' => 1048576,
]
]);
var_dump($info->getOptions());
The output would then resemble::
array(2) {
["capped"]=>
bool(true)
["size"]=>
int(1048576)
}
See Also
--------
- :phpmethod:`MongoDB\\Database::createCollection()`
- :manual:`listCollections ` command
reference in the MongoDB manual
docs/reference/method/MongoDBGridFSBucket-getChunkSizeBytes.txt 0000666 00000001375 13645314021 0020556 0 ustar 00 ============================================
MongoDB\\GridFS\\Bucket::getChunkSizeBytes()
============================================
.. versionchanged:: 1.2
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\GridFS\\Bucket::getChunkSizeBytes()
Returns the chunk size of this bucket in bytes.
.. code-block:: php
function getChunkSizeBytes(): integer
Return Values
-------------
The chunk size of this bucket in bytes.
Examples
--------
.. code-block:: php
test->selectGridFSBucket();
var_dump($bucket->getChunkSizeBytes());
The output would then resemble::
int(261120)
docs/reference/method/MongoDBBulkWriteResult-getMatchedCount.txt 0000666 00000002506 13645314021 0021052 0 ustar 00 ===========================================
MongoDB\\BulkWriteResult::getMatchedCount()
===========================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\BulkWriteResult::getMatchedCount()
Return the total number of documents that were matched by all update and
replace operations in the bulk write.
.. code-block:: php
function getMatchedCount(): integer
This method should only be called if the write was acknowledged.
.. note::
If an update/replace operation results in no change to the document
(e.g. setting the value of a field to its current value), the matched
count may be greater than the value returned by
:phpmethod:`getModifiedCount()
`.
Return Values
-------------
The total number of documents that were matched by all update and replace
operations in the bulk write.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-badmethodcallexception-write-result.rst
See Also
--------
- :phpmethod:`MongoDB\\BulkWriteResult::getModifiedCount()`
- :php:`MongoDB\\Driver\\WriteResult::getMatchedCount()
`
docs/reference/method/MongoDBCollection-mapReduce.txt 0000666 00000006734 13645314021 0016674 0 ustar 00 =================================
MongoDB\\Collection::mapReduce()
=================================
.. versionadded:: 1.2
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::mapReduce()
The :manual:`mapReduce ` command allows you to
run map-reduce aggregation operations over a collection.
.. code-block:: php
function mapReduce($map, $reduce, $out, array $options = []): MongoDB\MapReduceResult
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-mapReduce-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-mapReduce-option.rst
Return Values
-------------
A :phpclass:`MongoDB\\MapReduceResult` object, which allows for iteration of
map-reduce results irrespective of the output method (e.g. inline, collection)
via the :php:`IteratorAggregate ` interface. It also
provides access to command statistics.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-unsupportedexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-unexpectedvalueexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Behavior
--------
In MongoDB, the map-reduce operation can write results to a collection
or return the results inline. If you write map-reduce output to a
collection, you can perform subsequent map-reduce operations on the
same input collection that merge replace, merge, or reduce new results
with previous results. See :manual:`Map-Reduce ` and
:manual:`Perform Incremental Map-Reduce `
for details and examples.
When returning the results of a map-reduce operation *inline*, the
result documents must be within the :limit:`BSON Document Size` limit,
which is currently 16 megabytes.
MongoDB supports map-reduce operations on :manual:`sharded collections
`. Map-reduce operations can also output
the results to a sharded collection. See
:manual:`Map-Reduce and Sharded Collections `.
Example
-------
This example will use city populations to calculate the overall population of
each state.
.. code-block:: php
test->zips;
$map = new MongoDB\BSON\Javascript('function() { emit(this.state, this.pop); }');
$reduce = new MongoDB\BSON\Javascript('function(key, values) { return Array.sum(values) }');
$out = ['inline' => 1];
$populations = $collection->mapReduce($map, $reduce, $out);
foreach ($populations as $pop) {
var_dump($pop);
};
The output would then resemble::
object(stdClass)#2293 (2) {
["_id"]=>
string(2) "AK"
["value"]=>
float(544698)
}
object(stdClass)#2300 (2) {
["_id"]=>
string(2) "AL"
["value"]=>
float(4040587)
}
object(stdClass)#2293 (2) {
["_id"]=>
string(2) "AR"
["value"]=>
float(2350725)
}
object(stdClass)#2300 (2) {
["_id"]=>
string(2) "AZ"
["value"]=>
float(3665228)
}
See Also
--------
- :manual:`mapReduce ` command reference in the MongoDB
manual
- :manual:`Map-Reduce ` documentation in the MongoDB manual
docs/reference/method/MongoDBDatabase-createCollection.txt 0000666 00000005547 13645314021 0017660 0 ustar 00 =====================================
MongoDB\\Database::createCollection()
=====================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Database::createCollection()
Explicitly creates a collection.
.. code-block:: php
function createCollection($collectionName, array $options = []): array|object
MongoDB creates collections implicitly when you first reference the
collection in a command, such as when inserting a document into a new
collection. You may also explicitly create a collection with specific options
using the :phpmethod:`MongoDB\\Database::createCollection()` method, or using
:manual:`db.createCollection() ` in
the :program:`mongo` shell.
Explicitly creating collections enables you to create
:manual:`capped collections `, specify
:manual:`document validation criteria `,
or configure your storage engine or indexing options.
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBDatabase-method-createCollection-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBDatabase-method-createCollection-option.rst
Note that not all options are available on all versions of MongoDB. Document
validation, for example, was added in MongoDB 3.2; similarly, the WiredTiger
storage engine is available only for MongoDB 3.0 and later. Refer to the
:manual:`create ` command reference in the MongoDB
manual for compatibility considerations.
Return Values
-------------
An array or object with the result document of the :manual:`create
` command.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-unsupportedexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Example
-------
The following example creates a ``users`` collection in the ``test``
database with document validation criteria:
.. code-block:: php
test;
$result = $db->createCollection('users', [
'validator' => [
'username' => ['$type' => 'string'],
'email' => ['$regex' => '@mongodb\.com$'],
],
]);
var_dump($result);
The output would then resemble::
object(MongoDB\Model\BSONDocument)#11 (1) {
["storage":"ArrayObject":private]=>
array(1) {
["ok"]=>
float(1)
}
}
See Also
--------
- :manual:`create ` command reference in the MongoDB
manual
- :manual:`db.createCollection() `
docs/reference/method/MongoDBModelDatabaseInfo-isEmpty.txt 0000666 00000001457 13645314021 0017624 0 ustar 00 =======================================
MongoDB\\Model\\DatabaseInfo::isEmpty()
=======================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Model\\DatabaseInfo::isEmpty()
Return whether the database has any data.
.. code-block:: php
function isEmpty(): boolean
Return Values
-------------
A boolean indicating whether the database has any data.
Examples
--------
.. code-block:: php
true]);
var_dump($info->isEmpty());
The output would then resemble::
bool(true)
See Also
--------
- :manual:`listDatabases ` command reference
in the MongoDB manual
docs/reference/method/MongoDBCollection-dropIndex.txt 0000666 00000003572 13645314021 0016720 0 ustar 00 ================================
MongoDB\\Collection::dropIndex()
================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::dropIndex()
Drop an index from the collection.
.. code-block:: php
function dropIndex($indexName, array $options = []): array|object
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-dropIndex-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-dropIndex-option.rst
Return Values
-------------
An array or object with the result document of the :manual:`dropIndexes
` command. The return type will depend on the
``typeMap`` option.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-unsupportedexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Example
-------
The following drops an indexes with name ``borough_1`` from the ``restaurants``
collection in the ``test`` database:
.. code-block:: php
test->restaurants;
$result = $collection->dropIndex('borough_1');
var_dump($result);
The output would then resemble::
object(MongoDB\Model\BSONDocument)#9 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["nIndexesWas"]=>
int(2)
["ok"]=>
float(1)
}
}
See Also
--------
- :phpmethod:`MongoDB\\Collection::dropIndexes()`
- :doc:`/tutorial/indexes`
- :manual:`dropIndexes ` command reference in
the MongoDB manual
- :manual:`Index documentation ` in the MongoDB manual
docs/reference/method/MongoDBModelIndexInfo-isTtl.txt 0000666 00000002047 13645314021 0016630 0 ustar 00 ==================================
MongoDB\\Model\\IndexInfo::isTtl()
==================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Model\\IndexInfo::isTtl()
Return whether the index is a :manual:`TTL index `. This
correlates with the ``expireAfterSeconds`` option for
:phpmethod:`MongoDB\\Collection::createIndex()`.
.. code-block:: php
function isTtl(): boolean
Return Values
-------------
A boolean indicating whether the index is a TTL index.
Examples
--------
.. code-block:: php
100,
]);
var_dump($info->isTtl());
The output would then resemble::
bool(true)
See Also
--------
- :phpmethod:`MongoDB\\Collection::createIndex()`
- :manual:`listIndexes ` command reference in
the MongoDB manual
- :manual:`TTL Indexes ` in the MongoDB manual
docs/reference/method/MongoDBDatabase-getTypeMap.txt 0000666 00000002162 13645314021 0016446 0 ustar 00 ===============================
MongoDB\\Database::getTypeMap()
===============================
.. versionadded:: 1.2
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Database::getTypeMap()
Returns the type map for this database.
.. code-block:: php
function getTypeMap(): array
Return Values
-------------
A :ref:`type map ` array.
Example
-------
.. code-block:: php
selectDatabase('test', [
'typeMap' => [
'root' => 'array',
'document' => 'array',
'array' => 'array',
],
]);
var_dump($database->getTypeMap());
The output would then resemble::
array(3) {
["root"]=>
string(5) "array"
["document"]=>
string(5) "array"
["array"]=>
string(5) "array"
}
See Also
--------
- :doc:`/reference/bson`
- :phpmethod:`MongoDB\\Client::getTypeMap()`
- :phpmethod:`MongoDB\\Collection::getTypeMap()`
- :phpmethod:`MongoDB\\GridFS\\Bucket::getTypeMap()`
docs/reference/method/MongoDBGridFSBucket-uploadFromStream.txt 0000666 00000003322 13645314021 0020422 0 ustar 00 ===========================================
MongoDB\\GridFS\\Bucket::uploadFromStream()
===========================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\GridFS\\Bucket::uploadFromStream()
Creates a new GridFS file and copies the contents of a readable stream to it.
.. code-block:: php
function uploadFromStream($filename, $source, array $options = []): mixed
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBGridFSBucket-method-uploadFromStream-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBGridFSBucket-method-uploadFromStream-option.rst
Return Values
-------------
The ``_id`` field of the metadata document associated with the newly created
GridFS file. If the ``_id`` option is not specified, a new
:php:`MongoDB\\BSON\\ObjectId ` object will be used
by default.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Examples
--------
.. code-block:: php
test->selectGridFSBucket();
$stream = fopen('php://temp', 'w+b');
fwrite($stream, "foobar");
rewind($stream);
$id = $bucket->uploadFromStream('filename', $stream);
var_dump($id);
The output would then resemble::
object(MongoDB\BSON\ObjectId)#3009 (1) {
["oid"]=>
string(24) "5acf81017e21e816e538d883"
}
See Also
--------
- :phpmethod:`MongoDB\\GridFS\\Bucket::openUploadStream()`
docs/reference/method/MongoDBClient__construct.txt 0000666 00000010422 13645314021 0016344 0 ustar 00 ==============================
MongoDB\\Client::__construct()
==============================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Client::__construct()
Constructs a new :phpclass:`Client ` instance.
.. code-block:: php
function __construct($uri = 'mongodb://127.0.0.1/', array $uriOptions = [], array $driverOptions = [])
This constructor has the following parameters:
.. include:: /includes/apiargs/MongoDBClient-method-construct-param.rst
The ``$driverOptions`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBClient-method-construct-driverOptions.rst
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Behavior
--------
A :php:`MongoDB\\Driver\\Manager ` is constructed
internally. Per the `Server Discovery and Monitoring
`_
specification, :php:`MongoDB\\Driver\\Manager::__construct()
` performs no I/O. Connections will be
initialized on demand, when the first operation is executed.
Examples
--------
Connecting to a Replica Set
~~~~~~~~~~~~~~~~~~~~~~~~~~~
If you do not specify a ``$uri`` value, the driver connects to a standalone
:program:`mongod` on ``127.0.0.1`` via port ``27017``. The following example
demonstrates how to connect to a replica set with a custom read preference:
.. code-block:: php
'secondaryPreferred',
]
);
Connecting with SSL and Authentication
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The following example demonstrates how to connect to a MongoDB replica set with
SSL and authentication, as is used for `MongoDB Atlas
`_:
.. code-block:: php
'myUsername',
'password' => 'myPassword',
'ssl' => true,
'replicaSet' => 'myReplicaSet',
'authSource' => 'admin',
],
);
The driver supports additional :php:`SSL options
`,
which may be specified in the constructor's ``$driverOptions`` parameter. Those
options are covered in the :php:`MongoDB\\Driver\\Manager::__construct()
` documentation.
Specifying a Custom Type Map
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
By default, the |php-library| deserializes BSON documents and arrays
as :phpclass:`MongoDB\\Model\\BSONDocument` and
:phpclass:`MongoDB\\Model\\BSONArray` objects, respectively. The following
example demonstrates how to have the library unserialize everything as a PHP
array, as was done in the legacy :php:`mongo extension `.
.. code-block:: php
[
'root' => 'array',
'document' => 'array',
'array' => 'array',
],
]
);
See Also
--------
- :php:`MongoDB\\Driver\\Manager::__construct()
`
- :manual:`Connection String URI Format ` in the
MongoDB manual
- `Server Discovery and Monitoring
`_
specification
docs/reference/method/MongoDBModelCollectionInfo-getCappedMax.txt 0000666 00000002574 13645314021 0021124 0 ustar 00 ==============================================
MongoDB\\Model\\CollectionInfo::getCappedMax()
==============================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Model\\CollectionInfo::getCappedMax()
Return the document limit for the capped collection. This correlates with the
``max`` option for :phpmethod:`MongoDB\\Database::createCollection()`.
.. code-block:: php
function getCappedMax(): integer|null
Return Values
-------------
The document limit for the capped collection. If the collection is not capped,
``null`` will be returned.
Examples
--------
.. code-block:: php
'foo',
'options' => [
'capped' => true,
'size' => 1048576,
'max' => 100,
]
]);
var_dump($info->getCappedMax());
The output would then resemble::
int(100)
See Also
--------
- :phpmethod:`MongoDB\\Model\\CollectionInfo::getCappedSize()`
- :phpmethod:`MongoDB\\Model\\CollectionInfo::isCapped()`
- :phpmethod:`MongoDB\\Database::createCollection()`
- :manual:`Capped Collections ` in the MongoDB manual
- :manual:`listCollections ` command
reference in the MongoDB manual
docs/reference/method/MongoDBBulkWriteResult-getInsertedIds.txt 0000666 00000002155 13645314021 0020711 0 ustar 00 ==========================================
MongoDB\\BulkWriteResult::getInsertedIds()
==========================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\BulkWriteResult::getInsertedIds()
Return a map of IDs (i.e. ``_id`` field values) for documents that were
inserted by all insert operations in the bulk write.
.. code-block:: php
function getInsertedIds(): array
Since IDs are created by the driver, this method may be called irrespective
of whether the write was acknowledged.
Return Values
-------------
A map of IDs (i.e. ``_id`` field values) for documents that were inserted by all
insert operations in the bulk write.
The index of each ID in the map corresponds to each document's position in the
bulk operation. If a document had an ID prior to inserting (i.e. the driver did
not generate an ID), the index will contain its ``_id`` field value. Any
driver-generated ID will be a :php:`MongoDB\\BSON\\ObjectId
` instance.
docs/reference/method/MongoDBGridFSBucket-getWriteConcern.txt 0000666 00000002523 13645314021 0020242 0 ustar 00 =========================================
MongoDB\\GridFS\Bucket::getWriteConcern()
=========================================
.. versionadded:: 1.2
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\GridFS\\Bucket::getWriteConcern()
Returns the write concern for this GridFS bucket.
.. code-block:: php
function getWriteConcern(): MongoDB\Driver\WriteConcern
Return Values
-------------
A :php:`MongoDB\\Driver\\WriteConcern `
object.
Example
-------
.. code-block:: php
selectDatabase('test');
$bucket = $database->selectGridFSBucket([
'writeConcern' => new MongoDB\Driver\WriteConcern(1, 0, true),
]);
var_dump($bucket->getWriteConcern());
The output would then resemble::
object(MongoDB\Driver\WriteConcern)#3 (2) {
["w"]=>
int(1)
["j"]=>
bool(true)
}
See Also
--------
- :manual:`Write Concern ` in the MongoDB manual
- :php:`MongoDB\\Driver\\WriteConcern::isDefault() `
- :phpmethod:`MongoDB\\Client::getWriteConcern()`
- :phpmethod:`MongoDB\\Collection::getWriteConcern()`
- :phpmethod:`MongoDB\\Database::getWriteConcern()`
docs/reference/method/MongoDBCollection-getTypeMap.txt 0000666 00000002211 13645314021 0017030 0 ustar 00 =================================
MongoDB\\Collection::getTypeMap()
=================================
.. versionadded:: 1.2
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::getTypeMap()
Returns the type map for this collection.
.. code-block:: php
function getTypeMap(): array
Return Values
-------------
A :ref:`type map ` array.
Example
-------
.. code-block:: php
selectCollection('test', 'users', [
'typeMap' => [
'root' => 'array',
'document' => 'array',
'array' => 'array',
],
]);
var_dump($collection->getTypeMap());
The output would then resemble::
array(3) {
["root"]=>
string(5) "array"
["document"]=>
string(5) "array"
["array"]=>
string(5) "array"
}
See Also
--------
- :doc:`/reference/bson`
- :phpmethod:`MongoDB\\Client::getTypeMap()`
- :phpmethod:`MongoDB\\Database::getTypeMap()`
- :phpmethod:`MongoDB\\GridFS\\Bucket::getTypeMap()`
docs/reference/method/MongoDBInsertOneResult-getInsertedId.txt 0000666 00000001630 13645314021 0020521 0 ustar 00 =========================================
MongoDB\\InsertOneResult::getInsertedId()
=========================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\InsertOneResult::getInsertedId()
Return the ID (i.e. ``_id`` field value) for the inserted document.
.. code-block:: php
function getInsertedId(): mixed
Since IDs are created by the driver, this method may be called irrespective
of whether the write was acknowledged.
Return Values
-------------
The ID (i.e. ``_id`` field value) of the inserted document.
If the document had an ID prior to inserting (i.e. the driver did not need to
generate an ID), this will contain its ``_id`` field value. Any driver-generated
ID will be a :php:`MongoDB\\BSON\\ObjectId `
instance.
docs/reference/method/MongoDBUpdateResult-getMatchedCount.txt 0000666 00000002267 13645314021 0020370 0 ustar 00 ========================================
MongoDB\\UpdateResult::getMatchedCount()
========================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\UpdateResult::getMatchedCount()
Return the number of documents that were matched.
.. code-block:: php
function getMatchedCount(): integer
This method should only be called if the write was acknowledged.
.. note::
If an update/replace operation results in no change to the document
(e.g. setting the value of a field to its current value), the matched
count may be greater than the value returned by
:phpmethod:`getModifiedCount()
`.
Return Values
-------------
The number of documents that were matched.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-badmethodcallexception-write-result.rst
See Also
--------
- :phpmethod:`MongoDB\\UpdateResult::getModifiedCount()`
- :php:`MongoDB\\Driver\\WriteResult::getMatchedCount()
`
docs/reference/method/MongoDBInsertManyResult-isAcknowledged.txt 0000666 00000001354 13645314021 0021100 0 ustar 00 ===========================================
MongoDB\\InsertManyResult::isAcknowledged()
===========================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\InsertManyResult::isAcknowledged()
Return whether the write was acknowledged.
.. code-block:: php
function isAcknowledged(): boolean
Return Values
-------------
A boolean indicating whether the write was acknowledged.
See Also
--------
- :php:`MongoDB\\Driver\\WriteResult::isAcknowledged()
`
- :manual:`Write Concern ` in the MongoDB manual
docs/reference/method/MongoDBGridFSBucket-getReadConcern.txt 0000666 00000002522 13645314021 0020022 0 ustar 00 =========================================
MongoDB\\GridFS\\Bucket::getReadConcern()
=========================================
.. versionadded:: 1.2
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\GridFS\\Bucket::getReadConcern()
Returns the read concern for this GridFS bucket.
.. code-block:: php
function getReadConcern(): MongoDB\Driver\ReadConcern
Return Values
-------------
A :php:`MongoDB\\Driver\\ReadConcern ` object.
Example
-------
.. code-block:: php
selectDatabase('test');
$bucket = $database->selectGridFSBucket([
'readConcern' => new MongoDB\Driver\ReadConcern(MongoDB\Driver\ReadConcern::MAJORITY),
]);
var_dump($bucket->getReadConcern());
The output would then resemble::
object(MongoDB\Driver\ReadConcern)#3 (1) {
["level"]=>
string(8) "majority"
}
See Also
--------
- :manual:`Read Concern ` in the MongoDB manual
- :php:`MongoDB\\Driver\\ReadConcern::isDefault() `
- :phpmethod:`MongoDB\\Client::getReadConcern()`
- :phpmethod:`MongoDB\\Collection::getReadConcern()`
- :phpmethod:`MongoDB\\Database::getReadConcern()`
docs/reference/method/MongoDBCollection__construct.txt 0000666 00000002725 13645314021 0017230 0 ustar 00 ==================================
MongoDB\\Collection::__construct()
==================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::__construct()
Constructs a new :phpclass:`Collection ` instance.
.. code-block:: php
function __construct(MongoDB\Driver\Manager $manager, $databaseName, $collectionName, array $options = [])
This constructor has the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-construct-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-construct-option.rst
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-invalidargumentexception.rst
Behavior
--------
If you construct a Collection explicitly, the Collection inherits any options
from the :php:`MongoDB\\Driver\\Manager ` object.
If you select the Collection from a :phpclass:`Client ` or
:phpclass:`Database ` object, the Collection inherits its
options from that object.
.. todo: add an example
See Also
--------
- :phpmethod:`MongoDB\\Collection::withOptions()`
- :phpmethod:`MongoDB\\Client::selectCollection()`
- :phpmethod:`MongoDB\\Database::selectCollection()`
- :phpmethod:`MongoDB\\Database::__get()`
docs/reference/method/MongoDBClient-getWriteConcern.txt 0000666 00000002303 13645314021 0017200 0 ustar 00 ==================================
MongoDB\\Client::getWriteConcern()
==================================
.. versionadded:: 1.2
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Client::getWriteConcern()
Returns the write concern for this client.
.. code-block:: php
function getWriteConcern(): MongoDB\Driver\WriteConcern
Return Values
-------------
A :php:`MongoDB\\Driver\\WriteConcern `
object.
Example
-------
.. code-block:: php
true,
]);
var_dump($client->getWriteConcern());
The output would then resemble::
object(MongoDB\Driver\WriteConcern)#4 (1) {
["j"]=>
bool(true)
}
See Also
--------
- :manual:`Write Concern ` in the MongoDB manual
- :php:`MongoDB\\Driver\\WriteConcern::isDefault() `
- :phpmethod:`MongoDB\\Collection::getWriteConcern()`
- :phpmethod:`MongoDB\\Database::getWriteConcern()`
- :phpmethod:`MongoDB\\GridFS\\Bucket::getWriteConcern()`
docs/reference/method/MongoDBModelIndexInfo-is2dSphere.txt 0000666 00000002333 13645314021 0017537 0 ustar 00 =======================================
MongoDB\\Model\\IndexInfo::is2dSphere()
=======================================
.. versionadded:: 1.4
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Model\\IndexInfo::is2dSphere()
Return whether the index is a :manual:`2dsphere `
index.
.. code-block:: php
function is2dSphere(): boolean
Return Values
-------------
A boolean indicating whether the index is a 2dsphere index.
Examples
--------
.. code-block:: php
selectCollection('test', 'places');
$collection->createIndex(['pos' => '2dsphere']);
foreach ($collection->listIndexes() as $index) {
if ($index->is2dSphere()) {
printf("%s has 2dsphereIndexVersion: %d\n", $index->getName(), $index['2dsphereIndexVersion']);
}
}
The output would then resemble::
pos_2dsphere has 2dsphereIndexVersion: 3
See Also
--------
- :phpmethod:`MongoDB\\Collection::createIndex()`
- :phpmethod:`MongoDB\\Collection::listIndexes()`
- :manual:`2dsphere Indexes ` reference in the MongoDB
manual
docs/reference/method/MongoDBClient-listDatabases.txt 0000666 00000003531 13645314021 0016665 0 ustar 00 ================================
MongoDB\\Client::listDatabases()
================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Client::listDatabases()
Returns information for all databases on the server.
.. code-block:: php
function listDatabases(array $options = []): MongoDB\Model\DatabaseInfoIterator
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBClient-method-listDatabases-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBClient-method-listDatabases-option.rst
Return Values
-------------
A traversable :phpclass:`MongoDB\\Model\\DatabaseInfoIterator`, which contains
a :phpclass:`MongoDB\\Model\\DatabaseInfo` object for each database on the
server.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-unexpectedvalueexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Example
-------
The following example lists all databases on the server:
.. code-block:: php
listDatabases() as $databaseInfo) {
var_dump($databaseInfo);
}
The output would then resemble::
object(MongoDB\Model\DatabaseInfo)#4 (3) {
["name"]=>
string(5) "local"
["sizeOnDisk"]=>
float(65536)
["empty"]=>
bool(false)
}
object(MongoDB\Model\DatabaseInfo)#7 (3) {
["name"]=>
string(4) "test"
["sizeOnDisk"]=>
float(32768)
["empty"]=>
bool(false)
}
See Also
--------
- :manual:`listDatabases ` command reference
in the MongoDB manual
docs/reference/method/MongoDBCollection-updateOne.txt 0000666 00000004526 13645314021 0016710 0 ustar 00 ================================
MongoDB\\Collection::updateOne()
================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::updateOne()
Update at most one document that matches the filter criteria. If multiple
documents match the filter criteria, only the :term:`first `
matching document will be updated.
.. code-block:: php
function updateOne($filter, $update, array $options = []): MongoDB\UpdateResult
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-updateOne-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-updateOne-option.rst
Return Values
-------------
A :phpclass:`MongoDB\\UpdateResult` object, which encapsulates a
:php:`MongoDB\\Driver\\WriteResult ` object.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-unsupportedexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-bulkwriteexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Behavior
--------
.. include:: /includes/extracts/note-bson-comparison.rst
.. include:: /includes/extracts/bulkwriteexception-result.rst
Examples
--------
The following example updates one document with the ``restaurant_id`` of
``"40356151"`` by setting the ``name`` field to ``"Brunos on Astoria"``:
.. code-block:: php
$collection = (new MongoDB\Client)->test->restaurants;
$updateResult = $collection->updateOne(
[ 'restaurant_id' => '40356151' ],
[ '$set' => [ 'name' => 'Brunos on Astoria' ]]
);
printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());
The output would then resemble::
Matched 1 document(s)
Modified 1 document(s)
See Also
--------
- :phpmethod:`MongoDB\\Collection::replaceOne()`
- :phpmethod:`MongoDB\\Collection::updateMany()`
- :phpmethod:`MongoDB\\Collection::bulkWrite()`
- :doc:`/tutorial/crud`
- :manual:`update ` command reference in the MongoDB
manual
docs/reference/method/MongoDBGridFSBucket-openDownloadStreamByName.txt 0000666 00000003240 13645314021 0022036 0 ustar 00 ===================================================
MongoDB\\GridFS\\Bucket::openDownloadStreamByName()
===================================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\GridFS\\Bucket::openDownloadStreamByName()
Selects a GridFS file by its ``filename`` and opens it as a readable stream.
.. code-block:: php
function openDownloadStreamByName($filename, array $options = []): resource
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBGridFSBucket-method-openDownloadStreamByName-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBGridFSBucket-method-openDownloadStreamByName-option.rst
Return Values
-------------
A readable stream resource.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-gridfs-filenotfoundexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Examples
--------
.. code-block:: php
test->selectGridFSBucket();
$stream = fopen('php://temp', 'w+b');
fwrite($stream, "foobar");
rewind($stream);
$bucket->uploadFromStream('filename', $stream);
var_dump(stream_get_contents($bucket->openDownloadStreamByName('filename')));
The output would then resemble::
string(6) "foobar"
See Also
--------
- :phpmethod:`MongoDB\\GridFS\\Bucket::downloadToStream()`
- :phpmethod:`MongoDB\\GridFS\\Bucket::downloadToStreamByName()`
- :phpmethod:`MongoDB\\GridFS\\Bucket::openDownloadStream()`
docs/reference/method/MongoDBDatabase-dropCollection.txt 0000666 00000003420 13645314021 0017345 0 ustar 00 ===================================
MongoDB\\Database::dropCollection()
===================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Database::dropCollection()
Drop a collection within the current database.
.. code-block:: php
function dropCollection($collectionName, array $options = []): array|object
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBDatabase-method-dropCollection-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBDatabase-method-dropCollection-option.rst
Return Values
-------------
An array or object with the result document of the :manual:`drop
` command. The return type will depend on the
``typeMap`` option.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-unsupportedexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Example
-------
The following example drops the ``users`` collection in the ``test`` database:
.. code-block:: php
test;
$result = $db->dropCollection('users');
var_dump($result);
The output would then resemble::
object(MongoDB\Model\BSONDocument)#8 (1) {
["storage":"ArrayObject":private]=>
array(3) {
["ns"]=>
string(10) "test.users"
["nIndexesWas"]=>
int(1)
["ok"]=>
float(1)
}
}
See Also
--------
- :phpmethod:`MongoDB\\Collection::drop()`
- :manual:`drop ` command reference in the MongoDB
manual
docs/reference/method/MongoDBCollection-insertOne.txt 0000666 00000004105 13645314021 0016723 0 ustar 00 ================================
MongoDB\\Collection::insertOne()
================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::insertOne()
Insert one document.
.. code-block:: php
function insertOne($document, array $options = []): MongoDB\InsertOneResult
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-insertOne-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-insertOne-option.rst
Return Values
-------------
A :phpclass:`MongoDB\\InsertOneResult` object, which encapsulates a
:php:`MongoDB\\Driver\\WriteResult ` object.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-bulkwriteexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Behavior
--------
.. include:: /includes/extracts/bulkwriteexception-result.rst
Example
-------
.. start-crud-include
The following operation inserts a document into the ``users`` collection in the
``test`` database:
.. code-block:: php
test->users;
$insertOneResult = $collection->insertOne([
'username' => 'admin',
'email' => 'admin@example.com',
'name' => 'Admin User',
]);
printf("Inserted %d document(s)\n", $insertOneResult->getInsertedCount());
var_dump($insertOneResult->getInsertedId());
The output would then resemble::
Inserted 1 document(s)
object(MongoDB\BSON\ObjectId)#11 (1) {
["oid"]=>
string(24) "579a25921f417dd1e5518141"
}
.. end-crud-include
See Also
--------
- :phpmethod:`MongoDB\\Collection::insertMany()`
- :phpmethod:`MongoDB\\Collection::bulkWrite()`
- :doc:`/tutorial/crud`
- :manual:`insert ` command reference in the MongoDB
manual
docs/reference/method/MongoDBDatabase-listCollections.txt 0000666 00000005150 13645314021 0017541 0 ustar 00 ====================================
MongoDB\\Database::listCollections()
====================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Database::listCollections()
Returns information for all collections in this database.
.. code-block:: php
function listCollections(array $options = []): MongoDB\Model\CollectionInfoIterator
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBDatabase-method-listCollections-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBDatabase-method-listCollections-option.rst
Return Values
-------------
A traversable :phpclass:`MongoDB\\Model\\CollectionInfoIterator`, which contains
a :phpclass:`MongoDB\\Model\\CollectionInfo` object for each collection in the
database.
Example
-------
The following example lists all of the collections in the ``test`` database:
.. code-block:: php
test;
foreach ($database->listCollections() as $collectionInfo) {
var_dump($collectionInfo);
}
The output would then resemble::
object(MongoDB\Model\CollectionInfo)#3 (2) {
["name"]=>
string(11) "restaurants"
["options"]=>
array(0) {
}
}
object(MongoDB\Model\CollectionInfo)#3 (2) {
["name"]=>
string(5) "users"
["options"]=>
array(0) {
}
}
object(MongoDB\Model\CollectionInfo)#3 (2) {
["name"]=>
string(6) "restos"
["options"]=>
array(0) {
}
}
The following example lists all collections whose name starts with ``"rest"``
in the ``test`` database:
.. code-block:: php
test;
$collections = $database->listCollections([
'filter' => [
'name' => new MongoDB\BSON\Regex('^rest.*'),
],
]);
foreach ($collections as $collectionInfo) {
var_dump($collectionInfo);
}
The output would then resemble::
object(MongoDB\Model\CollectionInfo)#3 (2) {
["name"]=>
string(11) "restaurants"
["options"]=>
array(0) {
}
}
object(MongoDB\Model\CollectionInfo)#3 (2) {
["name"]=>
string(6) "restos"
["options"]=>
array(0) {
}
}
See Also
--------
- :manual:`listCollections `_
specification
docs/reference/method/MongoDBGridFSBucket-downloadToStream.txt 0000666 00000003045 13645314021 0020426 0 ustar 00 ===========================================
MongoDB\\GridFS\\Bucket::downloadToStream()
===========================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\GridFS\\Bucket::downloadToStream()
Selects a GridFS file by its ``_id`` and copies its contents to a writable
stream.
.. code-block:: php
function downloadToStream($id, $destination): void
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBGridFSBucket-method-downloadToStream-param.rst
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-gridfs-filenotfoundexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Examples
--------
.. code-block:: php
test->selectGridFSBucket();
$stream = fopen('php://temp', 'w+b');
fwrite($stream, "foobar");
rewind($stream);
$id = $bucket->uploadFromStream('filename', $stream);
$destination = fopen('php://temp', 'w+b');
$bucket->downloadToStream($id, $destination);
var_dump(stream_get_contents($destination, -1, 0));
The output would then resemble::
string(6) "foobar"
See Also
--------
- :phpmethod:`MongoDB\\GridFS\\Bucket::downloadToStreamByName()`
- :phpmethod:`MongoDB\\GridFS\\Bucket::openDownloadStream()`
- :phpmethod:`MongoDB\\GridFS\\Bucket::openDownloadStreamByName()`
docs/reference/method/MongoDBCollection-find.txt 0000666 00000007724 13645314021 0015707 0 ustar 00 ===========================
MongoDB\\Collection::find()
===========================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::find()
Finds documents matching the query.
.. code-block:: php
function find($filter = [], array $options = []): MongoDB\Driver\Cursor
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-find-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-find-option.rst
Return Values
-------------
A :php:`MongoDB\\Driver\\Cursor ` object.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-unsupportedexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Behavior
--------
.. include:: /includes/extracts/note-bson-comparison.rst
Examples
--------
The following example finds restaurants based on the ``cuisine`` and ``borough``
fields and uses a :manual:`projection
` to limit the fields that are
returned. It also limits the results to 5 documents.
.. code-block:: php
$collection = (new MongoDB\Client)->test->restaurants;
$cursor = $collection->find(
[
'cuisine' => 'Italian',
'borough' => 'Manhattan',
],
[
'limit' => 5,
'projection' => [
'name' => 1,
'borough' => 1,
'cuisine' => 1,
],
]
);
foreach ($cursor as $restaurant) {
var_dump($restaurant);
};
The output would then resemble::
object(MongoDB\Model\BSONDocument)#10 (1) {
["storage":"ArrayObject":private]=>
array(4) {
["_id"]=>
object(MongoDB\BSON\ObjectId)#8 (1) {
["oid"]=>
string(24) "576023c6b02fa9281da3f983"
}
["borough"]=>
string(9) "Manhattan"
["cuisine"]=>
string(7) "Italian"
["name"]=>
string(23) "Isle Of Capri Resturant"
}
}
object(MongoDB\Model\BSONDocument)#13 (1) {
["storage":"ArrayObject":private]=>
array(4) {
["_id"]=>
object(MongoDB\BSON\ObjectId)#12 (1) {
["oid"]=>
string(24) "576023c6b02fa9281da3f98d"
}
["borough"]=>
string(9) "Manhattan"
["cuisine"]=>
string(7) "Italian"
["name"]=>
string(18) "Marchis Restaurant"
}
}
object(MongoDB\Model\BSONDocument)#8 (1) {
["storage":"ArrayObject":private]=>
array(4) {
["_id"]=>
object(MongoDB\BSON\ObjectId)#10 (1) {
["oid"]=>
string(24) "576023c6b02fa9281da3f99b"
}
["borough"]=>
string(9) "Manhattan"
["cuisine"]=>
string(7) "Italian"
["name"]=>
string(19) "Forlinis Restaurant"
}
}
object(MongoDB\Model\BSONDocument)#12 (1) {
["storage":"ArrayObject":private]=>
array(4) {
["_id"]=>
object(MongoDB\BSON\ObjectId)#13 (1) {
["oid"]=>
string(24) "576023c6b02fa9281da3f9a8"
}
["borough"]=>
string(9) "Manhattan"
["cuisine"]=>
string(7) "Italian"
["name"]=>
string(22) "Angelo Of Mulberry St."
}
}
object(MongoDB\Model\BSONDocument)#10 (1) {
["storage":"ArrayObject":private]=>
array(4) {
["_id"]=>
object(MongoDB\BSON\ObjectId)#8 (1) {
["oid"]=>
string(24) "576023c6b02fa9281da3f9b4"
}
["borough"]=>
string(9) "Manhattan"
["cuisine"]=>
string(7) "Italian"
["name"]=>
string(16) "V & T Restaurant"
}
}
See Also
--------
- :phpmethod:`MongoDB\\Collection::findOne()`
- :manual:`find ` command reference in the MongoDB
manual
docs/reference/method/MongoDBMapReduceResult-getCounts.txt 0000666 00000002476 13645314021 0017712 0 ustar 00 =====================================
MongoDB\\MapReduceResult::getCounts()
=====================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\MapReduceResult::getCounts()
Returns count statistics for the map-reduce operation.
.. code-block:: php
function getCounts(): array
Return Values
-------------
An array of count statistics for the map-reduce operation.
Examples
--------
This example reports the count statistics for a map-reduce operation.
.. code-block:: php
test->zips;
$map = new MongoDB\BSON\Javascript('function() { emit(this.state, this.pop); }');
$reduce = new MongoDB\BSON\Javascript('function(key, values) { return Array.sum(values) }');
$out = ['inline' => 1];
$result = $collection->mapReduce($map, $reduce, $out);
var_dump($result->getCounts());
The output would then resemble::
array(4) {
["input"]=>
int(29353)
["emit"]=>
int(29353)
["reduce"]=>
int(180)
["output"]=>
int(51)
}
See Also
--------
- :phpmethod:`MongoDB\\Collection::mapReduce()`
- :manual:`mapReduce ` command reference in the
MongoDB manual
docs/reference/method/MongoDBBulkWriteResult-getModifiedCount.txt 0000666 00000002511 13645314021 0021221 0 ustar 00 ============================================
MongoDB\\BulkWriteResult::getModifiedCount()
============================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\BulkWriteResult::getModifiedCount()
Return the total number of documents that were modified by all update and
replace operations in the bulk write.
.. code-block:: php
function getModifiedCount(): integer|null
This method should only be called if the write was acknowledged.
.. note::
If an update/replace operation results in no change to the document
(e.g. setting the value of a field to its current value), the modified
count may be less than the value returned by :phpmethod:`getMatchedCount()
`.
Return Values
-------------
The total number of documents that were modified by all update and replace
operations in the bulk write.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-badmethodcallexception-write-result.rst
See Also
--------
- :phpmethod:`MongoDB\\BulkWriteResult::getMatchedCount()`
- :php:`MongoDB\\Driver\\WriteResult::getModifiedCount()
`
docs/reference/method/MongoDBCollection-watch.txt 0000666 00000007102 13645314021 0016063 0 ustar 00 ============================
MongoDB\\Collection::watch()
============================
.. versionadded:: 1.3
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::watch()
Executes a :manual:`change stream ` operation on the
collection. The change stream can be watched for collection-level changes.
.. code-block:: php
function watch(array $pipeline = [], array $options = []): MongoDB\ChangeStream
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-watch-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-watch-option.rst
Return Values
-------------
A :phpclass:`MongoDB\\ChangeStream` object, which allows for iteration of
events in the change stream via the :php:`Iterator ` interface.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-unexpectedvalueexception.rst
.. include:: /includes/extracts/error-unsupportedexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Examples
--------
This example reports events while iterating a change stream.
.. code-block:: php
test->inventory;
$changeStream = $collection->watch();
for ($changeStream->rewind(); true; $changeStream->next()) {
if ( ! $changeStream->valid()) {
continue;
}
$event = $changeStream->current();
if ($event['operationType'] === 'invalidate') {
break;
}
$ns = sprintf('%s.%s', $event['ns']['db'], $event['ns']['coll']);
$id = json_encode($event['documentKey']['_id']);
switch ($event['operationType']) {
case 'delete':
printf("Deleted document in %s with _id: %s\n\n", $ns, $id);
break;
case 'insert':
printf("Inserted new document in %s\n", $ns);
echo json_encode($event['fullDocument']), "\n\n";
break;
case 'replace':
printf("Replaced new document in %s with _id: %s\n", $ns, $id);
echo json_encode($event['fullDocument']), "\n\n";
break;
case 'update':
printf("Updated document in %s with _id: %s\n", $ns, $id);
echo json_encode($event['updateDescription']), "\n\n";
break;
}
}
Assuming that a document was inserted, updated, and deleted while the above
script was iterating the change stream, the output would then resemble:
.. code-block:: none
Inserted new document in test.user
{"_id":{"$oid":"5b329c4874083047cc05e60a"},"username":"bob"}
Inserted new document in test.products
{"_id":{"$oid":"5b329c4d74083047cc05e60b"},"name":"Widget","quantity":5}
Updated document in test.user with _id: {"$oid":"5b329a4f74083047cc05e603"}
{"updatedFields":{"username":"robert"},"removedFields":[]}
See Also
--------
- :phpmethod:`MongoDB\\Client::watch()`
- :phpmethod:`MongoDB\\Database::watch()`
- :manual:`Aggregation Pipeline ` documentation in
the MongoDB Manual
- :manual:`Change Streams ` documentation in the MongoDB manual
- :manual:`Change Events ` documentation in the
MongoDB manual
docs/reference/method/MongoDBCollection-createIndex.txt 0000666 00000005263 13645314021 0017216 0 ustar 00 ==================================
MongoDB\\Collection::createIndex()
==================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::createIndex()
Create an index for the collection.
.. code-block:: php
function createIndex($key, array $options = []): string
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-createIndex-param.rst
The ``$options`` parameter accepts all index options that your MongoDB
version supports. MongoDB includes the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-createIndex-option.rst
For a full list of the supported index creation options, refer to the
:manual:`createIndexes ` command reference
in the MongoDB manual.
Return Values
-------------
The name of the created index as a string.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-unsupportedexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Examples
--------
Create a Compound Index
~~~~~~~~~~~~~~~~~~~~~~~
The following example creates a :manual:`compound index `
on the ``borough`` and ``cuisine`` fields in the ``restaurants`` collection in
the ``test`` database.
.. code-block:: php
selectCollection('test', 'restaurants');
$indexName = $collection->createIndex(['borough' => 1, 'cuisine' => 1]);
var_dump($indexName);
The output would then resemble::
string(19) "borough_1_cuisine_1"
Create a Partial Index
~~~~~~~~~~~~~~~~~~~~~~
The following example adds a :manual:`partial index ` on
the ``borough`` field in the ``restaurants`` collection in the ``test``
database. The partial index indexes only documents where the ``borough`` field
exists.
.. code-block:: php
selectCollection('test, 'restaurants');
$indexName = $collection->createIndex(
['borough' => 1],
[
'partialFilterExpression' => [
'borough' => ['$exists' => true],
],
]
);
var_dump($indexName);
The output would then resemble::
string(9) "borough_1"
See Also
--------
- :phpmethod:`MongoDB\\Collection::createIndexes()`
- :doc:`/tutorial/indexes`
- :manual:`createIndexes ` command reference
in the MongoDB manual
- :manual:`Index ` documentation in the MongoDB Manual
docs/reference/method/MongoDBGridFSBucket-getFilesCollection.txt 0000666 00000001560 13645314021 0020716 0 ustar 00 =============================================
MongoDB\\GridFS\\Bucket::getFilesCollection()
=============================================
.. versionadded:: 1.2
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\GridFS\\Bucket::getFilesCollection()
Returns the files collection used by the bucket.
.. code-block:: php
function getFilesCollection(): MongoDB\Collection
Return Values
-------------
A :phpclass:`MongoDB\\Collection` object for the files collection.
Examples
--------
.. code-block:: php
test->selectGridFSBucket();
$filesCollection = $bucket->getFilesCollection();
var_dump($filesCollection->getCollectionName());
The output would then resemble::
string(8) "fs.files"
docs/reference/method/MongoDBCollection-dropIndexes.txt 0000666 00000003732 13645314021 0017246 0 ustar 00 ==================================
MongoDB\\Collection::dropIndexes()
==================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::dropIndexes()
Drop all indexes in the collection, except for the required index on the
``_id`` field.
.. code-block:: php
function dropIndexes(array $options = []): array|object
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-dropIndex-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-dropIndex-option.rst
Return Values
-------------
An array or object with the result document of the :manual:`dropIndexes
` command. The return type will depend on the
``typeMap`` option.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-unsupportedexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Example
-------
The following drops all indexes from the ``restaurants`` collection in the
``test`` database:
.. code-block:: php
test->restaurants;
$result = $collection->dropIndexes();
var_dump($result);
The output would then resemble::
object(MongoDB\Model\BSONDocument)#9 (1) {
["storage":"ArrayObject":private]=>
array(3) {
["nIndexesWas"]=>
int(3)
["msg"]=>
string(38) "non-_id indexes dropped for collection"
["ok"]=>
float(1)
}
}
See Also
--------
- :phpmethod:`MongoDB\\Collection::dropIndex()`
- :doc:`/tutorial/indexes`
- :manual:`dropIndexes ` command reference in
the MongoDB manual
- :manual:`Index documentation ` in the MongoDB manual
docs/reference/method/MongoDBCollection-listIndexes.txt 0000666 00000004677 13645314021 0017266 0 ustar 00 ==================================
MongoDB\\Collection::listIndexes()
==================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::listIndexes()
Returns information for all indexes for this collection.
.. code-block:: php
function listIndexes(array $options = []): MongoDB\Model\IndexInfoIterator
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-listIndexes-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-listIndexes-option.rst
Return Values
-------------
A traversable :phpclass:`MongoDB\\Model\\IndexInfoIterator`, which contains a
:phpclass:`MongoDB\\Model\\IndexInfo` object for each index for the collection.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Example
-------
The following example lists all of the indexes for the ``restaurants``
collection in the ``test`` database:
.. code-block:: php
test->restaurants;
foreach ($collection->listIndexes() as $index) {
var_dump($index);
}
The output would then resemble::
object(MongoDB\Model\IndexInfo)#8 (4) {
["v"]=>
int(1)
["key"]=>
array(1) {
["_id"]=>
int(1)
}
["name"]=>
string(4) "_id_"
["ns"]=>
string(16) "test.restaurants"
}
object(MongoDB\Model\IndexInfo)#12 (4) {
["v"]=>
int(1)
["key"]=>
array(1) {
["cuisine"]=>
float(-1)
}
["name"]=>
string(10) "cuisine_-1"
["ns"]=>
string(16) "test.restaurants"
}
object(MongoDB\Model\IndexInfo)#8 (4) {
["v"]=>
int(1)
["key"]=>
array(1) {
["borough"]=>
float(1)
}
["name"]=>
string(9) "borough_1"
["ns"]=>
string(16) "test.restaurants"
}
See Also
--------
- :doc:`/tutorial/indexes`
- :manual:`listIndexes ` command reference in
the MongoDB manual
- :manual:`Index documentation ` in the MongoDB manual
- `Enumerating Collections
`_
specification
docs/reference/method/MongoDBGridFSBucket-delete.txt 0000666 00000002147 13645314021 0016404 0 ustar 00 =================================
MongoDB\\GridFS\\Bucket::delete()
=================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\GridFS\\Bucket::delete()
Delete a file and its chunks from the GridFS bucket.
.. code-block:: php
function delete($id): void
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBGridFSBucket-method-delete-param.rst
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-gridfs-filenotfoundexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Behavior
--------
If the files collection document is not found, this method will still attempt to
delete orphaned chunks.
Examples
--------
.. code-block:: php
test->selectGridFSBucket();
$stream = fopen('php://temp', 'w+b');
fwrite($stream, "foobar");
rewind($stream);
$id = $bucket->uploadFromStream('filename', $stream);
$bucket->delete($id);
docs/reference/method/MongoDBCollection-findOne.txt 0000666 00000006171 13645314021 0016344 0 ustar 00 ==============================
MongoDB\\Collection::findOne()
==============================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::findOne()
Finds a single document matching the query.
.. code-block:: php
function findOne($filter = [], array $options = []): array|object|null
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-findOne-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-findOne-option.rst
Return Values
-------------
An array or object for the :term:`first document ` that matched
the query, or ``null`` if no document matched the query. The return type will
depend on the ``typeMap`` option.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-unsupportedexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Behavior
--------
.. include:: /includes/extracts/note-bson-comparison.rst
Examples
--------
Matching BSON Types in Query Criteria
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In the following example, documents in the ``restaurants`` collection use an
:manual:`ObjectId ` for their identifier (the default)
and documents in the ``zips`` collection use a string. Since ObjectId is a
special BSON type, the query criteria for selecting a restaurant must use the
:php:`MongoDB\\BSON\\ObjectId ` class.
.. code-block:: php
$database = (new MongoDB\Client)->test;
$zip = $database->zips->findOne(['_id' => '10036']);
$restaurant = $database->restaurants->findOne([
'_id' => new MongoDB\BSON\ObjectId('594d5ef280a846852a4b3f70'),
]);
Projecting Fields
~~~~~~~~~~~~~~~~~
The following example finds a restaurant based on the ``cuisine`` and
``borough`` fields and uses a :manual:`projection
` to limit the fields that are
returned.
.. code-block:: php
$collection = (new MongoDB\Client)->test->restaurants;
$restaurant = $collection->findOne(
[
'cuisine' => 'Italian',
'borough' => 'Manhattan',
],
[
'projection' => [
'name' => 1,
'borough' => 1,
'cuisine' => 1,
],
]
);
var_dump($restaurant);
The output would then resemble::
object(MongoDB\Model\BSONDocument)#10 (1) {
["storage":"ArrayObject":private]=>
array(4) {
["_id"]=>
object(MongoDB\BSON\ObjectId)#8 (1) {
["oid"]=>
string(24) "576023c6b02fa9281da3f983"
}
["borough"]=>
string(9) "Manhattan"
["cuisine"]=>
string(7) "Italian"
["name"]=>
string(23) "Isle Of Capri Resturant"
}
}
See Also
--------
- :phpmethod:`MongoDB\\Collection::find()`
- :manual:`find ` command reference in the MongoDB
manual
docs/reference/method/MongoDBModelIndexInfo-isGeoHaystack.txt 0000666 00000002407 13645314021 0020267 0 ustar 00 ==========================================
MongoDB\\Model\\IndexInfo::isGeoHaystack()
==========================================
.. versionadded:: 1.4
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Model\\IndexInfo::isGeoHaystack()
Return whether the index is a :manual:`geoHaystack
` index.
.. code-block:: php
function isGeoHaystack(): boolean
Return Values
-------------
A boolean indicating whether the index is a geoHaystack index.
Examples
--------
.. code-block:: php
selectCollection('test', 'places');
$collection->createIndex(['pos' => 'geoHaystack', 'x' => 1], ['bucketSize' => 5]);
foreach ($collection->listIndexes() as $index) {
if ($index->isGeoHaystack()) {
printf("%s has bucketSize: %d\n", $index->getName(), $index['bucketSize']);
}
}
The output would then resemble::
pos_geoHaystack_x_1 has bucketSize: 5
See Also
--------
- :phpmethod:`MongoDB\\Collection::createIndex()`
- :phpmethod:`MongoDB\\Collection::listIndexes()`
- :manual:`geoHaystack Indexes ` reference in the MongoDB
manual
docs/reference/method/MongoDBBulkWriteResult-getUpsertedIds.txt 0000666 00000002407 13645314021 0020727 0 ustar 00 ==========================================
MongoDB\\BulkWriteResult::getUpsertedIds()
==========================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\BulkWriteResult::getUpsertedIds()
Return a map of IDs (i.e. ``_id`` field values) for documents that were
upserted by all update and replace operations in the bulk write.
.. code-block:: php
function getUpsertedIds(): array
Return Values
-------------
A map of IDs (i.e. ``_id`` field values) for documents that were upserted by all
update and replace operations in the bulk write.
The index of each ID in the map corresponds to each document's position in the
bulk operation. If a document had an ID prior to upserting (i.e. the server did
not generate an ID), the index will contain its ``_id`` field value. Any
server-generated ID will be a :php:`MongoDB\\BSON\\ObjectId
` instance.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-badmethodcallexception-write-result.rst
See Also
--------
- :php:`MongoDB\\Driver\\WriteResult::getUpsertedIds()
`
docs/reference/method/MongoDBCollection-count.txt 0000666 00000004206 13645314021 0016107 0 ustar 00 ============================
MongoDB\\Collection::count()
============================
.. deprecated:: 1.4
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::count()
Count the number of documents that match the filter criteria.
.. code-block:: php
function count($filter = [], array $options = []): integer
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-count-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-count-option.rst
Return Values
-------------
The number of documents matching the filter criteria.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-unexpectedvalueexception.rst
.. include:: /includes/extracts/error-unsupportedexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Behavior
--------
This method is deprecated and cannot be executed within a transaction. It has
always been implemented using the :manual:`count `
command. The behavior of the ``count`` command differs depending on the options
passed to it and may or may not provide an accurate count. When no query filter
is provided, the ``count`` command provides an estimate using collection
metadata. Even when provided with a query filter the ``count`` command can
return inaccurate results with a sharded cluster if orphaned documents exist or
if a chunk migration is in progress. The
:phpmethod:`MongoDB\\Collection::countDocuments()` method avoids these sharded
cluster problems entirely when used with MongoDB 3.6+, and when a primary read
preference with older sharded clusters.
.. include:: /includes/extracts/note-bson-comparison.rst
See Also
--------
- :manual:`count ` command reference in the MongoDB
manual
- :phpmethod:`MongoDB\\Collection::countDocuments()`
- :phpmethod:`MongoDB\\Collection::estimatedDocumentCount()`
docs/reference/method/MongoDBCollection-withOptions.txt 0000666 00000002536 13645314021 0017312 0 ustar 00 ==================================
MongoDB\\Collection::withOptions()
==================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::withOptions()
Returns a clone of the Collection object, but with different options.
.. code-block:: php
function withOptions(array $options = []): MongoDB\Collection
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-withOptions-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-withOptions-option.rst
Return Values
-------------
A :phpclass:`MongoDB\\Collection` object.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-invalidargumentexception.rst
Example
-------
The following example clones an existing Collection object with a new read
preference:
.. code-block:: php
selectCollection('test', 'restaurants');
$newCollection = $sourceCollection->withOptions([
'readPreference' => new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY),
]);
See Also
--------
- :phpmethod:`MongoDB\\Collection::__construct()`
docs/reference/method/MongoDBDeleteResult-isAcknowledged.txt 0000666 00000001334 13645314021 0020207 0 ustar 00 =======================================
MongoDB\\DeleteResult::isAcknowledged()
=======================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\DeleteResult::isAcknowledged()
Return whether the write was acknowledged.
.. code-block:: php
function isAcknowledged(): boolean
Return Values
-------------
A boolean indicating whether the write was acknowledged.
See Also
--------
- :php:`MongoDB\\Driver\\WriteResult::isAcknowledged()
`
- :manual:`Write Concern ` in the MongoDB manual
docs/reference/method/MongoDBBulkWriteResult-getInsertedCount.txt 0000666 00000001704 13645314021 0021261 0 ustar 00 ============================================
MongoDB\\BulkWriteResult::getInsertedCount()
============================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\BulkWriteResult::getInsertedCount()
Return the total number of documents that were inserted by all insert
operations in the bulk write.
.. code-block:: php
function getInsertedCount(): integer
This method should only be called if the write was acknowledged.
Return Values
-------------
The total number of documents that were inserted by all insert operations in the
bulk write.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-badmethodcallexception-write-result.rst
See Also
--------
- :php:`MongoDB\\Driver\\WriteResult::getInsertedCount()
`
docs/reference/method/MongoDBCollection-getNamespace.txt 0000666 00000001722 13645314021 0017353 0 ustar 00 ===================================
MongoDB\\Collection::getNamespace()
===================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::getNamespace()
Returns the :term:`namespace` of the collection. A namespace is the canonical
name of an index or collection in MongoDB.
.. code-block:: php
function getNamespace(): string
Return Values
-------------
The namespace of this collection as a string.
Example
-------
The following returns the namespace of the ``zips`` collection in the ``test``
database.
.. code-block:: php
test->zips;
echo $collection->getNamespace();
The output would then resemble::
test.zips
See Also
--------
- :phpmethod:`MongoDB\\Collection::getCollectionName()`
- :phpmethod:`MongoDB\\Collection::getDatabaseName()`
docs/reference/method/MongoDBBulkWriteResult-isAcknowledged.txt 0000666 00000001350 13645314021 0020713 0 ustar 00 ==========================================
MongoDB\\BulkWriteResult::isAcknowledged()
==========================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\BulkWriteResult::isAcknowledged()
Return whether the write was acknowledged.
.. code-block:: php
function isAcknowledged(): boolean
Return Values
-------------
A boolean indicating whether the write was acknowledged.
See Also
--------
- :php:`MongoDB\\Driver\\WriteResult::isAcknowledged()
`
- :manual:`Write Concern ` in the MongoDB manual
docs/reference/method/MongoDBDatabase-selectGridFSBucket.txt 0000666 00000003442 13645314021 0020045 0 ustar 00 =======================================
MongoDB\\Database::selectGridFSBucket()
=======================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Database::selectGridFSBucket()
Selects a GridFS bucket within the database.
.. code-block:: php
function selectGridFSBucket(array $options = []): MongoDB\GridFS\Bucket
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBDatabase-method-selectGridFSBucket-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBDatabase-method-selectGridFSBucket-option.rst
Return Values
-------------
A :phpclass:`MongoDB\\GridFS\\Bucket` object.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-invalidargumentexception.rst
Behavior
--------
The selected bucket inherits options such as read preference and type
mapping from the :phpclass:`Database ` object. Options may be
overridden via the ``$options`` parameter.
Example
-------
The following example selects the default ``fs.files`` bucket in the ``test``
database:
.. code-block:: php
test;
$bucket = $db->selectGridFSBucket();
The following example selects the custom ``images.files`` bucket in the ``test``
database with a custom read preference:
.. code-block:: php
test;
$imagesBucket = $db->selectGridFSBucket([
'bucketName' => 'images',
'readPreference' => new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY),
]);
See Also
--------
- :phpmethod:`MongoDB\\GridFS\\Bucket::__construct()`
docs/reference/method/MongoDBChangeStream-valid.txt 0000666 00000002126 13645314021 0016323 0 ustar 00 ==============================
MongoDB\\ChangeStream::valid()
==============================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\ChangeStream::valid()
Returns whether there is a current event in the change stream.
.. code-block:: php
function valid(): boolean
When manually iterating the change stream using
:php:`Iterator ` methods, this method should
be used to determine if :phpmethod:`MongoDB\\ChangeStream::current()` and
:phpmethod:`MongoDB\\ChangeStream::key()` can be called.
Return Values
-------------
A boolean indicating whether there is a current event in the change stream.
See Also
--------
- :phpmethod:`MongoDB\\Client::watch()`
- :phpmethod:`MongoDB\\Collection::watch()`
- :phpmethod:`MongoDB\\Database::watch()`
- :php:`Iterator::valid() `
- :ref:`Tailable Cursor Iteration `
- :manual:`Change Streams ` documentation in the MongoDB manual
docs/reference/method/MongoDBBulkWriteResult-getUpsertedCount.txt 0000666 00000001734 13645314021 0021302 0 ustar 00 ============================================
MongoDB\\BulkWriteResult::getUpsertedCount()
============================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\BulkWriteResult::getUpsertedCount()
Return the total number of documents that were upserted by all update and
replace operations in the bulk write.
.. code-block:: php
function getUpsertedCount(): integer
This method should only be called if the write was acknowledged.
Return Values
-------------
The total number of documents that were upserted by all update and replace
operations in the bulk write.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-badmethodcallexception-write-result.rst
See Also
--------
- :php:`MongoDB\\Driver\\WriteResult::getUpsertedCount()
`
docs/reference/method/MongoDBGridFSBucket-openUploadStream.txt 0000666 00000002725 13645314021 0020426 0 ustar 00 ===========================================
MongoDB\\GridFS\\Bucket::openUploadStream()
===========================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\GridFS\\Bucket::openUploadStream()
Opens a writable stream for a new GridFS file.
.. code-block:: php
function openUploadStream($filename, array $options = []): resource
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBGridFSBucket-method-openUploadStream-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBGridFSBucket-method-openUploadStream-option.rst
Return Values
-------------
A writable stream resource.
Behavior
--------
Chunk documents will be created as data is written to the writable stream. The
metadata document will be created when the writable stream is closed.
Examples
--------
.. code-block:: php
test->selectGridFSBucket();
$uploadStream = $bucket->openUploadStream('filename');
fwrite($uploadStream, 'foobar');
fclose($uploadStream);
$downloadStream = $bucket->openDownloadStreamByName('filename');
var_dump(stream_get_contents($downloadStream));
The output would then resemble::
string(6) "foobar"
See Also
--------
- :phpmethod:`MongoDB\\GridFS\\Bucket::uploadFromStream()`
docs/reference/method/MongoDBDatabase-getDatabaseName.txt 0000666 00000001302 13645314021 0017367 0 ustar 00 ====================================
MongoDB\\Database::getDatabaseName()
====================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Database::getDatabaseName()
Returns the name of this database.
.. code-block:: php
function getDatabaseName(): string
Return Values
-------------
The name of this database as a string.
Example
-------
The following example prints the name of a database object:
.. code-block:: php
test;
echo $db->getDatabaseName();
The output would then resemble::
test
docs/reference/method/MongoDBCollection-getReadConcern.txt 0000666 00000002450 13645314021 0017641 0 ustar 00 =====================================
MongoDB\\Collection::getReadConcern()
=====================================
.. versionadded:: 1.2
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::getReadConcern()
Returns the read concern for this collection.
.. code-block:: php
function getReadConcern(): MongoDB\Driver\ReadConcern
Return Values
-------------
A :php:`MongoDB\\Driver\\ReadConcern ` object.
Example
-------
.. code-block:: php
selectCollection('test', 'users', [
'readConcern' => new MongoDB\Driver\ReadConcern(MongoDB\Driver\ReadConcern::MAJORITY),
]);
var_dump($collection->getReadConcern());
The output would then resemble::
object(MongoDB\Driver\ReadConcern)#5 (1) {
["level"]=>
string(8) "majority"
}
See Also
--------
- :manual:`Read Concern ` in the MongoDB manual
- :php:`MongoDB\\Driver\\ReadConcern::isDefault() `
- :phpmethod:`MongoDB\\Client::getReadConcern()`
- :phpmethod:`MongoDB\\Database::getReadConcern()`
- :phpmethod:`MongoDB\\GridFS\\Bucket::getReadConcern()`
docs/reference/method/MongoDBGridFSBucket-getTypeMap.txt 0000666 00000002263 13645314021 0017220 0 ustar 00 =====================================
MongoDB\\GridFS\\Bucket::getTypeMap()
=====================================
.. versionadded:: 1.2
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\GridFS\\Bucket::getTypeMap()
Returns the type map for this GridFS bucket.
.. code-block:: php
function getTypeMap(): array
Return Values
-------------
A :ref:`type map ` array.
Example
-------
.. code-block:: php
selectDatabase('test');
$bucket = $database->selectGridFSBucket([
'typeMap' => [
'root' => 'array',
'document' => 'array',
'array' => 'array',
],
]);
var_dump($bucket->getTypeMap());
The output would then resemble::
array(3) {
["root"]=>
string(5) "array"
["document"]=>
string(5) "array"
["array"]=>
string(5) "array"
}
See Also
--------
- :doc:`/reference/bson`
- :phpmethod:`MongoDB\\Client::getTypeMap()`
- :phpmethod:`MongoDB\\Collection::getTypeMap()`
- :phpmethod:`MongoDB\\Database::getTypeMap()`
docs/reference/method/MongoDBModelCollectionInfo-getName.txt 0000666 00000001467 13645314021 0020142 0 ustar 00 =========================================
MongoDB\\Model\\CollectionInfo::getName()
=========================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Model\\CollectionInfo::getName()
Return the collection name.
.. code-block:: php
function getName(): string
Return Values
-------------
The collection name.
Examples
--------
.. code-block:: php
'foo']);
echo $info->getName();
The output would then resemble::
foo
See Also
--------
- :phpmethod:`MongoDB\\Collection::getCollectionName()`
- :manual:`listCollections ` command
reference in the MongoDB manual
docs/reference/method/MongoDBDatabase-drop.txt 0000666 00000003153 13645314021 0015334 0 ustar 00 =========================
MongoDB\\Database::drop()
=========================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Database::drop()
Drop the database.
.. code-block:: php
function drop(array $options = []): array|object
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBDatabase-method-drop-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBDatabase-method-drop-option.rst
Return Values
-------------
An array or object with the result document of the :manual:`dropDatabase
` command. The return type will depend on the
``typeMap`` option.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-unsupportedexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Example
-------
The following example drops the ``test`` database:
.. code-block:: php
test;
$result = $db->drop();
var_dump($result);
The output would then resemble::
object(MongoDB\Model\BSONDocument)#8 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["dropped"]=>
string(4) "test"
["ok"]=>
float(1)
}
}
See Also
--------
- :phpmethod:`MongoDB\\Client::dropDatabase()`
- :manual:`dropDatabase ` command reference in
the MongoDB manual
docs/reference/method/MongoDBCollection-createIndexes.txt 0000666 00000005534 13645314021 0017547 0 ustar 00 ====================================
MongoDB\\Collection::createIndexes()
====================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::createIndexes($indexes)
Create one or more indexes for the collection.
.. code-block:: php
function createIndexes(array $indexes, array $options = []): string[]
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-createIndexes-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-createIndexes-option.rst
Return Values
-------------
The names of the created indexes as an array of strings.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-unsupportedexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
``$indexes`` parameter
----------------------
The ``$indexes`` parameter is an array of index specification documents. Each
element in ``$indexes`` must itself be an array or object with a ``key`` field,
which corresponds to the ``$key`` parameter of :phpmethod:`createIndex()
`. The array or object may include other
fields that correspond to index options accepted by :phpmethod:`createIndex()
` (excluding ``writeConcern``).
For example, the following ``$indexes`` parameter creates two indexes. The first
is an ascending unique index on the ``username`` field and the second is a
2dsphere index on the ``loc`` field with a custom name::
[
[ 'key' => [ 'username' => 1 ], 'unique' => true ],
[ 'key' => [ 'loc' => '2dsphere' ], 'name' => 'geo_index' ],
]
Example
-------
The following example creates two indexes on the ``restaurants`` collection in
the ``test`` database. One index is a compound index on the ``borough`` and
``cuisine`` fields and the other is 2dsphere index on the ``loc`` field with a
custom name.
.. code-block:: php
selectCollection('test', 'restaurants');
$indexNames = $collection->createIndexes([
[ 'key' => [ 'borough' => 1, 'cuisine' => 1] ],
[ 'key' => [ 'loc' => '2dsphere'], 'name' => 'geo_index' ],
]);
var_dump($indexNames);
The output would then resemble::
array(2) {
[0]=>
string(19) "borough_1_cuisine_1"
[1]=>
string(9) "geo_index"
}
See Also
--------
- :phpmethod:`MongoDB\\Collection::createIndex()`
- :doc:`/tutorial/indexes`
- :manual:`createIndexes ` command reference
in the MongoDB manual
- :manual:`Index ` documentation in the MongoDB Manual
docs/reference/method/MongoDBCollection-countDocuments.txt 0000666 00000004746 13645314021 0020002 0 ustar 00 =====================================
MongoDB\\Collection::countDocuments()
=====================================
.. versionadded:: 1.4
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::countDocuments()
Count the number of documents that match the filter criteria.
.. code-block:: php
function countDocuments($filter = [], array $options = []): integer
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-countDocuments-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-countDocuments-option.rst
Return Values
-------------
The number of documents matching the filter criteria.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-unexpectedvalueexception.rst
.. include:: /includes/extracts/error-unsupportedexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Behavior
--------
Internally, this method uses the ``$group`` aggregation pipeline operator to
obtain the result. If a ``filter`` parameter is given, this is converted into
a ``$match`` pipeline operator. Optional ``$skip`` and ``$limit`` stages are
added between ``$match`` and ``group`` if present in the options.
.. note::
This method counts documents on the server side. To obtain an approximate
total number of documents without filters, the
:phpmethod:`MongoDB\\Collection::estimatedDocumentCount()` method can be
used. This method estimates the number of documents based on collection
metadata, thus sacrificing accuracy for performance.
Since this method uses an aggregation pipeline, some query operators accepted
within a :phpmethod:`MongoDB\\Collection::count()` ``filter`` cannot be used.
Consider the following alternatives to these restricted operators:
.. list-table::
:header-rows: 1
* - Restricted
- Alternative Syntax
* - :query:`$near`
- :query:`$geoWithin` with :query:`$center`
* - :query:`$nearSphere`
- :query:`$geoWithin` with :query:`$centerSphere`
* - :query:`$where`
- :query:`$expr` (requires MongoDB 3.6+)
.. include:: /includes/extracts/note-bson-comparison.rst
.. todo: add output and examples
See Also
--------
- :phpmethod:`MongoDB\\Collection::estimatedDocumentCount()`
docs/reference/method/MongoDBCollection-findOneAndUpdate.txt 0000666 00000006266 13645314021 0020137 0 ustar 00 =======================================
MongoDB\\Collection::findOneAndUpdate()
=======================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::findOneAndUpdate()
Finds a single document matching the query and updates it.
.. code-block:: php
function findOneAndUpdate($filter, $update, array $options = []): object|null
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-findOneAndUpdate-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-findOneAndUpdate-option.rst
Return Values
-------------
An array or object for either the original or the updated document, depending on
the specified value of the ``returnDocument`` option. By default, the original
document is returned. If no document matched the query, ``null`` is returned.
The return type will depend on the ``typeMap`` option.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-unexpectedvalueexception.rst
.. include:: /includes/extracts/error-unsupportedexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Behavior
--------
.. include:: /includes/extracts/note-bson-comparison.rst
Examples
--------
The following operation updates the restaurant with ``restaurant_id`` of
``"40361708"`` in the ``restaurants`` collection in the ``test`` database by
setting its building number to ``"761"``:
.. code-block:: php
test->restaurants;
$updatedRestaurant = $collection->findOneAndUpdate(
[ 'restaurant_id' => '40361708' ],
[ '$set' => [ 'address.building' => '761' ]],
[
'projection' => [ 'address' => 1 ],
'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER,
]
);
var_dump($updatedRestaurant);
The output would then resemble::
object(MongoDB\Model\BSONDocument)#20 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["_id"]=>
object(MongoDB\BSON\ObjectId)#12 (1) {
["oid"]=>
string(24) "594d5ef280a846852a4b3dee"
}
["address"]=>
object(MongoDB\Model\BSONDocument)#19 (1) {
["storage":"ArrayObject":private]=>
array(4) {
["building"]=>
string(3) "761"
["coord"]=>
object(MongoDB\Model\BSONArray)#18 (1) {
["storage":"ArrayObject":private]=>
array(2) {
[0]=>
float(-73.9925306)
[1]=>
float(40.7309346)
}
}
["street"]=>
string(8) "Broadway"
["zipcode"]=>
string(5) "10003"
}
}
}
}
See Also
--------
- :phpmethod:`MongoDB\\Collection::findOneAndDelete()`
- :phpmethod:`MongoDB\\Collection::findOneAndReplace()`
- :manual:`findAndModify ` command reference
in the MongoDB manual
docs/reference/method/MongoDBClient-selectCollection.txt 0000666 00000003527 13645314021 0017402 0 ustar 00 ===================================
MongoDB\\Client::selectCollection()
===================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Client::selectCollection()
Selects a collection on the server.
.. code-block:: php
function selectCollection($databaseName, $collectionName, array $options = []): MongoDB\Collection
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBClient-method-selectCollection-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBClient-method-selectCollection-option.rst
Return Values
-------------
A :phpclass:`MongoDB\\Collection` object.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-invalidargumentexception.rst
Behavior
--------
The selected collection inherits options such as read preference and type
mapping from the :phpclass:`Client ` object. Options may be
overridden via the ``$options`` parameter.
Example
-------
The following example selects the ``users`` collection in the ``test`` database:
.. code-block:: php
selectCollection('test', 'users');
The following example selects the ``users`` collection in the ``test`` database
with a custom read preference:
.. code-block:: php
selectCollection(
'test',
'users',
[
'readPreference' => new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY),
]
);
See Also
--------
- :phpmethod:`MongoDB\\Collection::__construct()`
- :phpmethod:`MongoDB\\Database::selectCollection()`
docs/reference/method/MongoDBCollection-getWriteConcern.txt 0000666 00000002454 13645314021 0020064 0 ustar 00 ======================================
MongoDB\\Collection::getWriteConcern()
======================================
.. versionadded:: 1.2
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::getWriteConcern()
Returns the write concern for this collection.
.. code-block:: php
function getWriteConcern(): MongoDB\Driver\WriteConcern
Return Values
-------------
A :php:`MongoDB\\Driver\\WriteConcern `
object.
Example
-------
.. code-block:: php
selectCollection('test', 'users', [
'writeConcern' => new MongoDB\Driver\WriteConcern(1, 0, true),
]);
var_dump($collection->getWriteConcern());
The output would then resemble::
object(MongoDB\Driver\WriteConcern)#5 (2) {
["w"]=>
int(1)
["j"]=>
bool(true)
}
See Also
--------
- :manual:`Write Concern ` in the MongoDB manual
- :php:`MongoDB\\Driver\\WriteConcern::isDefault() `
- :phpmethod:`MongoDB\\Client::getWriteConcern()`
- :phpmethod:`MongoDB\\Database::getWriteConcern()`
- :phpmethod:`MongoDB\\GridFS\\Bucket::getWriteConcern()`
docs/reference/method/MongoDBBulkWriteResult-getDeletedCount.txt 0000666 00000001673 13645314021 0021057 0 ustar 00 ===========================================
MongoDB\\BulkWriteResult::getDeletedCount()
===========================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\BulkWriteResult::getDeletedCount()
Return the total number of documents that were deleted by all delete
operations in the bulk write.
.. code-block:: php
function getDeletedCount(): integer
This method should only be called if the write was acknowledged.
Return Values
-------------
The total number of documents that were deleted by all delete operations in the
bulk write.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-badmethodcallexception-write-result.rst
See Also
--------
- :php:`MongoDB\\Driver\\WriteResult::getDeletedCount()
`
docs/reference/method/MongoDBModelIndexInfo-isSparse.txt 0000666 00000002061 13645314021 0017316 0 ustar 00 =====================================
MongoDB\\Model\\IndexInfo::isSparse()
=====================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Model\\IndexInfo::isSparse()
Return whether the index is a :manual:`sparse index `.
This correlates with the ``sparse`` option for
:phpmethod:`MongoDB\\Collection::createIndex()`.
.. code-block:: php
function isSparse(): boolean
Return Values
-------------
A boolean indicating whether the index is a sparse index.
Examples
--------
.. code-block:: php
true,
]);
var_dump($info->isSparse());
The output would then resemble::
bool(true)
See Also
--------
- :phpmethod:`MongoDB\\Collection::createIndex()`
- :manual:`listIndexes ` command reference in
the MongoDB manual
- :manual:`Sparse Indexes ` in the MongoDB manual
docs/reference/method/MongoDBChangeStream-getCursorId.txt 0000666 00000002423 13645314021 0017456 0 ustar 00 ====================================
MongoDB\\ChangeStream::getCursorId()
====================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\ChangeStream::getCursorId()
Returns the change stream cursor's ID.
.. code-block:: php
function getCursorId(): MongoDB\Driver\CursorId
Return Values
-------------
A :php:`MongoDB\\Driver\\CursorId ` object.
Examples
--------
This example reports the cursor ID for a change stream.
.. code-block:: php
test->inventory;
$changeStream = $collection->watch();
var_dump($changeStream->getCursorId());
The output would then resemble::
object(MongoDB\Driver\CursorId)#5 (1) {
["id"]=>
int(8462642181784669708)
}
See Also
--------
- :phpmethod:`MongoDB\\Client::watch()`
- :phpmethod:`MongoDB\\Collection::watch()`
- :phpmethod:`MongoDB\\Database::watch()`
- :php:`MongoDB\\Driver\\CursorId `
- :php:`MongoDB\\Driver\\Cursor::getId() `
docs/reference/method/MongoDBInsertOneResult-isAcknowledged.txt 0000666 00000001350 13645314021 0020711 0 ustar 00 ==========================================
MongoDB\\InsertOneResult::isAcknowledged()
==========================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\InsertOneResult::isAcknowledged()
Return whether the write was acknowledged.
.. code-block:: php
function isAcknowledged(): boolean
Return Values
-------------
A boolean indicating whether the write was acknowledged.
See Also
--------
- :php:`MongoDB\\Driver\\WriteResult::isAcknowledged()
`
- :manual:`Write Concern ` in the MongoDB manual
docs/reference/method/MongoDBUpdateResult-getUpsertedId.txt 0000666 00000002112 13645314021 0020047 0 ustar 00 ======================================
MongoDB\\UpdateResult::getUpsertedId()
======================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\UpdateResult::getUpsertedId()
Return the ID (i.e. ``_id`` field value) of the upserted document.
.. code-block:: php
function getUpsertedId(): mixed|null
Return Values
-------------
The ID (i.e. ``_id`` field value) of the upserted document. If no document was
upserted, ``null`` will be returned.
If the document had an ID prior to upserting (i.e. the server did not need to
generate an ID), this will contain its ``_id`` field value. Any server-generated
ID will be a :php:`MongoDB\\BSON\\ObjectId `
instance.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-badmethodcallexception-write-result.rst
See Also
--------
- :php:`MongoDB\\Driver\\WriteResult::getUpsertedIds()
`
docs/reference/method/MongoDBGridFSBucket-getFileDocumentForStream.txt 0000666 00000003315 13645314021 0022041 0 ustar 00 ===================================================
MongoDB\\GridFS\\Bucket::getFileDocumentForStream()
===================================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\GridFS\\Bucket::getFileDocumentForStream()
Gets the file document of the GridFS file associated with a stream.
.. code-block:: php
function getFileDocumentForStream($stream): array|object
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBGridFSBucket-method-getFileDocumentForStream-param.rst
Return Values
-------------
The metadata document associated with the GridFS stream. The return type will
depend on the bucket's ``typeMap`` option.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Examples
--------
.. code-block:: php
test->selectGridFSBucket();
$stream = $bucket->openUploadStream('filename');
$fileDocument = $bucket->getFileDocumentForStream($stream);
var_dump($fileDocument);
fclose($stream);
The output would then resemble::
object(MongoDB\Model\BSONDocument)#4956 (1) {
["storage":"ArrayObject":private]=>
array(3) {
["_id"]=>
object(MongoDB\BSON\ObjectId)#4955 (1) {
["oid"]=>
string(24) "5acfb05b7e21e83b5a29037c"
}
["chunkSize"]=>
int(261120)
["filename"]=>
string(8) "filename"
}
}
See Also
--------
- :phpmethod:`MongoDB\\GridFS\\Bucket::getFileIdForStream()`
docs/reference/method/MongoDBDatabase-watch.txt 0000666 00000007022 13645314021 0015475 0 ustar 00 ==========================
MongoDB\\Database::watch()
==========================
.. versionadded:: 1.4
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Database::watch()
Executes a :manual:`change stream ` operation on the
database. The change stream can be watched for database-level changes.
.. code-block:: php
function watch(array $pipeline = [], array $options = []): MongoDB\ChangeStream
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBDatabase-method-watch-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBDatabase-method-watch-option.rst
Return Values
-------------
A :phpclass:`MongoDB\\ChangeStream` object, which allows for iteration of
events in the change stream via the :php:`Iterator ` interface.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-unexpectedvalueexception.rst
.. include:: /includes/extracts/error-unsupportedexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Examples
--------
This example reports events while iterating a change stream.
.. code-block:: php
test;
$changeStream = $database->watch();
for ($changeStream->rewind(); true; $changeStream->next()) {
if ( ! $changeStream->valid()) {
continue;
}
$event = $changeStream->current();
if ($event['operationType'] === 'invalidate') {
break;
}
$ns = sprintf('%s.%s', $event['ns']['db'], $event['ns']['coll']);
$id = json_encode($event['documentKey']['_id']);
switch ($event['operationType']) {
case 'delete':
printf("Deleted document in %s with _id: %s\n\n", $ns, $id);
break;
case 'insert':
printf("Inserted new document in %s\n", $ns);
echo json_encode($event['fullDocument']), "\n\n";
break;
case 'replace':
printf("Replaced new document in %s with _id: %s\n", $ns, $id);
echo json_encode($event['fullDocument']), "\n\n";
break;
case 'update':
printf("Updated document in %s with _id: %s\n", $ns, $id);
echo json_encode($event['updateDescription']), "\n\n";
break;
}
}
Assuming that a document was inserted, updated, and deleted while the above
script was iterating the change stream, the output would then resemble:
.. code-block:: none
Inserted new document in test.inventory
{"_id":{"$oid":"5a81fc0d6118fd1af1790d32"},"name":"Widget","quantity":5}
Updated document in test.inventory with _id: {"$oid":"5a81fc0d6118fd1af1790d32"}
{"updatedFields":{"quantity":4},"removedFields":[]}
Deleted document in test.inventory with _id: {"$oid":"5a81fc0d6118fd1af1790d32"}
See Also
--------
- :phpmethod:`MongoDB\\Collection::watch()`
- :phpmethod:`MongoDB\\Client::watch()`
- :manual:`Aggregation Pipeline ` documentation in
the MongoDB Manual
- :manual:`Change Streams ` documentation in the MongoDB manual
- :manual:`Change Events ` documentation in the
MongoDB manual
docs/reference/method/MongoDBClient-getTypeMap.txt 0000666 00000002150 13645314021 0016155 0 ustar 00 =============================
MongoDB\\Client::getTypeMap()
=============================
.. versionadded:: 1.2
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Client::getTypeMap()
Returns the type map for this client.
.. code-block:: php
function getTypeMap(): array
Return Values
-------------
A :ref:`type map ` array.
Example
-------
.. code-block:: php
[
'root' => 'array',
'document' => 'array',
'array' => 'array',
],
]);
var_dump($client->getTypeMap());
The output would then resemble::
array(3) {
["root"]=>
string(5) "array"
["document"]=>
string(5) "array"
["array"]=>
string(5) "array"
}
See Also
--------
- :doc:`/reference/bson`
- :phpmethod:`MongoDB\\Collection::getTypeMap()`
- :phpmethod:`MongoDB\\Database::getTypeMap()`
- :phpmethod:`MongoDB\\GridFS\\Bucket::getTypeMap()`
docs/reference/method/MongoDBCollection-insertMany.txt 0000666 00000004742 13645314021 0017115 0 ustar 00 =================================
MongoDB\\Collection::insertMany()
=================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::insertMany()
Insert multiple documents.
.. code-block:: php
function insertMany(array $documents, array $options = []): MongoDB\InsertManyResult
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-insertMany-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-insertMany-option.rst
Return Values
-------------
A :phpclass:`MongoDB\\InsertManyResult` object, which encapsulates a
:php:`MongoDB\\Driver\\WriteResult ` object.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-bulkwriteexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Behavior
--------
.. include:: /includes/extracts/bulkwriteexception-result.rst
.. include:: /includes/extracts/bulkwriteexception-ordered.rst
Example
-------
.. start-crud-include
The following operation inserts two documents into the ``users`` collection
in the ``test`` database:
.. code-block:: php
test->users;
$insertManyResult = $collection->insertMany([
[
'username' => 'admin',
'email' => 'admin@example.com',
'name' => 'Admin User',
],
[
'username' => 'test',
'email' => 'test@example.com',
'name' => 'Test User',
],
]);
printf("Inserted %d document(s)\n", $insertManyResult->getInsertedCount());
var_dump($insertManyResult->getInsertedIds());
The output would then resemble::
Inserted 2 document(s)
array(2) {
[0]=>
object(MongoDB\BSON\ObjectId)#11 (1) {
["oid"]=>
string(24) "579a25921f417dd1e5518141"
}
[1]=>
object(MongoDB\BSON\ObjectId)#12 (1) {
["oid"]=>
string(24) "579a25921f417dd1e5518142"
}
}
.. end-crud-include
See Also
--------
- :phpmethod:`MongoDB\\Collection::insertOne()`
- :phpmethod:`MongoDB\\Collection::bulkWrite()`
- :doc:`/tutorial/crud`
- :manual:`insert ` command reference in the MongoDB
manual
docs/reference/method/MongoDBCollection-getCollectionName.txt 0000666 00000001621 13645314021 0020351 0 ustar 00 ========================================
MongoDB\\Collection::getCollectionName()
========================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::getCollectionName()
Returns the name of this collection.
.. code-block:: php
function getCollectionName(): string
Return Values
-------------
The name of this collection as a string.
Example
-------
The following returns the collection name for the ``zips`` collection in the
``test`` database.
.. code-block:: php
test->zips;
echo $collection->getCollectionName();
The output would then resemble::
zips
See Also
--------
- :phpmethod:`MongoDB\\Collection::getDatabaseName()`
- :phpmethod:`MongoDB\\Collection::getNamespace()`
docs/reference/method/MongoDBClient__get.txt 0000666 00000003166 13645314021 0015106 0 ustar 00 ========================
MongoDB\\Client::__get()
========================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Client::__get()
Selects a database on the server. This :php:`magic method ` is
an alias for the :phpmethod:`selectDatabase()
` method.
.. code-block:: php
function __get($databaseName): MongoDB\Database
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBClient-method-get-param.rst
Return Values
-------------
A :phpclass:`MongoDB\\Database` object.
Behavior
--------
The selected database inherits options such as read preference and type mapping
from the :phpclass:`Client ` object. If you wish to override
any options, use the :phpmethod:`MongoDB\\Client::selectDatabase` method.
.. note::
To select databases whose names contain special characters, such as
``-``, use complex syntax, as in ``$client->{'that-database'}``.
Alternatively, :phpmethod:`MongoDB\\Client::selectDatabase()` supports
selecting databases whose names contain special characters.
Examples
--------
The following example selects the ``test`` and ``another-app`` databases:
.. code-block:: php
test;
$anotherApp = $client->{'another-app'};
See Also
--------
- :phpmethod:`MongoDB\\Client::selectDatabase()`
- :phpmethod:`MongoDB\\Database::__construct()`
- :php:`Property Overloading ` in the PHP Manual
docs/reference/method/MongoDBCollection-drop.txt 0000666 00000003315 13645314021 0015723 0 ustar 00 ===========================
MongoDB\\Collection::drop()
===========================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::drop()
Drop the collection.
.. code-block:: php
function drop(array $options = []): array|object
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-drop-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-drop-option.rst
Return Values
-------------
An array or object with the result document of the :manual:`drop
` command. The return type will depend on the
``typeMap`` option.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-unsupportedexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Example
-------
The following operation drops the ``restaurants`` collection in the ``test``
database:
.. code-block:: php
test->restaurants;
$result = $collection->drop();
var_dump($result);
The output would then resemble::
object(MongoDB\Model\BSONDocument)#9 (1) {
["storage":"ArrayObject":private]=>
array(3) {
["ns"]=>
string(16) "test.restaurants"
["nIndexesWas"]=>
int(3)
["ok"]=>
float(1)
}
}
See Also
--------
- :phpmethod:`MongoDB\\Database::dropCollection()`
- :manual:`drop ` command reference in the MongoDB
manual
docs/reference/method/MongoDBChangeStream-next.txt 0000666 00000002075 13645314021 0016205 0 ustar 00 =============================
MongoDB\\ChangeStream::next()
=============================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\ChangeStream::next()
Advances the change stream and attempts to load the next event.
.. code-block:: php
function next(): void
.. note::
Advancing the change stream does not guarantee that there will be a
current event to access. You should still call
:phpmethod:`MongoDB\\ChangeStream::valid()` to check for a current event
at each step of iteration.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-driver-runtimeexception.rst
See Also
--------
- :phpmethod:`MongoDB\\Client::watch()`
- :phpmethod:`MongoDB\\Collection::watch()`
- :phpmethod:`MongoDB\\Database::watch()`
- :php:`Iterator::next() `
- :ref:`Tailable Cursor Iteration `
- :manual:`Change Streams ` documentation in the MongoDB manual
docs/reference/method/MongoDBDatabase-getWriteConcern.txt 0000666 00000002425 13645314021 0017473 0 ustar 00 ====================================
MongoDB\\Database::getWriteConcern()
====================================
.. versionadded:: 1.2
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Database::getWriteConcern()
Returns the write concern for this database.
.. code-block:: php
function getWriteConcern(): MongoDB\Driver\WriteConcern
Return Values
-------------
A :php:`MongoDB\\Driver\\WriteConcern `
object.
Example
-------
.. code-block:: php
selectDatabase('test', [
'writeConcern' => new MongoDB\Driver\WriteConcern(1, 0, true),
]);
var_dump($database->getWriteConcern());
The output would then resemble::
object(MongoDB\Driver\WriteConcern)#5 (2) {
["w"]=>
int(1)
["j"]=>
bool(true)
}
See Also
--------
- :manual:`Write Concern ` in the MongoDB manual
- :php:`MongoDB\\Driver\\WriteConcern::isDefault() `
- :phpmethod:`MongoDB\\Client::getWriteConcern()`
- :phpmethod:`MongoDB\\Collection::getWriteConcern()`
- :phpmethod:`MongoDB\\GridFS\\Bucket::getWriteConcern()`
docs/reference/method/MongoDBCollection-getReadPreference.txt 0000666 00000002373 13645314021 0020334 0 ustar 00 ========================================
MongoDB\\Collection::getReadPreference()
========================================
.. versionadded:: 1.2
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::getReadPreference()
Returns the read preference for this collection.
.. code-block:: php
function getReadPreference(): MongoDB\Driver\ReadPreference
Return Values
-------------
A :php:`MongoDB\\Driver\\ReadPreference `
object.
Example
-------
.. code-block:: php
selectCollection('test', 'users', [
'readPreference' => new MongoDB\Driver\ReadPreference('primaryPreferred'),
]);
var_dump($collection->getReadPreference());
The output would then resemble::
object(MongoDB\Driver\ReadPreference)#5 (1) {
["mode"]=>
string(16) "primaryPreferred"
}
See Also
--------
- :manual:`Read Preference ` in the MongoDB manual
- :phpmethod:`MongoDB\\Client::getReadPreference()`
- :phpmethod:`MongoDB\\Database::getReadPreference()`
- :phpmethod:`MongoDB\\GridFS\\Bucket::getReadPreference()`
docs/reference/method/MongoDBInsertManyResult-getInsertedIds.txt 0000666 00000002014 13645314021 0021064 0 ustar 00 ===========================================
MongoDB\\InsertManyResult::getInsertedIds()
===========================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\InsertManyResult::getInsertedIds()
Return a map of IDs (i.e. ``_id`` field values) for the inserted documents.
.. code-block:: php
function getInsertedIds(): array
Since IDs are created by the driver, this method may be called irrespective
of whether the write was acknowledged.
Return Values
-------------
A map of IDs (i.e. ``_id`` field values) for the inserted documents.
The index of each ID in the map corresponds to each document's position in the
bulk operation. If a document had an ID prior to inserting (i.e. the driver did
not generate an ID), the index will contain its ``_id`` field value. Any
driver-generated ID will be a :php:`MongoDB\\BSON\\ObjectId
` instance.
docs/reference/method/MongoDBModelDatabaseInfo-getSizeOnDisk.txt 0000666 00000001556 13645314021 0020714 0 ustar 00 =============================================
MongoDB\\Model\\DatabaseInfo::getSizeOnDisk()
=============================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Model\\DatabaseInfo::getSizeOnDisk()
Return the total size of the database file on disk in bytes.
.. code-block:: php
function getSizeOnDisk(): integer
Return Values
-------------
The total size of the database file on disk in bytes.
Examples
--------
.. code-block:: php
1048576]);
var_dump($info->getSizeOnDisk());
The output would then resemble::
int(1048576)
See Also
--------
- :manual:`listDatabases ` command reference
in the MongoDB manual
docs/reference/method/MongoDBMapReduceResult-getExecutionTimeMS.txt 0000666 00000002430 13645314021 0021447 0 ustar 00 ==============================================
MongoDB\\MapReduceResult::getExecutionTimeMS()
==============================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\MapReduceResult::getExecutionTimeMS()
Returns the execution time in milliseconds of the map-reduce operation.
.. code-block:: php
function getExecutionTimeMS(): integer
Return Values
-------------
An integer denoting the execution time in milliseconds for the map-reduce
operation.
Examples
--------
This example reports the execution time for a map-reduce operation.
.. code-block:: php
test->zips;
$map = new MongoDB\BSON\Javascript('function() { emit(this.state, this.pop); }');
$reduce = new MongoDB\BSON\Javascript('function(key, values) { return Array.sum(values) }');
$out = ['inline' => 1];
$result = $collection->mapReduce($map, $reduce, $out);
var_dump($result->getExecutionTimeMS());
The output would then resemble::
int(244)
See Also
--------
- :phpmethod:`MongoDB\\Collection::mapReduce()`
- :manual:`mapReduce ` command reference in the
MongoDB manual
docs/reference/method/MongoDBCollection-bulkWrite.txt 0000666 00000003340 13645314021 0016725 0 ustar 00 ================================
MongoDB\\Collection::bulkWrite()
================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::bulkWrite()
Executes multiple write operations.
.. code-block:: php
function bulkWrite(array $operations, array $options = []): MongoDB\BulkWriteResult
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-bulkWrite-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-bulkWrite-option.rst
Return Values
-------------
A :phpclass:`MongoDB\\BulkWriteResult` object, which encapsulates a
:php:`MongoDB\\Driver\\WriteResult ` object.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-unsupportedexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-bulkwriteexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Behavior
--------
.. include:: /includes/extracts/bulkwriteexception-result.rst
.. include:: /includes/extracts/bulkwriteexception-ordered.rst
.. todo: add output and examples
See Also
--------
- :phpmethod:`MongoDB\\Collection::deleteMany()`
- :phpmethod:`MongoDB\\Collection::deleteOne()`
- :phpmethod:`MongoDB\\Collection::insertMany()`
- :phpmethod:`MongoDB\\Collection::insertOne()`
- :phpmethod:`MongoDB\\Collection::replaceOne()`
- :phpmethod:`MongoDB\\Collection::updateMany()`
- :phpmethod:`MongoDB\\Collection::updateOne()`
- :doc:`/tutorial/crud`
docs/reference/method/MongoDBChangeStream-getResumeToken.txt 0000666 00000003520 13645314021 0020164 0 ustar 00 =======================================
MongoDB\\ChangeStream::getResumeToken()
=======================================
.. versionadded:: 1.5
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\ChangeStream::getResumeToken()
Returns the cached resume token that will be used to resume the change
stream.
.. code-block:: php
function getResumeToken(): array|object|null
Return Values
-------------
An array or object, or ``null`` if there is no cached resume token. The return
type will depend on the ``typeMap`` option for the ``watch()`` method used to
create the change stream.
Examples
--------
This example captures the resume token for a change stream after encountering
an ``invalidate`` event and uses it to construct a second change stream using
the ``startAfter`` option.
.. code-block:: php
test->inventory;
$changeStream = $collection->watch();
for ($changeStream->rewind(); true; $changeStream->next()) {
if ( ! $changeStream->valid()) {
continue;
}
$event = $changeStream->current();
if ($event['operationType'] === 'invalidate') {
$startAfter = $changeStream->getResumeToken();
break;
}
printf("%d: %s\n", $changeStream->key(), $event['operationType']);
}
$changeStream = $collection->watch([], ['startAfter' => $startAfter]);
See Also
--------
- :phpmethod:`MongoDB\\Client::watch()`
- :phpmethod:`MongoDB\\Collection::watch()`
- :phpmethod:`MongoDB\\Database::watch()`
- :manual:`Resume a Change Stream `
documentation in the MongoDB manual
docs/reference/method/MongoDBCollection-replaceOne.txt 0000666 00000004765 13645314021 0017046 0 ustar 00 =================================
MongoDB\\Collection::replaceOne()
=================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::replaceOne()
Replace at most one document that matches the filter criteria. If multiple
documents match the filter criteria, only the :term:`first `
matching document will be replaced.
.. code-block:: php
function replaceOne($filter, $replacement, array $options = []): MongoDB\UpdateResult
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-replaceOne-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-replaceOne-option.rst
Return Values
-------------
A :phpclass:`MongoDB\\UpdateResult` object, which encapsulates a
:php:`MongoDB\\Driver\\WriteResult ` object.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-unsupportedexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-bulkwriteexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Behavior
--------
.. include:: /includes/extracts/note-bson-comparison.rst
.. include:: /includes/extracts/bulkwriteexception-result.rst
Example
-------
The following example replaces the document with ``restaurant_id`` of
``"40356068"`` in the ``restaurants`` collection in the ``test`` database:
.. code-block:: php
test->restaurants;
$updateResult = $collection->replaceOne(
[ 'restaurant_id' => '40356068' ],
[
'name' => 'New Restaurant',
'restaurant_id' => '99988877',
'borough' => 'Queens',
'cuisine' => 'Cafe',
'grades' => [],
]
);
printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());
The output would then resemble::
Matched 1 document(s)
Modified 1 document(s)
See Also
--------
- :phpmethod:`MongoDB\\Collection::updateMany()`
- :phpmethod:`MongoDB\\Collection::updateOne()`
- :phpmethod:`MongoDB\\Collection::bulkWrite()`
- :doc:`/tutorial/crud`
- :manual:`update ` command reference in the MongoDB
manual
docs/reference/method/MongoDBClient-createClientEncryption.txt 0000666 00000003105 13645314021 0020554 0 ustar 00 =========================================
MongoDB\\Client::createClientEncryption()
=========================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Client::createClientEncryption()
Returns a :php:`MongoDB\\Driver\\ClientEncryption `
object for manual encryption and decryption of values.
.. code-block:: php
function createClientEncryption(array $options): MongoDB\Driver\ClientEncryption
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBClient-method-createClientEncryption-param.rst
The ``$options`` parameter supports all options documented in the
:php:`extension manual `.
For the ``keyVaultClient`` option, an instance of :phpclass:`MongoDB\\Client`
is automatically unwrapped and the :php:`MongoDB\\Driver\\Manager `
instance is passed to the extension.
Return Values
-------------
A :php:`MongoDB\\Driver\\ClientEncryption `
instance which can be used to encrypt and decrypt values.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-invalidargumentexception.rst
See Also
--------
- :php:`MongoDB\\Driver\\Manager::createClientEncryption()
`
docs/reference/method/MongoDBGridFSBucket__construct.txt 0000666 00000003071 13645314021 0017404 0 ustar 00 ======================================
MongoDB\\GridFS\\Bucket::__construct()
======================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\GridFS\\Bucket::__construct()
Constructs a new :phpclass:`Bucket ` instance.
.. code-block:: php
function __construct(MongoDB\Driver\Manager $manager, $databaseName, array $options = [])
This constructor has the following parameters:
.. include:: /includes/apiargs/MongoDBGridFSBucket-method-construct-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBGridFSBucket-method-construct-option.rst
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-invalidargumentexception.rst
Behavior
--------
If you construct a Bucket explicitly, the Bucket inherits any options
from the :php:`MongoDB\\Driver\\Manager ` object.
If you select the Bucket from a :phpclass:`Database ` object,
the Bucket inherits its options from that object.
Examples
--------
.. code-block:: php
test->selectGridFSBucket();
var_dump($bucket);
The output would then resemble::
object(MongoDB\GridFS\Bucket)#3053 (2) {
["bucketName"]=>
string(4) "test"
["databaseName"]=>
string(11) "phplib_test"
}
See Also
--------
- :phpmethod:`MongoDB\\Database::selectGridFSBucket()`
docs/reference/method/MongoDBChangeStream-key.txt 0000666 00000003435 13645314021 0016020 0 ustar 00 ============================
MongoDB\\ChangeStream::key()
============================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\ChangeStream::key()
Returns the index of the current event in the change stream.
.. code-block:: php
function key(): integer|null
The index of the first event in a change stream starts at zero and will
increment by one for each subsequent event.
Return Values
-------------
The index of the current event in the change stream, or ``null`` if there is no
current event (i.e. :phpmethod:`MongoDB\\ChangeStream::valid()` returns
``false``).
Examples
--------
This example reports the index of events while iterating a change stream.
.. code-block:: php
test->inventory;
$changeStream = $collection->watch();
for ($changeStream->rewind(); true; $changeStream->next()) {
if ( ! $changeStream->valid()) {
continue;
}
$event = $changeStream->current();
printf("%d: %s\n", $changeStream->key(), $event['operationType']);
}
Assuming that a document was inserted, updated, and deleted while the above
script was iterating the change stream, the output would then resemble:
.. code-block:: none
0: insert
1: update
2: delete
See Also
--------
- :phpmethod:`MongoDB\\Client::watch()`
- :phpmethod:`MongoDB\\Collection::watch()`
- :phpmethod:`MongoDB\\Database::watch()`
- :php:`Iterator::key() `
- :ref:`Tailable Cursor Iteration `
- :manual:`Change Streams ` documentation in the MongoDB manual docs/reference/method/MongoDBDatabase-getReadPreference.txt 0000666 00000002344 13645314021 0017743 0 ustar 00 ======================================
MongoDB\\Database::getReadPreference()
======================================
.. versionadded:: 1.2
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Database::getReadPreference()
Returns the read preference for this database.
.. code-block:: php
function getReadPreference(): MongoDB\Driver\ReadPreference
Return Values
-------------
A :php:`MongoDB\\Driver\\ReadPreference `
object.
Example
-------
.. code-block:: php
selectDatabase('test', [
'readPreference' => new MongoDB\Driver\ReadPreference('primaryPreferred'),
]);
var_dump($database->getReadPreference());
The output would then resemble::
object(MongoDB\Driver\ReadPreference)#5 (1) {
["mode"]=>
string(16) "primaryPreferred"
}
See Also
--------
- :manual:`Read Preference ` in the MongoDB manual
- :phpmethod:`MongoDB\\Client::getReadPreference()`
- :phpmethod:`MongoDB\\Collection::getReadPreference()`
- :phpmethod:`MongoDB\\GridFS\\Bucket::getReadPreference()`
docs/reference/method/MongoDBClient-selectDatabase.txt 0000666 00000003275 13645314021 0017013 0 ustar 00 =================================
MongoDB\\Client::selectDatabase()
=================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Client::selectDatabase()
Selects a database on the server.
.. code-block:: php
function selectDatabase($databaseName, array $options = []): MongoDB\Database
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBClient-method-selectDatabase-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBClient-method-selectDatabase-option.rst
Return Values
-------------
A :phpclass:`MongoDB\\Database` object.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-invalidargumentexception.rst
Behavior
--------
The selected database inherits options such as read preference and type mapping
from the :phpclass:`Client ` object. Options may be overridden
via the ``$options`` parameter.
Example
-------
The following example selects the ``test`` database:
.. code-block:: php
selectDatabase('test');
The following examples selects the ``test`` database with a custom read
preference:
.. code-block:: php
selectDatabase(
'test',
[
'readPreference' => new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY),
]
);
See Also
--------
- :phpmethod:`MongoDB\\Client::__get()`
- :phpmethod:`MongoDB\\Database::__construct()`
docs/reference/method/MongoDBGridFSBucket-findOne.txt 0000666 00000004214 13645314021 0016521 0 ustar 00 ==================================
MongoDB\\GridFS\\Bucket::findOne()
==================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\GridFS\\Bucket::findOne()
Finds a single document from the GridFS bucket's files collection matching
the query.
.. code-block:: php
function findOne($filter = [], array $options = []): array|object|null
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-findOne-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBGridFSBucket-method-findOne-option.rst
Return Values
-------------
An array or object for the :term:`first document ` that matched
the query, or ``null`` if no document matched the query. The return type will
depend on the ``typeMap`` option.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-unsupportedexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Behavior
--------
.. include:: /includes/extracts/note-bson-comparison.rst
Examples
--------
.. code-block:: php
test->selectGridFSBucket();
$stream = fopen('php://temp', 'w+b');
fwrite($stream, "foobar");
rewind($stream);
$bucket->uploadFromStream('b', $stream);
$fileDocument = $bucket->findOne(
['length' => ['$lte' => 6]],
[
'projection' => [
'filename' => 1,
'length' => 1,
'_id' => 0,
],
'sort' => ['length' => -1],
]
);
var_dump($fileDocument);
The output would then resemble::
object(MongoDB\Model\BSONDocument)#3004 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["filename"]=>
string(1) "b"
["length"]=>
int(6)
}
}
See Also
--------
- :phpmethod:`MongoDB\\Collection::findOne()`
- :phpmethod:`MongoDB\\GridFS\\Bucket::find()`
docs/reference/method/MongoDBModelIndexInfo-isText.txt 0000666 00000002261 13645314021 0017007 0 ustar 00 ===================================
MongoDB\\Model\\IndexInfo::isText()
===================================
.. versionadded:: 1.4
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Model\\IndexInfo::isText()
Return whether the index is a :manual:`text ` index.
.. code-block:: php
function isText(): boolean
Return Values
-------------
A boolean indicating whether the index is a text index.
Examples
--------
.. code-block:: php
selectCollection('test', 'restaurants');
$collection->createIndex(['name' => 'text']);
foreach ($collection->listIndexes() as $index) {
if ($index->isText()) {
printf("%s has default language: %d\n", $index->getName(), $index['default_language']);
}
}
The output would then resemble::
name_text has default language: english
See Also
--------
- :phpmethod:`MongoDB\\Collection::createIndex()`
- :phpmethod:`MongoDB\\Collection::listIndexes()`
- :manual:`Text Indexes ` reference in the MongoDB
manual
docs/reference/method/MongoDBModelIndexInfo-getName.txt 0000666 00000001743 13645314021 0017113 0 ustar 00 ====================================
MongoDB\\Model\\IndexInfo::getName()
====================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Model\\IndexInfo::getName()
Return the index name. This correlates with the return value of
:phpmethod:`MongoDB\\Collection::createIndex()`. An index name may be derived
from the ``$key`` parameter or or explicitly specified via the ``name``
option.
.. code-block:: php
function getName(): string
Return Values
-------------
The index name.
Examples
--------
.. code-block:: php
'x_1',
]);
echo $info->getName();
The output would then resemble::
x_1
See Also
--------
- :phpmethod:`MongoDB\\Collection::createIndex()`
- :manual:`listIndexes ` command reference in
the MongoDB manual
docs/reference/method/MongoDBDatabase__get.txt 0000666 00000003103 13645314021 0015363 0 ustar 00 ==========================
MongoDB\\Database::__get()
==========================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Database::__get()
Select a collection within the database.
.. code-block:: php
function __get($collectionName): MongoDB\Collection
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBDatabase-method-get-param.rst
Return Values
-------------
A :phpclass:`MongoDB\\Collection` object.
Behavior
--------
The selected collection inherits options such as read preference and type
mapping from the :phpclass:`Database ` object. If you wish to
override any options, use the :phpmethod:`MongoDB\\Database::selectCollection`
method.
.. note::
To select collections whose names contain special characters, such as
``.``, use complex syntax, as in ``$database->{'that.database'}``.
Alternatively, :phpmethod:`MongoDB\\Database::selectCollection` supports
selecting collections whose names contain special characters.
Examples
--------
The following example selects the ``users`` and ``system.profile``
collections from the ``test`` database:
.. code-block:: php
test;
$users = $db->users;
$systemProfile = $db->{'system.profile'};
See Also
--------
- :phpmethod:`MongoDB\\Database::selectCollection()`
- :phpmethod:`MongoDB\\Client::selectCollection()`
- :php:`Property Overloading ` in the PHP Manual
docs/reference/method/MongoDBGridFSBucket-find.txt 0000666 00000004047 13645314021 0016063 0 ustar 00 ===============================
MongoDB\\GridFS\\Bucket::find()
===============================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\GridFS\\Bucket::find()
Finds documents from the GridFS bucket's files collection matching the query.
.. code-block:: php
function find($filter = [], array $options = []): MongoDB\Driver\Cursor
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-find-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBGridFSBucket-method-find-option.rst
Return Values
-------------
A :php:`MongoDB\\Driver\\Cursor ` object.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-unsupportedexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Behavior
--------
.. include:: /includes/extracts/note-bson-comparison.rst
Examples
--------
.. code-block:: php
test->selectGridFSBucket();
$stream = fopen('php://temp', 'w+b');
fwrite($stream, "foobar");
rewind($stream);
$bucket->uploadFromStream('b', $stream);
$cursor = $bucket->find(
['length' => ['$lte' => 6]],
[
'projection' => [
'filename' => 1,
'length' => 1,
'_id' => 0,
],
'sort' => ['length' => -1],
]
);
var_dump($cursor->toArray());
The output would then resemble::
array(1) {
[0]=>
object(MongoDB\Model\BSONDocument)#3015 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["filename"]=>
string(1) "b"
["length"]=>
int(6)
}
}
}
See Also
--------
- :phpmethod:`MongoDB\\Collection::find()`
- :phpmethod:`MongoDB\\GridFS\\Bucket::findOne()`
docs/reference/method/MongoDBDatabase-aggregate.txt 0000666 00000003361 13645314021 0016317 0 ustar 00 ==============================
MongoDB\\Database::aggregate()
==============================
.. versionadded:: 1.5
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Database::aggregate()
Runs a specified :manual:`admin/diagnostic pipeline
` which does
not require an underlying collection. For aggregations on collection data,
see :phpmethod:`MongoDB\\Collection::aggregate()`.
.. code-block:: php
function aggregate(array $pipeline, array $options = []): Traversable
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBDatabase-method-aggregate-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBDatabase-method-aggregate-option.rst
Return Values
-------------
A :php:`MongoDB\\Driver\\Cursor ` or
:php:`ArrayIterator ` object. In both cases, the return value
will be :php:`Traversable `.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-unexpectedvalueexception.rst
.. include:: /includes/extracts/error-unsupportedexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
.. _php-db-agg-method-behavior:
.. todo: add examples
See Also
--------
- :phpmethod:`MongoDB\\Collection::aggregate()`
- :manual:`aggregate ` command reference in the
MongoDB manual
- :manual:`Aggregation Pipeline ` documentation in
the MongoDB Manual
docs/reference/method/MongoDBCollection-deleteMany.txt 0000666 00000004161 13645314021 0017046 0 ustar 00 =================================
MongoDB\\Collection::deleteMany()
=================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::deleteMany()
Deletes all documents that match the filter criteria.
.. code-block:: php
function deleteMany($filter, array $options = []): MongoDB\DeleteResult
This method has the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-deleteMany-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-deleteMany-option.rst
Return Values
-------------
A :phpclass:`MongoDB\\DeleteResult` object, which encapsulates a
:php:`MongoDB\\Driver\\WriteResult ` object.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-unsupportedexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-bulkwriteexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Behavior
--------
.. include:: /includes/extracts/note-bson-comparison.rst
.. include:: /includes/extracts/bulkwriteexception-result.rst
Example
-------
The following example deletes all of the documents in the ``users`` collection
that have ``"ny"`` as the value for the ``state`` field:
.. code-block:: php
test->users;
$collection->drop();
$collection->insertOne(['name' => 'Bob', 'state' => 'ny']);
$collection->insertOne(['name' => 'Alice', 'state' => 'ny']);
$deleteResult = $collection->deleteMany(['state' => 'ny']);
printf("Deleted %d document(s)\n", $deleteResult->getDeletedCount());
The output would then resemble::
Deleted 2 document(s)
See Also
--------
- :phpmethod:`MongoDB\\Collection::deleteOne()`
- :phpmethod:`MongoDB\\Collection::bulkWrite()`
- :doc:`/tutorial/crud`
- :manual:`delete