Commit d5c501a2 authored by Allison Moore's avatar Allison Moore Committed by Jeremy Mikola

Port docs to RST and split the API reference

parent ab7aba10
arg_name: param
name: $uri
type: string
description: |
The URI of the standalone, replica set, or sharded cluster to which to connect. Refer
to the :manual:`MongoDB connection string reference </reference/connection-string>`
for formatting.
Defaults to ``mongodb://localhost:27017`` if unspecified.
interface: phpmethod
operation: MongoDB\\Client::__construct
optional: true
position: 1
---
arg_name: param
name: $uriOptions
type: array
description: |
Specifies additional URI options, such as authentication credentials
or query string parameters. The options specified in ``$uriOptions``
take precedence over any analogous options present in the
``$uri`` string.
post: |
Refer to the :php:`MongoDB\\Driver\\Manager::__construct()
<mongodb-driver-manager.construct>` extension reference and
:manual:`MongoDB connection string </reference/connection-string>`
documentation for valid options.
interface: phpmethod
operation: MongoDB\\Client::__construct
optional: true
position: 2
---
arg_name: param
name: $driverOptions
type: array
description: |
Specify driver-specific options. In addition to any
options supported by the :php:`extension <mongodb-driver-manager>`,
the |php-library| allows you to specify a default ``typeMap`` to
apply to the cursors it creates. Refer to the driver's
:php:`Persistence documentation <mongodb-persistence>` for more
about type maps.
interface: phpmethod
operation: MongoDB\\Client::__construct
optional: true
position: 3
...
\ No newline at end of file
arg_name: option
interface: phpmethod
operation: MongoDB\\Client::dropDatabase
source:
file: apiargs-common-option.yaml
ref: typeMap
position: 1
...
source:
ref: $databaseName
file: apiargs-common-param.yaml
arg_name: param
interface: phpmethod
operation: MongoDB\\Client::dropDatabase
---
source:
ref: $options
file: apiargs-common-param.yaml
arg_name: param
interface: phpmethod
operation: MongoDB\\Client::dropDatabase
position: 2
...
source:
ref: $databaseName
file: apiargs-common-param.yaml
arg_name: param
interface: phpmethod
operation: MongoDB\\Client::__get
...
source:
file: apiargs-common-option.yaml
ref: maxTimeMS
position: 1
...
source:
ref: $options
file: apiargs-common-param.yaml
arg_name: param
interface: phpmethod
operation: MongoDB\\Client::listDatabases
position: 1
...
source:
ref: readConcern
file: apiargs-common-option.yaml
operation: MongoDB\\Client::selectDatabase
replacement:
resource: "database"
---
source:
ref: readPreference
file: apiargs-common-option.yaml
operation: MongoDB\\Client::selectDatabase
replacement:
resource: "database"
---
source:
ref: typeMap
file: apiargs-common-option.yaml
operation: MongoDB\\Client::selectDatabase
---
source:
ref: writeConcern
file: apiargs-common-option.yaml
operation: MongoDB\\Client::selectDatabase
replacement:
resource: "database"
...
\ No newline at end of file
source:
ref: $databaseName
file: apiargs-common-param.yaml
operation: MongoDB\\Client::selectDatabase
position: 1
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Client::selectDatabase
position: 2
...
arg_name: option
name: allowDiskUse
type: boolean
description: |
Enables writing to temporary files. When set to true, aggregation
stages can write data to the ``_tmp`` sub-directory in the dbPath
directory. The default is ``false``.
interface: phpmethod
operation: MongoDB\\Collection::aggregate
optional: true
position: 1
---
arg_name: option
name: batchSize
type: integer
description: |
The number of documents to return per batch
interface: phpmethod
operation: MongoDB\\Collection::aggregate
optional: true
position: 2
---
source:
ref: bypassDocumentValidation
file: apiargs-common-option.yaml
operation: MongoDB\\Collection::aggregate
position: 5
---
source:
ref: maxTimeMS
file: apiargs-common-option.yaml
operation: MongoDB\\Collection::aggregate
position: 4
---
source:
ref: readConcern
file: apiargs-common-option.yaml
operation: MongoDB\\Collection::selectDatabase
replacement:
resource: "aggregation"
position: 5
---
source:
ref: readPreference
file: apiargs-common-option.yaml
operation: MongoDB\\Collection::selectDatabase
replacement:
resource: "aggregation"
position: 6
---
source:
ref: typeMap
file: apiargs-common-option.yaml
operation: MongoDB\\Collection::selectDatabase
position: 7
---
arg_name: param
name: useCursor
type: boolean
description: |
Indicates whether the command will request that the server provide
results using a cursor. The default is ``true``.
For MongoDB version 2.6 or later, ``useCursor`` allows users to turn
off cursors if necessary to aid in mongod/mongos upgrades.
``useCursor`` is ignored for MongoDB versions prior to 2.6 as
aggregation cursors are not available pre-2.6.
interface: phpmethod
operation: MongoDB\\Collection::aggregate
optional: true
position: 8
...
arg_name: param
name: $pipeline
type: array
description: |
Specifies an :manual:`aggregation pipeline </core/aggregation-pipeline>` operation.
interface: phpmethod
operation: MongoDB\\Collection::aggregate
optional: true
position: 1
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::aggregate
position: 2
...
\ No newline at end of file
source:
ref: bypassDocumentValidation
file: apiargs-common-option.yaml
operation: MongoDB\\Collection::bulkWrite
position: 1
---
arg_name: option
name: ordered
type: boolean
description: |
If ``true``: when an insert fails, the operation returns without performing the
remaining writes.
If ``false``: when a write fails, the operation will continue with the
remaining writes, if any.
The default is ``true``.
optional: true
interface: phpmethod
operation: MongoDB\\Collection::bulkWrite
position: 2
---
source:
ref: writeConcern
file: apiargs-common-option.yaml
operation: MongoDB\\Collection::bulkWrite
replacement:
resource: "write"
position: 3
...
arg_name: param
name: $operations
type: array
description: |
An array containing the write operations to perform. {{role}}
supports :phpmethod:`deleteMany <MongoDB\\Collection::deleteMany>`,
:phpmethod:`deleteOne <MongoDB\\Collection::deleteOne>`, :phpmethod:`insertOne
<MongoDB\\Collection::insertOne>`, :phpmethod:`replaceOne
<MongoDB\\Collection::replaceOne>`, :phpmethod:`updateMany
<MongoDB\\Collection::updateMany>`, and :phpmethod:`updateOne
<MongoDB\\Collection::updateOne>` operations in the following array
structure:
.. code-block:: php
[
[ 'deleteMany' => [ $filter ] ],
[ 'deleteOne' => [ $filter ] ],
[ 'insertOne' => [ $document ] ],
[ 'replaceOne' => [ $filter, $replacement, $options ] ],
[ 'updateMany' => [ $filter, $update, $options ] ],
[ 'updateOne' => [ $filter, $update, $options ] ],
]
post: |
Arguments correspond to the respective operation methods. However,
the ``writeConcern`` option is specified for the top-level bulk write
operation instead of each individual operation.
interface: phpmethod
operation: MongoDB\\Collection::bulkWrite
optional: true
position: 1
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::bulkWrite
interface: phpmethod
position: 2
...
\ No newline at end of file
arg_name: param
name: $manager
type: :php:`MongoDB\\Driver\\Manager <class.mongodb-driver-manager>`
description: |
The :php:`Manager <mongodb-driver-manager>` instance from the driver.
The manager maintains connections between the driver and your MongoDB
instances.
interface: phpmethod
operation: MongoDB\\Collection::__construct
optional: false
position: 1
---
source:
ref: $databaseName
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::__construct
replacement:
select: ""
position: 2
---
source:
ref: $collectionName
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::__construct
replacement:
select: ""
position: 3
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::__construct
position: 4
...
\ No newline at end of file
arg_name: option
name: hint
type: string or array|object
description: |
The index to use. If you specify a document, it is interpreted as
an index specification and a name will be generated.
optional: true
interface: phpmethod
operation: MongoDB\\Collection::count
position: 1
---
arg_name: option
name: limit
type: integer
description: |
The maximum number of documents to return.
optional: true
interface: phpmethod
operation: MongoDB\\Collection::count
position: 2
---
source:
ref: maxTimeMS
file: apiargs-common-option.yaml
operation: MongoDB\\Collection::count
position: 3
---
source:
ref: readConcern
file: apiargs-common-option.yaml
operation: MongoDB\\Collection::count
replacement:
resource: "count"
position: 4
---
source:
ref: readPreference
file: apiargs-common-option.yaml
replacement:
resource: "count"
position: 5
---
arg_name: option
name: skip
type: integer
description: |
The number of documents to skip before returning the documents.
optional: true
interface: phpmethod
operation: MongoDB\\Collection::count
position: 6
...
source:
ref: $filter
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::count
position: 1
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::count
position: 2
...
arg_name: option
name: unique
type: boolean
description: |
Creates a :manual:`unique </core/index-unique>` index.
interface: phpmethod
operation: MongoDB\\Collection::createIndex
optional: true
position: 1
---
arg_name: option
name: partialFilterExpression
type: array|object
description: |
Creates a :manual:`partial </core/index-partial>` index.
interface: phpmethod
operation: MongoDB\\Collection::createIndex
optional: true
position: 2
---
arg_name: option
name: sparse
type: boolean
description: |
Creates a :manual:`sparse </core/index-sparse>` index.
interface: phpmethod
operation: MongoDB\\Collection::createIndex
optional: true
position: 3
---
arg_name: option
name: expireAfterSeconds
type: integer
description: |
Creates a :manual:`TTL </core/index-ttl>` index.
interface: phpmethod
operation: MongoDB\\Collection::createIndex
optional: true
position: 4
---
arg_name: option
name: name
type: string
description: |
Specifies the name for the index. By default, MongoDB creates index
names based on the key.
interface: phpmethod
operation: MongoDB\\Collection::createIndex
optional: true
position: 5
---
arg_name: option
name: background
type: string
description: |
Instructs MongoDB to build the index :manual:`as a background
</core/index-creation>` process.
interface: phpmethod
operation: MongoDB\\Collection::createIndex
optional: true
position: 6
---
arg_name: option
name: 2dsphereIndexVersion
type: integer
description: |
Specifies the :manual:`version of a 2dsphere </core/2dsphere>` index
to create.
MongoDB 2.6 introduced version 2 of 2dsphere indexes. Version 2 is
the default version of 2dsphere indexes created in MongoDB 2.6 and
later series. ``2dsphereIndexVersion`` enables you to overrride the
default version 2.
interface: phpmethod
operation: MongoDB\\Collection::createIndex
optional: true
position: 7
---
arg_name: option
name: socketTimeoutMS
type: integer
description: |
Specifies the time limit, in milliseconds, for socket
communication. If the :program:`mongod` does not respond within the
timeout period, a ``MongoCursorTimeoutException`` is thrown and
there will be no way to determine if the server actually handled the
write or not. Specify ``-1`` to block indefinitely. The default value
is 30000 (30 seconds).
interface: phpmethod
operation: MongoDB\\Collection::createIndex
optional: true
position: 8
---
source:
ref: maxTimeMS
file: apiargs-common-option.yaml
operation: MongoDB\\Collection::createIndex
position: 9
...
arg_name: param
name: $key
type: array|object
description: |
Specifies the field or fields to index and the index order.
For example, the following specifies a descending index
on the ``username`` field:
.. code-block:: php
$key = [ 'username' => -1 ];
operation: MongoDB\\Collection::createIndex
interface: phpmethod
optional: false
position: 1
---
source:
file: apiargs-common-param.yaml
ref: $options
operation: MongoDB\\Collection::createIndex
position: 2
...
\ No newline at end of file
source:
ref: writeConcern
file: apiargs-common-option.yaml
operation: MongoDB\\Collection::deleteMany
replacement:
resource: "delete"
position: 1
...
source:
ref: $filter
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::deleteMany
replacement:
verb: "delete"
position: 1
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::deleteMany
position: 2
...
source:
ref: writeConcern
file: apiargs-common-option.yaml
operation: MongoDB\\Collection::deleteOne
replacement:
resource: "delete"
position: 1
...
source:
ref: $filter
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::deleteOne
replacement:
verb: "delete"
position: 1
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::deleteOne
position: 2
...
source:
ref: maxTimeMS
file: apiargs-common-option.yaml
operation: MongoDB\\Collection::distinct
position: 1
---
source:
ref: readConcern
file: apiargs-common-option.yaml
operation: MongoDB\\Collection::distinct
replacement:
resource: "distinct"
position: 2
---
source:
ref: readPreference
file: apiargs-common-option.yaml
replacement:
resource: "distinct"
position: 3
...
arg_name: param
name: $fieldName
type: string
description: |
The field for which to return distinct values.
interface: phpmethod
operation: MongoDB\\Collection::distinct
optional: false
position: 1
---
source:
file: apiargs-common-param.yaml
ref: $filter
position: 2
optional: true
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::count
position: 3
...
source:
file: apiargs-common-option.yaml
ref: typeMap
operation: MongoDB\\Collection::drop
position: 1
...
\ No newline at end of file
source:
file: apiargs-common-param.yaml
ref: $options
interface: phpmethod
operation: MongoDB\\Collection::drop
position: 1
...
\ No newline at end of file
source:
file: apiargs-common-option.yaml
ref: typeMap
operation: MongoDB\\Collection::dropIndex
position: 1
...
\ No newline at end of file
arg_name: param
name: $indexName
type: string
description: |
The name of the index to drop. View the existing indexes on the
collection using the :phpmethod:`listIndexes
<MongoDB\\Collection::listIndexes>` method.
interface: phpmethod
operation: MongoDB\\Collection::dropIndex
optional: false
position: 1
---
source:
file: apiargs-common-param.yaml
ref: $options
interface: phpmethod
operation: MongoDB\\Collection::dropIndex
position: 2
...
\ No newline at end of file
source:
file: apiargs-common-option.yaml
ref: typeMap
operation: MongoDB\\Collection::dropIndexes
position: 1
...
\ No newline at end of file
source:
file: apiargs-common-param.yaml
ref: $options
operation: MongoDB\\Collection::dropIndexes
position: 1
...
\ No newline at end of file
name: sort
type: array|object
optional: true
description: |
The sort specification for the ordering of the results.
arg_name: field
operation: MongoDB\\Collection::find
interface: phpmethod
position: 2
---
name: projection
type: array|object
optional: true
description: |
The :ref:`projection specification <projections>` to determine
which fields to include in the returned documents. See
:manual:`Project Fields to Return from Query
</tutorial/project-fields-from-query-results>` in the MongoDB
manual.
arg_name: field
operation: MongoDB\\Collection::find
interface: phpmethod
position: 1
---
name: skip
type: integer
optional: true
description: |
Number of documents to skip. Defaults to 0.
arg_name: field
operation: MongoDB\\Collection::find
interface: phpmethod
position: 3
---
name: limit
type: integer
optional: true
description: |
The maximum number of documents to return. If unspecified,
then defaults to no limit. A limit of 0 is equivalent to setting no
limit.
arg_name: field
operation: MongoDB\\Collection::find
interface: phpmethod
position: 4
---
name: batchSize
type: integer
optional: true
description: |
The number of documents to return in the first batch.
Defaults to 101. A batchSize of 0 means that the cursor will be
established, but no documents will be returned in the first batch.
Unlike the previous wire protocol version, a batchSize of 1 for
the :dbcommand:`find` command does not close the cursor.
arg_name: field
operation: MongoDB\\Collection::find
interface: phpmethod
position: 5
---
name: comment
type: string
optional: true
description: |
A comment to attach to the query to help interpret and trace query
:dbcommand:`profile` data.
arg_name: field
operation: MongoDB\\Collection::find
interface: phpmethod
position: 6
---
arg_name: option
name: cursorType
type: integer
description: |
Indicates the type of cursor to use. The cursor types are
``MongoDB\Operation\Find`` class constants.
Must be either
``NON_TAILABLE``, ``TAILABLE``, or ``TAILABLE_AWAIT``. The default is
``NON_TAILABLE``.
interface: phpmethod
operation: MongoDB\\Collection::find
optional: true
position: 7
---
source:
file: apiargs-common-option.yaml
ref: maxTimeMS
operation: MongoDB\\Collection::find
position: 8
---
source:
file: apiargs-common-option.yaml
ref: readConcern
operation: MongoDB\\Collection::find
position: 9
---
source:
file: apiargs-common-option.yaml
ref: readPreference
pre: |
For use with MongoDB 3.0 and earlier.
operation: MongoDB\\Collection::find
position: 10
---
name: oplogReplay
type: boolean
optional: true
description: |
Internal use for replica sets. To use oplogReplay, you must include
the following condition in the filter:
.. code-block:: javascript
{ ts: { $gte: <timestamp> } }
The :php:`MongoDB\\BSON\\Timestamp <class.mongodb-bson-timestamp>`
class reference describes how to represent MongoDB's BSON
timestamp type with PHP.
arg_name: field
operation: MongoDB\\Collection::find
interface: phpmethod
position: 11
---
name: noCursorTimeout
type: boolean
optional: true
description: |
Prevents the server from timing out idle cursors after an inactivity
period (10 minutes).
arg_name: field
operation: MongoDB\\Collection::find
interface: phpmethod
position: 12
---
name: allowPartialResults
type: boolean
optional: true
description: |
For queries against a sharded collection, returns partial results from
the :program:`mongos` if some shards are unavailable instead of
throwing an error.
arg_name: field
operation: MongoDB\\Collection::find
interface: phpmethod
position: 13
---
source:
file: apiargs-common-option.yaml
ref: typeMap
operation: MongoDB\\Collection::find
position: 14
---
arg_name: option
name: modifiers
type: array
description: |
Meta-operators that modify the output or behavior of a query.
:manual:`Cursor Methods </reference/method/js-cursor`> describes the
query modification methods available in MongoDB.
interface: phpmethod
operation: MongoDB\\Collection::find
optional: true
position: 15
...
source:
ref: $filter
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::find
replacement:
verb: "query"
position: 1
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::find
position: 2
...
source:
file: apiargs-MongoDBCollection-method-find-option.yaml
ref: projection
operation: MongoDB\\Collection::findOne
position: 1
---
source:
file: apiargs-MongoDBCollection-method-find-option.yaml
ref: sort
operation: MongoDB\\Collection::findOne
position: 2
---
source:
file: apiargs-MongoDBCollection-method-find-option.yaml
ref: skip
operation: MongoDB\\Collection::findOne
position: 3
---
source:
file: apiargs-MongoDBCollection-method-find-option.yaml
ref: comment
operation: MongoDB\\Collection::findOne
position: 4
---
source:
file: apiargs-MongoDBCollection-method-find-option.yaml
ref: modifiers
operation: MongoDB\\Collection::findOne
position: 5
---
source:
file: apiargs-common-option.yaml
ref: maxTimeMS
operation: MongoDB\\Collection::findOne
position: 6
---
source:
file: apiargs-common-option.yaml
ref: readConcern
operation: MongoDB\\Collection::findOne
position: 7
---
source:
file: apiargs-common-option.yaml
ref: readPreference
pre: |
For use with MongoDB 3.0 and earlier.
operation: MongoDB\\Collection::findOne
position: 8
---
source:
file: apiargs-common-option.yaml
ref: typeMap
operation: MongoDB\\Collection::findOne
position: 9
...
\ No newline at end of file
source:
ref: $filter
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::findOne
replacement:
verb: "query"
position: 1
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::findOne
position: 2
...
source:
file: apiargs-MongoDBCollection-method-find-option.yaml
ref: projection
operation: MongoDB\\Collection::findOneAndDelete
position: 1
---
source:
file: apiargs-MongoDBCollection-method-find-option.yaml
ref: sort
operation: MongoDB\\Collection::findOneAndDelete
position: 2
---
source:
file: apiargs-common-option.yaml
ref: maxTimeMS
operation: MongoDB\\Collection::findOneAndDelete
position: 3
---
source:
file: apiargs-common-option.yaml
ref: writeConcern
operation: MongoDB\\Collection::findOneAndDelete
position: 4
...
\ No newline at end of file
source:
ref: $filter
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::findOneAndDelete
replacement:
verb: "query"
position: 1
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::findOneAndDelete
position: 2
...
source:
file: apiargs-MongoDBCollection-method-find-option.yaml
ref: projection
operation: MongoDB\\Collection::findOneAndReplace
position: 1
---
source:
file: apiargs-MongoDBCollection-method-find-option.yaml
ref: sort
operation: MongoDB\\Collection::findOneAndReplace
position: 2
---
source:
file: apiargs-common-option.yaml
ref: maxTimeMS
operation: MongoDB\\Collection::findOneAndReplace
position: 3
---
source:
file: apiargs-common-option.yaml
ref: bypassDocumentValidation
operation: MongoDB\\Collection::findOneAndReplace
position: 4
---
source:
file: apiargs-MongoDBCollection-method-findOneAndUpdate-option.yaml
ref: returnDocument
operation: MongoDB\\Collection::findOneAndReplace
position: 5
---
source:
file: apiargs-common-option.yaml
ref: upsert
operation: MongoDB\\Collection::findOneAndReplace
position: 6
---
source:
file: apiargs-common-option.yaml
ref: writeConcern
operation: MongoDB\\Collection::findOneAndReplace
position: 7
...
\ No newline at end of file
source:
ref: $filter
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::findOneAndReplace
replacement:
verb: "query"
optional: false
position: 1
---
arg_name: param
name: $replacement
type: array|object
description: |
The document to replace.
interface: phpmethod
operation: MongoDB\\Collection::findOneAndReplace
optional: false
position: 2
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::findOneAndReplace
position: 3
...
source:
file: apiargs-MongoDBCollection-method-find-option.yaml
ref: projection
operation: MongoDB\Collection::findOneAndUpdate
position: 1
---
source:
file: apiargs-MongoDBCollection-method-find-option.yaml
ref: sort
operation: MongoDB\Collection::findOneAndUpdate
position: 2
---
source:
file: apiargs-common-option.yaml
ref: maxTimeMS
operation: MongoDB\Collection::findOneAndUpdate
position: 3
---
source:
file: apiargs-common-option.yaml
ref: bypassDocumentValidation
operation: MongoDB\Collection::findOneAndUpdate
position: 4
---
arg_name: option
name: returnDocument
type: integer
description: |
Specifies whether to return the document before the {{event}}, or
after. ``returnDocument`` supports the following values:
- ``MongoDB\Operation\FindOneAndReplace::RETURN_DOCUMENT_BEFORE`` (*default*)
- ``MongoDB\Operation\FindOneAndReplace::RETURN_DOCUMENT_AFTER``
optional: true
replacement:
event: "update is applied"
interface: phpmethod
operation: MongoDB\Collection::findOneAndUpdate
position: 5
---
source:
file: apiargs-common-option.yaml
ref: upsert
operation: MongoDB\\Collection::findOneAndUpdate
position: 6
---
source:
file: apiargs-common-option.yaml
ref: writeConcern
operation: MongoDB\Collection::findOneAndUpdate
position: 7
...
\ No newline at end of file
source:
ref: $filter
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::findOneAndUpdate
replacement:
verb: "query"
optional: false
position: 1
---
arg_name: param
name: $update
type: array|object
description: |
Specifies the field and value combinations to update and any
relevant update operators. ``$update`` uses MongoDB's
:method:`update operators </reference/operator/update>`.
interface: phpmethod
operation: MongoDB\\Collection::findOneAndUpdate
optional: false
position: 2
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::findOneAndUpdate
position: 3
...
source:
file: apiargs-common-option.yaml
ref: bypassDocumentValidation
operation: MongoDB\\Collection::insertMany
position: 1
---
source:
file: apiargs-MongoDBCollection-method-bulkWrite-option.yaml
ref: ordered
operation: MongoDB\\Collection::insertMany
position: 2
---
source:
file: apiargs-common-option.yaml
ref: writeConcern
operation: MongoDB\\Collection::insertMany
position: 3
...
\ No newline at end of file
arg_name: param
name: $documents
type: array
description: |
The documents to insert into the collection.
interface: phpmethod
operation: MongoDB\\Collection::insertMany
optional: false
position: 1
---
source:
file: apiargs-common-param.yaml
ref: $options
operation: MongoDB\\Collection::insertMany
position: 2
...
\ No newline at end of file
source:
file: apiargs-common-option.yaml
ref: bypassDocumentValidation
operation: MongoDB\\Collection::insertOne
position: 1
---
source:
file: apiargs-common-option.yaml
ref: writeConcern
operation: MongoDB\\Collection::insertOne
position: 2
...
\ No newline at end of file
arg_name: param
name: $document
type: array|object
description: |
The document to insert into the collection.
interface: phpmethod
operation: MongoDB\\Collection::insertOne
optional: false
position: 1
---
source:
file: apiargs-common-param.yaml
ref: $options
operation: MongoDB\\Collection::insertOne
position: 2
...
\ No newline at end of file
source:
ref: maxTimeMS
file: apiargs-common-option.yaml
operation: MongoDB\\Collection::listIndexes
position: 1
...
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::listIndexes
position: 1
...
source:
file: apiargs-common-option.yaml
ref: bypassDocumentValidation
operation: MongoDB\\Collection::replaceOne
position: 1
---
source:
file: apiargs-common-option.yaml
ref: upsert
operation: MongoDB\\Collection::replaceOne
position: 2
---
source:
file: apiargs-common-option.yaml
ref: writeConcern
operation: MongoDB\\Collection::replaceOne
position: 3
...
\ No newline at end of file
source:
ref: $filter
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::replaceOne
replacement:
verb: "query"
optional: false
position: 1
---
arg_name: param
name: $replacement
type: array
description: |
The document to replace.
interface: phpmethod
operation: MongoDB\\Collection::replaceOne
optional: false
position: 2
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::replaceOne
position: 3
...
source:
file: apiargs-common-option.yaml
ref: bypassDocumentValidation
operation: MongoDB\\Collection::updateMany
position: 1
---
source:
file: apiargs-common-option.yaml
ref: upsert
operation: MongoDB\\Collection::updateMany
position: 2
---
source:
file: apiargs-common-option.yaml
ref: writeConcern
operation: MongoDB\\Collection::updateMany
position: 3
...
\ No newline at end of file
source:
ref: $filter
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::updateMany
replacement:
verb: "query"
optional: false
position: 1
---
source:
file: apiargs-MongoDBCollection-method-findOneAndUpdate-param.yaml
ref: $update
operation: MongoDB\\Collection::updateMany
optional: false
position: 2
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::updateMany
position: 3
...
source:
file: apiargs-common-option.yaml
ref: bypassDocumentValidation
operation: MongoDB\\Collection::updateOne
position: 1
---
source:
file: apiargs-common-option.yaml
ref: upsert
operation: MongoDB\\Collection::updateOne
position: 2
---
source:
file: apiargs-common-option.yaml
ref: writeConcern
operation: MongoDB\\Collection::updateOne
position: 3
...
\ No newline at end of file
source:
ref: $filter
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::updateOne
replacement:
verb: "query"
optional: false
position: 1
---
source:
file: apiargs-MongoDBCollection-method-findOneAndUpdate-param.yaml
ref: $update
operation: MongoDB\\Collection::updateOne
optional: false
position: 2
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::updateOne
position: 3
...
source:
file: apiargs-common-option.yaml
ref: readConcern
operation: MongoDB\\Collection::withOptions
description: |
The default read concern to use for collection operations. Defaults
to the original Collection's specified read concern.
---
source:
file: apiargs-common-option.yaml
ref: readPreference
operation: MongoDB\\Collection::withOptions
description: |
The default read preference to use for collection operations.
Defaults to the original Collection's read preference.
---
source:
file: apiargs-common-option.yaml
ref: typeMap
operation: MongoDB\\Collection::withOptions
description: |
Default type map for cursors and BSON documents. Defaults to the
original Collection's type map value.
---
source:
file: apiargs-common-option.yaml
ref: writeConcern
operation: MongoDB\\Collection::withOptions
description: |
The default write concern to use for collection operations. Defaults
to the original Collection's specified write concern.
...
\ No newline at end of file
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::withOptions
position: 1
...
source:
file: apiargs-common-option.yaml
ref: readPreference
operation: MongoDB\\Database::command
position: 1
---
source:
file: apiargs-common-option.yaml
ref: typeMap
operation: MongoDB\\Database::command
position: 2
...
arg_name: param
name: $command
type: string
description: |
The name of the :manual:`database command </reference/command>`
to execute.
interface: phpmethod
operation: MongoDB\\Database::command
optional: false
position: 1
---
source:
file: apiargs-common-param.yaml
ref: $options
operation: MongoDB\\Database::command
position: 2
...
source:
file: apiargs-common-option.yaml
ref: readConcern
operation: MongoDB\\Database::__construct
position: 1
---
source:
file: apiargs-common-option.yaml
ref: readPreference
operation: MongoDB\\Database::__construct
position: 2
---
source:
file: apiargs-common-option.yaml
ref: typeMap
operation: MongoDB\\Database::__construct
position: 3
---
source:
file: apiargs-common-option.yaml
ref: writeConcern
operation: MongoDB\\Database::__construct
position: 4
...
\ No newline at end of file
source:
file: apiargs-MongoDBCollection-method-construct-param.yaml
ref: $manager
operation: MongoDB\\Database::__construct
position: 1
---
source:
ref: $databaseName
file: apiargs-common-param.yaml
operation: MongoDB\\Database::__construct
position: 2
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Database::__construct
position: 2
...
\ No newline at end of file
arg_name: option
name: autoIndexId
type: boolean
description: |
*Default: true*. Specify false to disable the automatic creation of
an index on the _id field.
.. important::
For replica sets, do not set ``autoIndexId`` to ``false``.
.. deprecated:: 3.2. The ``autoIndexId`` option will be removed in MongoDB v3.4.
optional: true
interface: phpmethod
operation: MongoDB\\Database::createCollection
position: 1
---
arg_name: option
name: indexOptionDefaults
type: array
description: |
Allows users to specify a default configuration for indexes when
creating a collection.
The ``indexOptionDefaults`` option accepts a ``storageEngine`` document,
which should take the following form::
{ <storage-engine-name>: <options> }
Storage engine configurations specified when creating indexes are
validated and logged to the :term:`oplog` during replication to support
replica sets with members that use different storage engines.
optional: true
interface: phpmethod
operation: MongoDB\\Database::createCollection
position: 2
---
arg_name: option
name: capped
type: boolean
description: |
To create a capped collection, specify ``true``. If you specify
``true``, you must also set a maximum size in the ``size`` option.
optional: true
interface: phpmethod
operation: MongoDB\\Database::createCollection
position: 3
---
arg_name: option
name: size
type: integer
description: |
Specify a maximum size in bytes for a capped collection. Once a
capped collection reaches its maximum size, MongoDB removes the older
documents to make space for the new documents. The ``size`` option is
required for capped collections and ignored for other collections.
optional: true
interface: phpmethod
operation: MongoDB\\Database::createCollection
position: 4
---
arg_name: option
name: max
type: integer
description: |
The maximum number of documents allowed in the capped collection. The
``size`` option takes precedence over this limit. If a capped
collection reaches the ``size`` limit before it reaches the maximum
number of documents, MongoDB removes old documents. If you prefer to
use the ``max`` limit, ensure that the ``size`` limit, which is
required for a capped collection, is sufficient to contain the
maximum number of documents.
interface: phpmethod
operation: MongoDB\\Database::createCollection
optional: true
position: 5
---
arg_name: option
name: storageEngine
type: array
description: |
Available for the WiredTiger storage engine only.
Allows users to specify configuration to the storage engine on a
per-collection basis when creating a collection. The value of the
``storageEngine`` option should take the following form::
{ <storage-engine-name>: <options> }
Storage engine configurations specified when creating collections are
validated and logged to the :term:`oplog` during replication to support
replica sets with members that use different storage engines.
interface: phpmethod
operation: MongoDB\\Database::createCollection
optional: true
position: 6
---
arg_name: option
name: flags
type: integer
description: |
Available for the MMAPv1 storage engine only to set the
``usePowerOf2Sizes`` and ``noPadding`` flags.
The |php-library| provides constants that you can combine with a
:php:`bitwise OR operator <language.operators.bitwise>` to set the
flag values:
- ``MongoDB\Operation\CreateCollection::USE_POWER_OF_2_SIZES``: ``1``
- ``MongoDB\Operation\CreateCollection::NO_PADDING``: ``2``
Defaults to ``1``.
.. note::
MongoDB 3.0 and later ignores the ``usePowerOf2Sizes`` flag. See
:manual:`collMod </reference/command/collMod>` and
:manual:`db.createCollection()
</reference/method/db.createCollection>` for more information.
interface: phpmethod
operation: MongoDB\\Database::createCollection
optional: true
position: 7
---
arg_name: option
name: validator
type: array
description: |
Allows users to specify :manual:`validation rules or expressions
</core/document-validation>` for the collection. For more information,
see :manual:`Document Validation </core/document-validation>`
in the MongoDB manual.
The ``validator`` option takes an array that specifies the
validation rules or expressions. You can specify the expressions using
the same operators as MongoDB's :manual:`query operators </reference/operator/query>`
with the exception of :query:`$geoNear`, :query:`$near`,
:query:`$nearSphere`, :query:`$text`, and :query:`$where`.
.. note::
- Validation occurs during updates and inserts. Existing
documents do not undergo validation checks until modification.
- You cannot specify a validator for collections in the ``admin``,
``local``, and ``config`` databases.
- You cannot specify a validator for ``system.*`` collections.
operation: MongoDB\\Database::createCollection
interface: phpmethod
optional: true
position: 8
---
arg_name: option
name: validationLevel
type: string
description: |
Determines how strictly MongoDB applies the
validation rules to existing documents during an update.
.. list-table::
:header-rows: 1
* - ``validationLevel``
- Description
* - ``"off"``
- No validation for inserts or updates.
* - ``"strict"``
- **Default** Apply validation rules to all inserts and all
updates.
* - ``"moderate"``
- Apply validation rules to inserts and to updates on existing *valid*
documents. Do not apply rules to updates on existing *invalid*
documents.
interface: phpmethod
operation: MongoDB\\Database::createCollection
optional: true
position: 9
---
arg_name: option
name: validationAction
type: string
description: |
Determines whether to ``error`` on invalid documents or just ``warn``
about the violations but allow invalid documents to be inserted.
.. important::
Validation of documents only applies to those documents as
determined by the ``validationLevel``.
.. list-table::
:header-rows: 1
* - ``validationAction``
- Description
* - ``"error"``
- **Default** Documents must pass validation before the write occurs.
Otherwise, the write operation fails.
* - ``"warn"``
- Documents do not have to pass validation. If the document fails
validation, the write operation logs the validation failure.
interface: phpmethod
operation: MongoDB\\Database::createCollection
optional: true
position: 10
---
source:
file: apiargs-common-option.yaml
ref: maxTimeMS
operation: MongoDB\\Database::createCollection
position: 11
---
source:
file: apiargs-common-option.yaml
ref: typeMap
operation: MongoDB\\Database::createCollection
position: 12
...
\ No newline at end of file
source:
file: apiargs-common-param.yaml
ref: $collectionName
operation: MongoDB\\Database::createCollection
position: 1
optional: false
---
source:
file: apiargs-common-param.yaml
ref: $options
operation: MongoDB\\Database::createCollection
position: 2
optional: true
...
\ No newline at end of file
source:
file: apiargs-common-option.yaml
ref: typeMap
operation: MongoDB\\Database::dropCollection
position: 1
...
\ No newline at end of file
source:
file: apiargs-common-param.yaml
ref: $collectionName
operation: MongoDB\\Database::dropCollection
position: 1
optional: false
---
source:
file: apiargs-common-param.yaml
ref: $options
operation: MongoDB\\Database::dropCollection
position: 2
optional: true
...
\ No newline at end of file
source:
file: apiargs-common-option.yaml
ref: typeMap
operation: MongoDB\\Database::dropCollection
position: 1
...
\ No newline at end of file
source:
file: apiargs-common-param.yaml
ref: $collectionName
operation: MongoDB\\Database::dropCollection
position: 1
optional: false
---
source:
file: apiargs-common-param.yaml
ref: $options
operation: MongoDB\\Database::dropCollection
position: 2
optional: true
...
\ No newline at end of file
source:
file: apiargs-common-param.yaml
ref: $collectionName
operation: MongoDB\\Database::__get
position: 1
...
\ No newline at end of file
source:
file: apiargs-common-option.yaml
ref: readConcern
operation: MongoDB\\Database::listCollections
position: 1
---
source:
file: apiargs-common-option.yaml
ref: readPreference
operation: MongoDB\\Database::listCollections
position: 2
---
source:
file: apiargs-common-option.yaml
ref: typeMap
operation: MongoDB\\Database::listCollections
position: 3
---
source:
file: apiargs-common-option.yaml
ref: writeConcern
operation: MongoDB\\Database::listCollections
position: 4
...
\ No newline at end of file
source:
file: apiargs-common-param.yaml
ref: $options
operation: MongoDB\\Database::listCollections
position: 1
optional: true
...
\ No newline at end of file
source:
file: apiargs-common-option.yaml
ref: readConcern
operation: MongoDB\\Database::selectCollection
position: 1
---
source:
file: apiargs-common-option.yaml
ref: readPreference
operation: MongoDB\\Database::selectCollection
position: 2
---
source:
file: apiargs-common-option.yaml
ref: typeMap
operation: MongoDB\\Database::selectCollection
position: 3
---
source:
file: apiargs-common-option.yaml
ref: writeConcern
operation: MongoDB\\Database::selectCollection
position: 4
...
\ No newline at end of file
source:
file: apiargs-common-param.yaml
ref: $collectionName
operation: MongoDB\\Database::selectCollection
position: 1
optional: false
---
source:
file: apiargs-common-param.yaml
ref: $options
operation: MongoDB\\Database::selectCollection
position: 2
...
\ No newline at end of file
source:
file: apiargs-common-option.yaml
ref: readConcern
operation: MongoDB\\Database::withOptions
description: |
The default read concern to use for database operations. Defaults
to the original Databases's specified read concern.
---
source:
file: apiargs-common-option.yaml
ref: readPreference
operation: MongoDB\\Database::withOptions
description: |
The default read preference to use for database operations.
Defaults to the original Database's read preference.
---
source:
file: apiargs-common-option.yaml
ref: typeMap
operation: MongoDB\\Database::withOptions
description: |
Default type map for cursors and BSON documents. Defaults to the
original Database's type map value.
---
source:
file: apiargs-common-option.yaml
ref: writeConcern
operation: MongoDB\\Database::withOptions
description: |
The default write concern to use for database operations. Defaults
to the original Database's specified write concern.
...
\ No newline at end of file
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Database::withOptions
position: 1
...
arg_name: option
name: readConcern
type: :php:`MongoDB\\Driver\\ReadConcern <class.mongodb-driver-readconcern>`
description: |
The default read concern to use for {{resource}} operations. Defaults
to the Client's specified read concern.
interface: phpmethod
operation: selectCollection
optional: true
position: 1
replacement:
resource: "collection"
---
arg_name: option
description: |
The default read preference to use for {{resource}} operations.
Defaults to the {{parent}}'s read preference.
interface: phpmethod
name: readPreference
operation: selectCollection
optional: true
position: 2
type: :php:`MongoDB\\Driver\\ReadPreference <class.mongodb-driver-readpreference>`
replacement:
resource: "collection"
parent: "Client"
---
arg_name: option
description: |
Default type map for cursors and BSON documents. Defaults to the
{{parent}}'s type map.
interface: phpmethod
name: typeMap
operation: selectCollection
optional: true
position: 3
type: array
replacement:
parent: "Client"
---
arg_name: option
name: writeConcern
type: :php:`MongoDB\\Driver\\WriteConcern <class.mongodb-driver-writeconcern>`
description: |
The default write concern to use for {{resource}} operations. Defaults
to the {{parent}}'s specified write concern.
interface: phpmethod
operation: selectCollection
optional: true
position: 4
replacement:
resource: "collection"
parent: "Client"
---
arg_name: option
name: maxTimeMS
description: |
The cumulative time limit in milliseconds for processing operations on
the cursor. MongoDB aborts the operation at the earliest following
:term:`interrupt point`.
interface: phpmethod
operation: listDatabases
type: integer
optional: true
position: 5
---
arg_name: option
name: bypassDocumentValidation
type: boolean
description: |
If ``true``, allows the write operation to circumvent document level
validation. This only applies when using the :pipeline:`$out` stage.
Document validation requires MongoDB v3.2 or later: if you are using
an earlier version of MongoDB, this option will be ignored.
interface: phpmethod
operation: aggregate
optional: true
position: 6
---
arg_name: option
name: upsert
type: boolean
description: |
When true, {{role}} creates a new document if no document
matches the query. If a document matches the query, {{role}}
performs an update. To avoid multiple upserts, ensure that the query
fields are uniquely indexed.
The default is ``false``.
optional: true
interface: phpmethod
operation: MongoDB\\Collection::findOneAndUpdate
position: 7
...
\ No newline at end of file
arg_name: param
name: $databaseName
type: string
description: |
The name of the database{{select}}.
interface: phpmethod
operation: selectCollection
optional: false
replacement:
select: " to select"
position: 1
---
arg_name: param
name: $collectionName
type: string
description: |
The name of the collection{{select}}.
interface: phpmethod
operation: selectCollection
optional: false
replacement:
select: " to select"
position: 2
---
arg_name: param
name: $options
type: array
description: |
An array specifying the desired options.
interface: phpmethod
operation: selectCollection
optional: true
position: 3
---
arg_name: param
name: $filter
type: array|object
description: |
The filter criteria that specifies the documents to {{verb}}.
interface: phpmethod
operation: count
optional: false
position: 4
replacement:
verb: "count"
...
.. code-block:: php
<?php
$database = new MongoDB\Client;
$collection = $database->selectCollection('users','restaurants');
$newUser = $collection->insertOne(
[
'username' => 'admin',
'email' => 'admin@example.com',
'name' => 'Anna Bennett'
],
);
echo "<pre>";
var_dump($newUser);
The output would resemble:
.. code-block:: none
object(MongoDB\InsertOneResult)#13 (3) {
["writeResult":"MongoDB\InsertOneResult":private]=>
object(MongoDB\Driver\WriteResult)#12 (9) {
["nInserted"]=>
int(1)
["nMatched"]=>
int(0)
["nModified"]=>
int(0)
["nRemoved"]=>
int(0)
["nUpserted"]=>
int(0)
["upsertedIds"]=>
array(0) {
}
["writeErrors"]=>
array(0) {
}
["writeConcernError"]=>
NULL
["writeConcern"]=>
array(4) {
["w"]=>
NULL
["wmajority"]=>
bool(false)
["wtimeout"]=>
int(0)
["journal"]=>
NULL
}
}
["insertedId":"MongoDB\InsertOneResult":private]=>
object(MongoDB\BSON\ObjectID)#11 (1) {
["oid"]=>
string(24) "577282631f417d1823121691"
}
["isAcknowledged":"MongoDB\InsertOneResult":private]=>
bool(true)
}
\ No newline at end of file
ref: _bson-deserialization
content: |
.. note::
{{method}} does not
yet support a ``typeMap`` option for BSON deserialization of the
returned document.
Classes implementing
:php:`MongoDB\\BSON\\Persistable <class.mongodb-bson-persistable>`
are deserialized according to the :php:`persistance
<mongodb.persistance>` specification.
...
\ No newline at end of file
ref: bson-deserialization-findOneAndDelete
source:
file: extracts-bson-deserialization-base.yaml
ref: _bson-deserialization
replacement:
method: ":phpmethod:`MongoDB\\Collection::findOneAndDelete`"
---
ref: bson-deserialization-findOneAndReplace
source:
file: extracts-bson-deserialization-base.yaml
ref: _bson-deserialization
replacement:
method: ":phpmethod:`MongoDB\\Collection::findOneAndReplace`"
---
ref: bson-deserialization-findOneAndUpdate
source:
file: extracts-bson-deserialization-base.yaml
ref: _bson-deserialization
replacement:
method: ":phpmethod:`MongoDB\\Collection::findOneAndUpdate`"
...
===================
MongoDB PHP Library
===================
.. default-domain:: mongodb
The |php-library| provides a high-level abstraction
around the lower-level `PHP Driver <https://php.net/mongodb>`_, also
known as the ``mongodb`` extension.
While the ``mongodb`` extension provides a limited API for executing
commands, queries, and write operations, the |php-library|
implements an API similar to that of the `legacy PHP driver
<http://php.net/manual/en/book.mongo.php>`_. The library contains
abstractions for client, database, and collection objects, and provides
methods for CRUD operations and common commands such as index and
collection management.
If you are developing a PHP application with MongoDB, you should consider
using this library, or another high-level abstraction, instead of the
extension alone.
For additional information about the MongoDB PHP Library and the
``mongodb`` extension, see the `Architecture Overview
<http://php.net/manual/en/mongodb.overview.php>`_ article in the
extension documentation. `Derick Rethans <http://derickrethans.nl/>`_
has also written a series of blog posts entitled *New MongoDB Drivers
for PHP and HHVM*:
- `Part One: History <https://derickrethans.nl/new-drivers.html>`_
- `Part Two: Architecture
<https://derickrethans.nl/new-drivers-part2.html>`_
- `Part Three: Cursor Behaviour
<https://derickrethans.nl/new-drivers-part3-cursor.html>`_
API Reference
-------------
Generated API reference documentation for the library is available at:
`http://mongodb.github.io/mongo-php-library/api
<http://mongodb.github.io/mongo-php-library/api>`_
New to MongoDB?
---------------
If you are a new MongoDB user, these links should help you become more familiar
with MongoDB and introduce some of the concepts and terms you will encounter in
this documentation:
- `Introduction to CRUD operations in MongoDB
<http://docs.mongodb.org/manual/core/crud-introduction/>`_
- `What is a MongoDB document?
<http://docs.mongodb.org/manual/core/document/>`_
- `MongoDB's *dot notation* for accessing document properties
<http://docs.mongodb.org/manual/core/document/#dot-notation>`_
- `ObjectId: MongoDB's document identifier
<http://docs.mongodb.org/manual/reference/object-id/>`_
.. class:: hidden
.. toctree::
:titlesonly:
Installation </tutorial/install-php-library>
/tutorial
/upgrade
/reference
.. /getting-started
\ No newline at end of file
=========
Reference
=========
.. default-domain:: mongodb
.. toctree::
:titlesonly:
/reference/bson
/reference/class/MongoDBClient
/reference/class/MongoDBDatabase
/reference/class/MongoDBCollection
====
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 <http://bsonspec.org/>`_.
By default, the |php-library| returns BSON documents as
``MongoDB\Model\BSONDocument`` objects and BSON arrays as
``MongoDB\Model\BSONArray`` objects. ``MongoDB\Model\BSONDocument`` and
``MongoDB\Model\BSONArray`` extend PHP's
:php:`ArrayObject <arrayobject>` class and implement the MongoDB PHP
driver's :php:`MongoDB\\BSON\\Serializable <mongodb-bson-serializable>`
and :php:`MongoDB\\BSON\\Unserializable <mongodb-bson-unserializable>`
interfaces.
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 applies to any supporting methods and selected classes by default.
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',
]
Serialization and deserialization of PHP variables into MongoDB
---------------------------------------------------------------
``Persistable`` Classes
~~~~~~~~~~~~~~~~~~~~~~~
The PHP driver's :php:`persistence <mongodb.persistence>` specification
specifies how classes implementing :php:`MongoDB\\BSON\\Persistable
<mongodb-bson-persistable>` are serialized and deserialized, and is
analogous to PHP's :php:`Serializable interface <class.serializable>`.
The PHP :php:`driver <mongodb>` automatically handles serialization and
deserialization for classes implementing ``MongoDB\BSON\Persistable``
without requiring the use of the ``typeMap`` option.
Consider the following class definition:
.. code-block:: php
<?php
class Person implements MongoDB\BSON\Persistable
{
private $id;
private $name;
private $createdAt;
public function __construct($name)
{
$this->id = new MongoDB\BSON\ObjectID;
$this->name = (string) $name;
// Get current time in milliseconds since the epoch
$msec = floor(microtime(true) * 1000);
$this->createdAt = new MongoDB\BSON\UTCDateTime($msec);
}
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 constructs a ``Person`` object, inserts it into the
database, and reads it back as an object of the same type:
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->demo->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 <mongodb-bson-persistable>` may only be used
for root and embedded BSON documents. BSON arrays are not supported.
Emulating the Legacy Driver
~~~~~~~~~~~~~~~~~~~~~~~~~~~
The legacy :php:`mongo extension <mongo>` 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 reindex the array.
The |php-library|'s ``MongoDB\Model\BSONDocument`` and ``MongoDB\Model\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
<?php
$client = new MongoDB\Client(
null,
[],
['typeMap' => [
'root' => 'array', 'document' => 'array', 'array' => 'array'
],
]
);
$document = $client->demo->zips->findOne(
['_id' => '94301'],
['typeMap' => [
'root' => 'array', 'document' => 'array', 'array' => 'array'
],
]
);
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"
}
=====================
MongoDB\\Client Class
=====================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpclass:: MongoDB\\Client
Serves as an entry point for the |php-library|. ``MongoDB\Client``
is the preferred class for connecting to a MongoDB server or cluster
of servers and serves as a gateway for accessing individual
databases and collections. ``MongoDB\Client`` is analogous to the
driver's :php:`MongoDB\\Driver\\Manager <mongodb-driver-manager>`
class, which it composes.
Methods
-------
.. toctree::
:titlesonly:
/reference/method/MongoDBClient__construct
/reference/method/MongoDBClient__get
/reference/method/MongoDBClient-dropDatabase
/reference/method/MongoDBClient-listDatabases
/reference/method/MongoDBClient-selectCollection
/reference/method/MongoDBClient-selectDatabase
=========================
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 PHP extension's
``Manager`` class, select a collection from the |php-library|'s
:phpclass:`MongoDB\\Client` or :phpclass:`MongoDB\\Database`
classes, or create a collection from an existing collection using the
:phpmethod:`withOptions <MongoDB\\Collection::withOptions>` clone method.
:phpclass:`MongoDB\\Collection` supports the :php:`readConcern
<mongodb-driver-readconcern>`, :php:`readPreference
<mongodb-driver-readpreference>`, :php:`typeMap
<mongodb.persistence.php#mongodb.persistence.typemaps>`, and
:php:`writeConcern <mongodb-driver-writeconcern>` options.
If you omit an option, the collection inherits the value from the
Manager constructor argument or the Database object used to select
the collection.
Operations within the ``Collection`` class
inherit the Collection's options.
The :phpmethod:`MongoDB\\Collection::aggregate` method (when not
using a cursor), :phpmethod:`MongoDB\\Collection::distinct`, and
:manual:`findAndModify </reference/command/findAndModify>` helpers do not
support a ``typeMap`` option due to a driver limitation.
:phpmethod:`MongoDB\\Collection::aggregate`,
:phpmethod:`MongoDB\\Collection::distinct`,
:phpmethod:`MongoDB\\Collection::findOneAndReplace`,
:phpmethod:`MongoDB\\Collection::findOneAndUpdate`, and
:phpmethod:`MongoDB\\Collection::findOneAndDelete`
return BSON documents as `stdClass` objects and 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-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-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-getNamespace
/reference/method/MongoDBCollection-insertMany
/reference/method/MongoDBCollection-insertOne
/reference/method/MongoDBCollection-listIndexes
/reference/method/MongoDBCollection-replaceOne
/reference/method/MongoDBCollection-updateMany
/reference/method/MongoDBCollection-updateOne
/reference/method/MongoDBCollection-withOptions
=======================
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 PHP extension's
``Manager`` class or select a database from the |php-library|'s
:phpclass:`MongoDB\\Client`
class.
:phpclass:`MongoDB\\Database` supports the :php:`readConcern
<mongodb-driver-readconcern>`, :php:`readPreference
<mongodb-driver-readpreference>`, :php:`typeMap
<mongodb.persistence.php#mongodb.persistence.typemaps>`, and
:php:`writeConcern <mongodb-driver-writeconcern>` options.
If you omit an option, the database inherits the value from the
Manager constructor argument or the Client object used to select
the database.
Operations within the ``Database`` class
:phpmethod:`MongoDB\\Database::command` method
inherit the Database's options.
.. _database-methods:
Methods
-------
.. toctree::
:titlesonly:
/reference/method/MongoDBDatabase__get
/reference/method/MongoDBDatabase__construct
/reference/method/MongoDBDatabase-command
/reference/method/MongoDBDatabase-createCollection
/reference/method/MongoDBDatabase-drop
/reference/method/MongoDBDatabase-dropCollection
/reference/method/MongoDBDatabase-getDatabaseName
/reference/method/MongoDBDatabase-listCollections
/reference/method/MongoDBDatabase-selectCollection
/reference/method/MongoDBDatabase-withOptions
===============================
MongoDB\\Client::dropDatabase()
===============================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Client::dropDatabase($databaseName, $options)
Drop a MongoDB database.
.. code-block:: php
function dropDatabase($databaseName, array $options [])
:phpmethod:`MongoDB\\Client::dropDatabase` has the following parameters:
.. include:: /includes/apiargs/MongoDBClient-method-dropDatabase-param.rst
``dropDatabase`` supports the following values for the ``$options`` array:
.. include:: /includes/apiargs/MongoDBClient-method-dropDatabase-option.rst
Output
------
Returns an array or object containing the result document.
Example
-------
The following example drops the ``demo`` database:
.. code-block:: php
<?php
$client = new MongoDB\Client;
$result = $client->dropDatabase('demo');
var_dump($result);
The ``dropDatabase`` operation would return an object similar to:
.. code-block:: php
object(MongoDB\Model\BSONDocument)#8 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["dropped"]=>
string(4) "demo"
["ok"]=>
float(1)
}
}
.. seealso::
- :phpmethod:`MongoDB\\Client::drop`
- :manual:`dropDatabase() command reference
</reference/command/dropDatabase>` in the MongoDB manual.
================================
MongoDB\\Client::listDatabases()
================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Client::listDatabases($options)
Lists the available databases.
.. code-block:: php
function listDatabases(array $options = []): MongoDB\Model\DatabaseInfoIterator
:phpmethod:`MongoDB\\Client::listDatabases` has the following parameters:
.. include:: /includes/apiargs/MongoDBClient-method-listDatabases-param.rst
``listDatabases`` supports the following values for the ``$options`` array:
.. include:: /includes/apiargs/MongoDBClient-method-listDatabases-option.rst
Output
------
Information for all databases on the :program:`mongod`, replica set,
or sharded cluster to which you are connected. The returned elements are
``MongoDB\Model\DatabaseInfo`` objects.
Example
-------
The following example lists all databases on the server:
.. code-block:: php
<?php
$client = new MongoDB\Client;
foreach ($client->listDatabases() as $databaseInfo) {
var_dump($databaseInfo);
}
The above example would output something similar to:
.. code-block:: php
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)
}
.. seealso::
:manual:`listDatabases() command reference in the MongoDB
manual </reference/command/listDatabases>`
===================================
MongoDB\\Client::selectCollection()
===================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Client::selectCollection($databaseName, $collectionName, $options)
Selects a collection on the :program:`mongod` to which your application
is connected.
.. code-block:: php
function selectCollection($databaseName, $collectionName, array $options = [])
:phpmethod:`MongoDB\\Client::selectCollection` has the following parameters:
.. include:: /includes/apiargs/common-param.rst
The following table describes the options that
:phpmethod:`MongoDB\\Client::selectCollection` can accept.
.. include:: /includes/apiargs/common-option.rst
Output
------
Returns a :phpclass:`MongoDB\\Collection` object.
Example
-------
The following example selects the ``users`` collection in the ``demo``
database:
.. code-block:: php
<?php
$client = new MongoDB\Client;
$collection = $client->selectCollection('demo', 'users');
The following examples selects the ``users`` collection in the ``demo``
database with a custom read preference:
.. code-block:: php
$client = new MongoDB\Client;
$collection = $client->selectCollection(
'demo',
'users',
[
'readPreference' => new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY),
]
);
.. seealso::
- :phpmethod:`Collection::__construct`
- :phpmethod:`MongoDB\\Client::__get`
=================================
MongoDB\\Client::selectDatabase()
=================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Client::selectDatabase($databaseName, $options)
Selects a database on the :program:`mongod` instance to which your
application is connected.
.. code-block:: php
function selectDatabase($databaseName array $options = []): MongoDB\Database
:phpmethod:`MongoDB\\Client::selectDatabase` has the following parameters:
.. include:: /includes/apiargs/MongoDBClient-method-selectDatabase-param.rst
The following table describes the options that
:phpmethod:`MongoDB\\Client::selectDatabase` can accept.
.. include:: /includes/apiargs/MongoDBClient-method-selectDatabase-option.rst
Output
------
Returns a :phpclass:`MongoDB\\Database` object.
Example
-------
The following example selects the ``demo`` database:
.. code-block:: php
<?php
$client = new MongoDB\Client;
$db = $client->selectDatabase('demo');
The following examples selects the ``demo`` database with a custom read
preference:
.. code-block:: php
<?php
$client = new MongoDB\Client;
$db = $client->selectDatabase(
'demo',
[
'readPreference' => new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY),
]
);
.. seealso::
- :phpmethod:`Collection::__construct`
- :phpmethod:`MongoDB\\Client::__get`
==============================
MongoDB\\Client::__construct()
==============================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Client::__construct($uri, $uriOptions, $driverOptions)
Constructs a new :phpclass:`Client <MongoDB\\Client>` instance.
.. code-block:: php
function __construct($uri = 'mongodb://localhost:27017', array $uriOptions = [], array $driverOptions = [])
:phpmethod:`MongoDB\\Client::__construct` has the following parameters:
.. include:: /includes/apiargs/MongoDBClient-method-construct-param.rst
Examples
--------
If you do not specify a ``$uri`` value, the driver connects to a
standalone :program:`mongod` on ``localhost`` via port ``27017``. The
following example demonstrates how to connect to a replica set
with a custom
read preference:
.. code-block:: php
<?php
$client = new MongoDB\Client(
'mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet',
[
'readPreference' => 'secondaryPreferred'
]
);
By default, the |php-library| deserializes BSON documents and arrays
as ``MongoDB\Model\BSONDocument`` and ``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 <mongo>`.
.. code-block:: php
<?php
$client = new MongoDB\Client(
null,
[],
[ 'typeMap' => [
'root' => 'array', 'document' => 'array', 'array' => 'array'
],
]
);
========================
MongoDB\\Client::__get()
========================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Client::__get($databaseName)
Select a MongoDB database.
.. code-block:: php
function __get($databaseName): MongoDB\Database
:phpmethod:`MongoDB\\Client::__get` has the following parameters:
.. include:: /includes/apiargs/MongoDBClient-method-get-param.rst
Behavior
--------
The selected database inherits options such as read preference and
type mapping from the :phpclass:`Client <MongoDB\\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 ``demo`` and ``another-app``
databases:
.. code-block:: php
<?php
$client = new MongoDB\Client;
$demo = $client->demo;
$anotherApp = $client->{'another-app'};
.. seealso::
- :phpmethod:`MongoDB\\Client::selectDatabase`
- :php:`Property Overloading <oop5.overloading>` in the PHP Manual.
================================
MongoDB\\Collection::aggregate()
================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::aggregate($pipeline, $options)
Executes an :manual:`aggregation framework pipeline
</core/aggregation-pipeline/>` operation on the collection.
.. code-block:: php
function aggregate(array $pipeline, array $options = []): Traversable
:phpmethod:`MongoDB\\Collection::aggregate` has the following
parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-aggregate-param.rst
:phpmethod:`MongoDB\\Collection::aggregate` supports the following
options:
.. include:: /includes/apiargs/MongoDBCollection-method-aggregate-option.rst
.. _php-agg-method-output:
Output
------
:phpmethod:`MongoDB\\Collection::aggregate`'s return value depends on
the MongoDB server version and whether the ``useCursor`` option is
specified. If ``useCursor`` is true,
:phpmethod:`MongoDB\\Collection::aggregate` returns a
``MongoDB\Driver\Cursor`` object. If ``useCursor`` is false,
:phpmethod:`MongoDB\\Collection::aggregate` returns an
``ArrayIterator`` that wraps the ``result`` array from the command
response document.
.. note::
BSON deserialization of inline aggregation results (i.e. not using a
command cursor) does not yet support a ``typeMap`` option. Classes
implementing :php:`MongoDB\\BSON\\Persistable
<mongodb-bson-persistable>` will still be deserialized according to
the :php:`Persistence <mongodb.persistence.deserialization>`
specification.
.. todo: add examples
.. seealso::
- :manual:`aggregate command reference
</reference/command/aggregate>` in the MongoDB manual and
- :manual:`Aggregation Pipeline </core/aggregation-pipeline>`
documentation in the MongoDB Manual.
================================
MongoDB\\Collection::bulkWrite()
================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::bulkWrite($operations, $options)
Executes multiple write operations.
.. code-block:: php
function bulkWrite(array $operations, array $options = []): MongoDB\BulkWriteResult
:phpmethod:`MongoDB\\Collection::bulkWrite` has the following
parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-bulkWrite-param.rst
:phpmethod:`MongoDB\\Collection::bulkWrite` supports the following
options:
.. include:: /includes/apiargs/MongoDBCollection-method-bulkWrite-option.rst
.. todo: add output and examples
.. seealso::
- :phpmethod:`deleteMany <MongoDB\\Collection::deleteMany>`
- :phpmethod:`deleteOne <MongoDB\\Collection::deleteOne>`
- :phpmethod:`insertOne <MongoDB\\Collection::insertOne>`
- :phpmethod:`replaceOne <MongoDB\\Collection::replaceOne>`
- :phpmethod:`updateMany <MongoDB\\Collection::updateMany>`
- :phpmethod:`updateOne <MongoDB\\Collection::updateOne>`
- :doc:`/tutorial/crud`
============================
MongoDB\\Collection::count()
============================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::count($filter, $options)
Counts the number of documents that match filter criteria.
.. code-block:: php
function count($filter = [], array $options = []): integer
:phpmethod:`MongoDB\\Collection::count` has the following
parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-count-param.rst
:phpmethod:`MongoDB\\Collection::count` supports the following
options:
.. include:: /includes/apiargs/MongoDBCollection-method-count-option.rst
.. todo: add output and examples
.. seealso::
- :manual:`count command reference </reference/command/count>`
in the MongoDB manual.
================================
MongoDBCollection::createIndex()
================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::createIndex($key, $options)
Create an index for the collection.
.. code-block:: php
function createIndex($key, array $options = []): string
``createIndex()`` accepts the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-createIndex-param.rst
The ``$options`` parameter accepts all index options that your
MongoDB version supports. MongoDB 3.2 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 </reference/command/createIndexes>`
command reference in the MongoDB manual.
Output
------
Returns the name of the created index as a string.
Examples
--------
Create a Compound Index
~~~~~~~~~~~~~~~~~~~~~~~
The following operation creates a :manual:`compound index
</core/index-compound>` on the ``borough`` and ``cuisine`` fields
in the ``restaurants`` collection.
.. code-block:: php
<?php
$database = new MongoDB\Client;
$collection = $database->selectCollection('example','restaurants');
$keys = ['borough' => 1, 'cuisine' => 1];
$indexString = $collection->createIndex($keys, ['name' => 'compound']);
var_dump($indexString);
The output would resemble the following:
.. code-block:: none
string(8) "compound"
Create a Partial Index
~~~~~~~~~~~~~~~~~~~~~~
The following operation adds a :manual:`partial index
</core/index-parital>` on the ``borough`` field in the ``restaurants``
collection in the ``example`` database. The partial index indexes only
fields where the ``borough`` field exists.
.. code-block:: php
<?php
$database = new MongoDB\Client;
$collection = $database->selectCollection('example','restaurants');
$indexString = $collection->createIndex(
['borough' => 1],
['partialFilterExpression'=>
['borough'=>
['$exists'=>true]
]]);
var_dump($indexString);
The output would resemble::
string(9) "borough_1"
.. seealso::
- :phpmethod:`MongoDB\\Collection::createIndexes`
- :doc:`/tutorial/indexes`
- :manual:`createIndexes </reference/command/createIndexes>`
command reference in the MongoDB manual
- :manual:`Index documentation </indexes>`
==================================
MongoDBCollection::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): string[]
``createIndex()`` has one parameter: ``$indexes``, which is an array
or object.
Each element in the ``$indexes`` array|object must have a
"``key`` document" that specifies the fields to index and the
array direction or type. You can then specify index options as
additional key-value pairs in that element.
For example, the following ``$indexes`` parameter creates an ascending
unique index on the ``username`` field:
.. code-block:: none
[ 'key' => ['username => 1 '], 'unique' => true ],
The following ``$indexes`` parameter creates a 2dsphere index on the ``loc`` field and
specifies a custom index name:
.. code-block:: none
[ 'key' => [ 'loc' => '2dsphere'], 'name' => 'geo_index' ],
You can specify any index options that your MongoDB version
supports. MongoDB 3.2 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 </reference/command/createIndexes>`
command reference in the MongoDB manual.
Output
------
Returns the name of the created indexes as an array of strings.
Example
-------
The following creates two indexes on the ``restaurants`` collection in
the ``example`` database. One index is a compound index on the
``borough`` and ``cuisine`` fields and the other is 2dsphere index
on the ``location`` field with a custom name.
.. code-block:: php
<?php
$database = new MongoDB\Client;
$collection = $database->selectCollection('example','restaurants');
$index = $collection->createIndexes(
[
[ 'key' => [ 'borough' => 1, 'cuisine' => 1] ],
[ 'key' => [ 'location' => '2dsphere'], 'name' => 'geo_index'],
]);
var_dump($index);
The output would resemble the following::
array(2) {
[0]=>
string(19) "borough_1_cuisine_1"
[1]=>
string(9) "geo_index"
}
.. seealso::
- :phpmethod:`MongoDB\\Collection::createIndex`
- :doc:`/tutorial/indexes`
- :manual:`createIndexes </reference/command/createIndexes>`
command reference in the MongoDB manual
- :manual:`Index documentation </indexes>`
=================================
MongoDB\\Collection::deleteMany()
=================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::deleteMany($filter, $options)
Deletes all documents that match the filter criteria.
.. code-block:: php
function deleteMany($filter, array $options = []): MongoDB\DeleteResult
:phpmethod:`MongoDB\\Collection::deleteMany` has the following
parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-deleteMany-param.rst
:phpmethod:`MongoDB\\Collection::deleteMany` supports the following
options:
.. include:: /includes/apiargs/MongoDBCollection-method-deleteMany-option.rst
Output
------
Returns a ``MongoDB\DeleteResult`` object.
Example
-------
The following operation deletes all of the documents in the ``users``
collection that have ``ny`` as the value for the ``state`` field:
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->demo->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)
.. seealso::
- :phpmethod:`MongoDB\\Collection::bulkWrite`
- :phpmethod:`MongoDB\\Collection::deleteOne`
- :doc:`/tutorial/crud`
- :manual:`delete command reference </reference/command/delete`
in the MongoDB manual
\ No newline at end of file
================================
MongoDB\\Collection::deleteOne()
================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::deleteOne($filter, $options)
Deletes at most one document that matches the filter criteria. If
multiple documents match the filter criteria,
:phpmethod:`MongoDB\\Collection::deleteOne` deletes the :term:`first
<natural order>` matching document.
.. code-block:: php
function deleteOne($filter, array $options = []): MongoDB\DeleteResult
:phpmethod:`MongoDB\\Collection::deleteMany` has the following
parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-deleteOne-param.rst
:phpmethod:`MongoDB\\Collection::deleteMany` supports the following
options:
.. include:: /includes/apiargs/MongoDBCollection-method-deleteOne-option.rst
Output
------
Returns a ``MongoDB\DeleteResult`` object.
Example
-------
The following operation deletes the first documents in the ``users``
collection that has ``ny`` as the value for the ``state`` field:
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->demo->users;
$collection->drop();
$collection->insertOne(['name' => 'Bob', 'state' => 'ny']);
$collection->insertOne(['name' => 'Alice', 'state' => 'ny']);
$deleteResult = $collection->deleteOne(['state' => 'ny']);
printf("Deleted %d document(s)\n", $deleteResult->getDeletedCount());
The output would then resemble::
Deleted 1 document(s)
.. seealso::
- :phpmethod:`MongoDB\\Collection::bulkWrite`
- :phpmethod:`MongoDB\\Collection::deleteMany`
- :doc:`/tutorial/crud`
- :manual:`delete command reference </reference/command/delete`
in the MongoDB manual
\ No newline at end of file
===============================
MongoDB\\Collection::distinct()
===============================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::distinct()
Finds the distinct values for a specified field across the collection.
.. code-block:: php
function distinct($fieldName, $filter = [], array $options = []): mixed[]
``distinct`` has the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-distinct-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-distinct-option.rst
Output
------
Returns an array of the distinct values.
Examples
--------
Return Distinct Values for a Field
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The following example identifies the distinct values for the
``borough`` field in the ``restaurants`` collection in the
``example`` database.
.. code-block:: php
<?php
$database = new MongoDB\Client;
$collection = $database->selectCollection('example','restaurants');
$distinct = $collection->distinct('borough');
var_dump($distinct);
The output would resemble::
array(6) {
[0]=>
string(5) "Bronx"
[1]=>
string(8) "Brooklyn"
[2]=>
string(9) "Manhattan"
[3]=>
string(7) "Missing"
[4]=>
string(6) "Queens"
[5]=>
string(13) "Staten Island"
}
Return Distinct Values Using a Filter
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The following example identifies the distinct values for the
``cuisine`` field in the ``restaurants`` collection in the ``example``
database for documents where the ``borough`` is ``Queens``:
.. code-block:: php
<?php
$database = new MongoDB\Client;
$collection = $database->selectCollection('example','restaurants');
$distinct = $collection->distinct('cuisine', ['borough'=>'Queens']);
var_dump($distinct);
The output would then resemble::
array(75) {
[0]=>
string(6) "Afghan"
[1]=>
string(7) "African"
[2]=>
string(9) "American "
[3]=>
string(8) "Armenian"
[4]=>
string(5) "Asian"
[5]=>
string(10) "Australian"
[6]=>
string(15) "Bagels/Pretzels"
[7]=>
string(6) "Bakery"
[8]=>
string(11) "Bangladeshi"
[9]=>
string(8) "Barbecue"
[10]=>
string(55) "Bottled beverages, including water, sodas, juices, etc."
[11]=>
string(9) "Brazilian"
[12]=>
string(4) "Cafe"
[13]=>
string(16) "Café/Coffee/Tea"
[14]=>
string(5) "Cajun"
[15]=>
string(9) "Caribbean"
[16]=>
string(7) "Chicken"
[17]=>
string(7) "Chinese"
[18]=>
string(13) "Chinese/Cuban"
[19]=>
string(16) "Chinese/Japanese"
[20]=>
string(11) "Continental"
[21]=>
string(6) "Creole"
[22]=>
string(5) "Czech"
[23]=>
string(12) "Delicatessen"
[24]=>
string(6) "Donuts"
[25]=>
string(16) "Eastern European"
[26]=>
string(8) "Egyptian"
[27]=>
string(7) "English"
[28]=>
string(8) "Filipino"
[29]=>
string(6) "French"
[30]=>
string(17) "Fruits/Vegetables"
[31]=>
string(6) "German"
[32]=>
string(5) "Greek"
[33]=>
string(10) "Hamburgers"
[34]=>
string(16) "Hotdogs/Pretzels"
[35]=>
string(31) "Ice Cream, Gelato, Yogurt, Ices"
[36]=>
string(6) "Indian"
[37]=>
string(10) "Indonesian"
[38]=>
string(5) "Irish"
[39]=>
string(7) "Italian"
[40]=>
string(8) "Japanese"
[41]=>
string(13) "Jewish/Kosher"
[42]=>
string(30) "Juice, Smoothies, Fruit Salads"
[43]=>
string(6) "Korean"
[44]=>
string(64) "Latin (Cuban, Dominican, Puerto Rican, South & Central American)"
[45]=>
string(13) "Mediterranean"
[46]=>
string(7) "Mexican"
[47]=>
string(14) "Middle Eastern"
[48]=>
string(8) "Moroccan"
[49]=>
string(25) "Not Listed/Not Applicable"
[50]=>
string(18) "Nuts/Confectionary"
[51]=>
string(5) "Other"
[52]=>
string(9) "Pakistani"
[53]=>
string(16) "Pancakes/Waffles"
[54]=>
string(8) "Peruvian"
[55]=>
string(5) "Pizza"
[56]=>
string(13) "Pizza/Italian"
[57]=>
string(6) "Polish"
[58]=>
string(10) "Portuguese"
[59]=>
string(7) "Russian"
[60]=>
string(6) "Salads"
[61]=>
string(10) "Sandwiches"
[62]=>
string(30) "Sandwiches/Salads/Mixed Buffet"
[63]=>
string(7) "Seafood"
[64]=>
string(9) "Soul Food"
[65]=>
string(18) "Soups & Sandwiches"
[66]=>
string(12) "Southwestern"
[67]=>
string(7) "Spanish"
[68]=>
string(5) "Steak"
[69]=>
string(5) "Tapas"
[70]=>
string(7) "Tex-Mex"
[71]=>
string(4) "Thai"
[72]=>
string(7) "Turkish"
[73]=>
string(10) "Vegetarian"
[74]=>
string(29) "Vietnamese/Cambodian/Malaysia"
}
.. seealso::
- :manual:`distinct </reference/command/distinct>` command
reference in the MongoDB manual.
===========================
MongoDB\\Collection::drop()
===========================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::drop
Drops the collection.
.. code-block:: php
function drop(array $options = []): array|object
``drop()`` supports the following parameter:
.. include:: /includes/apiargs/MongoDBCollection-method-drop-param.rst
The ``$options`` parameter supports the following option:
.. include:: /includes/apiargs/MongoDBCollection-method-drop-option.rst
Output
------
Returns the command result document as an array or object, depending
on the ``typeMap`` specification.
Example
-------
The following operation drops the ``restaurants`` collection in the
``example`` database:
.. code-block:: php
<?php
$database = new MongoDB\Client;
$collection = $database->selectCollection('example','restaurants');
$output = $collection->drop();
var_dump($output);
The output would resemble::
object(MongoDB\Model\BSONDocument)#9 (1) {
["storage":"ArrayObject":private]=>
array(3) {
["ns"]=>
string(19) "example.restaurants"
["nIndexesWas"]=>
int(3)
["ok"]=>
float(1)
}
}
.. seealso::
- :phpmethod:`MongoDB\\Database::dropCollection`
- :manual:`drop </reference/command/drop>` command reference in
the MongoDB manual.
================================
MongoDB\\Collection::dropIndex()
================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::dropIndex($indexName, $options)
Drops an index from the collection.
.. code-block:: php
function dropIndex($indexName, array $options = []): array|object
``dropIndex()`` supports the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-dropIndex-param.rst
The ``$options`` parameter supports the following option:
.. include:: /includes/apiargs/MongoDBCollection-method-dropIndex-option.rst
Output
------
Returns the command result document as an array or object, depending
on the ``typeMap`` specification.
Example
-------
The following drops an indexes with name ``borough_1`` from the
``restaurants`` collection in the ``example`` database:
.. code-block:: php
<?php
$database = new MongoDB\Client;
$collection = $database->selectCollection('example','restaurants');
$index = $collection->dropIndex( "borough_1" );
var_dump($index);
The output would resemble the following::
object(MongoDB\Model\BSONDocument)#9 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["nIndexesWas"]=>
int(2)
["ok"]=>
float(1)
}
}
.. seealso::
- :phpmethod:`MongoDB\\Collection::dropIndexes`
- :doc:`/tutorial/indexes`
- :manual:`dropIndexes </reference/command/dropIndexes>` command
references in the MongoDB manual.
- :manual:`Index documentation </indexes>`
==================================
MongoDB\\Collection::dropIndexes()
==================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::dropIndexes($options)
Drops **all indexes** in the collection.
.. code-block:: php
function dropIndexes(array $options = []): array|object
``dropIndexes()`` supports the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-dropIndex-param.rst
The ``$options`` parameter supports the following option:
.. include:: /includes/apiargs/MongoDBCollection-method-dropIndex-option.rst
Output
------
Returns the command result document as an array or object, depending
on the ``typeMap`` specification.
Example
-------
The following drops all indexes from the ``restaurants`` collection in
the ``example`` database:
.. code-block:: php
<?php
$database = new MongoDB\Client;
$collection = $database->selectCollection('example','restaurants');
$response = $collection->dropIndexes();
var_dump($response);
The output would resemble the following::
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)
}
}
.. seealso::
- :phpmethod:`MongoDB\\Collection::dropIndex`
- :doc:`/tutorial/indexes`
- :manual:`dropIndexes </reference/command/dropIndexes>` command
references in the MongoDB manual.
- :manual:`Index documentation </indexes>`
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment