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>`
===========================
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
``find()`` supports 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
Output
------
Returns a ``MongoDB\Driver\Cursor`` object.
Examples
--------
The following example finds restaurants based on the ``cuisine`` and
``borough`` fields and uses a :manual:`projection
</tutorial/project-fields-from-query-results>` to limit the fields
that are returned. It also limits the results to 5 documents.
.. code-block:: php
$database = new MongoDB\Client;
$collection = $database->selectCollection('example','restaurants');
$restaurants = $collection->find(
[ 'cuisine' => 'Italian', 'borough' => 'Manhattan' ],
[ 'limit' => 5,
'projection' => [
'name' => 1, 'borough' => 1, 'cuisine' => 1,
],
]
);
foreach ($restaurants as $restaurant) {
var_dump($restaurant);
};
The output would resemble:
.. code-block:: none
object(MongoDB\Model\BSONDocument)#10 (1) {
["storage":"ArrayObject":private]=>
array(4) {
["_id"]=>
object(MongoDB\BSON\ObjectID)#8 (1) {
["oid"]=>
string(24) "576023c6b02fa9281da3f983"
}
["borough"]=>
string(9) "Manhattan"
["cuisine"]=>
string(7) "Italian"
["name"]=>
string(23) "Isle Of Capri Resturant"
}
}
object(MongoDB\Model\BSONDocument)#13 (1) {
["storage":"ArrayObject":private]=>
array(4) {
["_id"]=>
object(MongoDB\BSON\ObjectID)#12 (1) {
["oid"]=>
string(24) "576023c6b02fa9281da3f98d"
}
["borough"]=>
string(9) "Manhattan"
["cuisine"]=>
string(7) "Italian"
["name"]=>
string(18) "Marchis Restaurant"
}
}
object(MongoDB\Model\BSONDocument)#8 (1) {
["storage":"ArrayObject":private]=>
array(4) {
["_id"]=>
object(MongoDB\BSON\ObjectID)#10 (1) {
["oid"]=>
string(24) "576023c6b02fa9281da3f99b"
}
["borough"]=>
string(9) "Manhattan"
["cuisine"]=>
string(7) "Italian"
["name"]=>
string(19) "Forlinis Restaurant"
}
}
object(MongoDB\Model\BSONDocument)#12 (1) {
["storage":"ArrayObject":private]=>
array(4) {
["_id"]=>
object(MongoDB\BSON\ObjectID)#13 (1) {
["oid"]=>
string(24) "576023c6b02fa9281da3f9a8"
}
["borough"]=>
string(9) "Manhattan"
["cuisine"]=>
string(7) "Italian"
["name"]=>
string(22) "Angelo Of Mulberry St."
}
}
object(MongoDB\Model\BSONDocument)#10 (1) {
["storage":"ArrayObject":private]=>
array(4) {
["_id"]=>
object(MongoDB\BSON\ObjectID)#8 (1) {
["oid"]=>
string(24) "576023c6b02fa9281da3f9b4"
}
["borough"]=>
string(9) "Manhattan"
["cuisine"]=>
string(7) "Italian"
["name"]=>
string(16) "V & T Restaurant"
}
}
.. seealso::
- :phpmethod:`MongoDB\\Collection::findOne`
- :manual:`find </reference/command/find>` command reference
in the MongoDB manual
==============================
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
``findOne()`` supports 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
Output
------
Returns the :term:`first document <natural order>` that matches the
query or ``null`` if no document matches the query.
Examples
--------
The following example finds a restaurant based on the ``cuisine`` and
``borough`` fields and uses a :manual:`projection
</tutorial/project-fields-from-query-results>` to limit the fields
that are returned.
.. code-block:: php
$database = new MongoDB\Client;
$collection = $database->selectCollection('example','restaurants');
$restaurants = $collection->findOne(
[ 'cuisine' => 'Italian', 'borough' => 'Manhattan'],
[ 'limit' => 5,
'projection' => [
'name' => 1, 'borough' => 1, 'cuisine' => 1,
],
]
);
foreach ($restaurants as $restaurant) {
var_dump($restaurant);
};
The output would resemble:
.. code-block:: none
object(MongoDB\BSON\ObjectID)#11 (1) {
["oid"]=>
string(24) "576023c6b02fa9281da3f983"
}
string(9) "Manhattan"
string(7) "Italian"
string(23) "Isle Of Capri Resturant"
.. seealso::
- :phpmethod:`MongoDB\\Collection::findOne`
- :manual:`find </reference/command/find>` command reference
in the MongoDB manual
=======================================
MongoDB\\Collection::findOneAndDelete()
=======================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::findOneAndDelete
Finds a single document and deletes it.
.. code-block:: php
function findOneAndDelete($filter = [], array $options = []): object|null
``findOne()`` supports the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-findOneAndDelete-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-findOneAndDelete-option.rst
.. include:: /includes/extracts/bson-deserialization-findOneAndDelete.rst
Output
------
Returns the document that was deleted. If no document matched the
filter, the returned document is ``null``.
Examples
--------
The following example deletes the document with ``restaurant_id`` of
``40375376`` from the ``restaurants`` collection in the ``example``
database:
.. code-block:: php
<?php
$database = new MongoDB\Client;
$collection = $database->selectCollection('example','restaurants');
$deletedRestaurant = $collection->findOneAndDelete(
[ 'restaurant_id' => '40375376' ],
[ 'projection' => [ 'name' => 1,
'borough' => 1,
'restaurant_id' => 1
]
]
);
The output would resemble:
.. code-block:: none
object(stdClass)#14 (4) {
["_id"]=>
object(MongoDB\BSON\ObjectID)#11 (1) {
["oid"]=>
string(24) "576023c6b02fa9281da3fad9"
}
["borough"]=>
string(9) "Manhattan"
["name"]=>
string(15) "Agra Restaurant"
["restaurant_id"]=>
string(8) "40375376"
}
.. seealso::
- :phpmethod:`MongoDB\\Collection::findOneAndUpdate`
- :phpmethod:`MongoDB\\Collection::findOneAndReplace`
- :manual:`findAndModify </reference/command/findAndModify>`
command reference in the MongoDB manual
========================================
MongoDB\\Collection::findOneAndReplace()
========================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::findOneAndReplace
Finds a single document matching the query and replaces it.
.. code-block:: php
function findOneAndReplace($filter, $replacement, array $options = []): object|null
``findOneAndReplace()`` supports the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-findOneAndReplace-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-findOneAndReplace-option.rst
.. include:: /includes/extracts/bson-deserialization-findOneAndReplace.rst
Output
------
By default, returns the original document. To return the *new*
document, use the ``returnDocument`` option. If no document matched
the query, returns ``null``.
Examples
--------
Consider the following document in the ``restaurants`` collection in
the ``example`` database:
.. code-block:: javascript
{
"_id" : ObjectId("576023c7b02fa9281da4139e"),
"address" : {
"building" : "977",
"coord" : [
-74.06940569999999,
40.6188443
],
"street" : "Bay Street",
"zipcode" : "10305"
},
"borough" : "Staten Island",
"cuisine" : "French",
"grades" : [
{
"date" : ISODate("2014-08-15T00:00:00Z"),
"grade" : "A",
"score" : 7
},
{
"date" : ISODate("2014-02-13T00:00:00Z"),
"grade" : "A",
"score" : 5
},
{
"date" : ISODate("2013-06-07T00:00:00Z"),
"grade" : "A",
"score" : 11
}
],
"name" : "Zest",
"restaurant_id" : "41220906"
}
The following operation replaces the document with ``restaurant_id :
41220906`` with the new specified document:
.. code-block:: php
<?php
$collection = $database->selectCollection('example','restaurants');
$updateRestaurant = $collection->findOneAndReplace(
[ 'restaurant_id' => '41220906' ],
[ 'Borough' => 'Staten Island',
'cuisine' => 'Italian',
'grades' => [],
'name' => 'Staten Island Pastaria',
'restaurant_id' => '999999999',
],
[ 'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER ]
);
var_dump($updateRestaurant)
The ``var_dump()`` output contains the new document, as in the following::
object(stdClass)#14 (6) {
["_id"]=>
object(MongoDB\BSON\ObjectID)#11 (1) {
["oid"]=>
string(24) "576023c7b02fa9281da4139e"
}
["borough"]=>
string(13) "Staten Island"
["cuisine"]=>
string(7) "Italian"
["grades"]=>
array(0) {
}
["name"]=>
string(22) "Staten Island Pastaria"
["restaurant_id"]=>
string(9) "999999999"
}
.. seealso::
- :phpmethod:`MongoDB\\Collection::findOneAndDelete`
- :phpmethod:`MongoDB\\Collection::findOneAndUpdate`
- :manual:`findAndModify </reference/command/findAndModify>`
command reference in the MongoDB manual
=======================================
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
``findOneAndUpdate()`` supports 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
.. include:: /includes/extracts/bson-deserialization-findOneAndUpdate.rst
Output
------
Returns either the original or the updated document, depending on the
specified value for the ``returnDocument`` option. By default, the
original document is returned.
Examples
--------
The following operation updates the building number of the restaurant
with ``restaurant_id : 40361708`` in the ``restaurants`` collection in
the ``example`` database to ``761``:
.. code-block:: php
<?php
$database = new MongoDB\Client;
$collection = $database->selectCollection('example','restaurants');
$updateRestaurant = $collection->findOneAndUpdate(
[ 'restaurant_id' => '40361708' ],
[ '$set' => ['address.building' => '761']],
[ 'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER ]
);
var_dump($updateRestaurant)
.. seealso::
- :phpmethod:`MongoDB\\Collection::findOneAndDelete`
- :phpmethod:`MongoDB\\Collection::findOneAndReplace`
- :manual:`findAndModify </reference/command/findAndModify>` command reference
in the MongoDB manual
========================================
MongoDB\\Collection::getCollectionName()
========================================
.. default-domain:: mongodb
Definition
----------
.. phpmethod:: MongoDB\\Collection::getCollectionName()
Returns the name of the current collection.
.. code-block:: php
function getCollectionName(): string
Example
-------
The following returns the name of the collection assigned to the
``$collection`` variable
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->demo->zips;
echo $collection->getCollectionName();
The ``$collection`` variable uses the :phpmethod:`constructor
<MongoDB\\Collection::__construct>` method to select the ``zips``
collection in the ``demo`` database, as such, the printed output would
resemble:
.. code-block:: none
zips
======================================
MongoDB\\Collection::getDatabaseName()
======================================
.. default-domain:: mongodb
Definition
----------
.. phpmethod:: MongoDB\\Collection::getDatabaseName()
Returns the name of the current database.
.. code-block:: php
function getDatabaseName(): string
Example
-------
The following returns the name of the database of the collection
assigned to the ``$collection`` variable
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->demo->zips;
echo $collection->getDatabaseName();
The ``$collection`` variable uses the :phpmethod:`constructor
<MongoDB\\Collection::__construct>` method to select the ``zips``
collection in the ``demo`` database, as such, the printed output would
resemble:
.. code-block:: none
demo
===================================
MongoDB\\Collection::getNamespace()
===================================
.. default-domain:: mongodb
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
Example
-------
The following returns the namespace of the collection
assigned to the ``$collection`` variable
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->demo->zips;
echo $collection->getNamespace();
The ``$collection`` variable uses the :phpmethod:`constructor
<MongoDB\\Collection::__construct>` method to select the ``zips``
collection in the ``demo`` database, as such, the printed output would
resemble:
.. code-block:: none
demo.zips
=================================
MongoDB\\Collection::insertMany()
=================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::insertMany
Inserts one document.
.. code-block:: php
function insertMany(array $documents, array $options = []): MongoDB\InsertManyResult
``insertMany()`` supports 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
Output
------
Returns a ``MongoDB\InsertManyResult`` object.
Example
-------
.. start-crud-include
The following operation inserts two documents into the ``users``
collection in the ``example`` database:
.. code-block:: php
<?php
$database = new MongoDB\Client;
$collection = $database->selectCollection('users','restaurants');
$newUsers = $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", $newUsers->getInsertedCount());
var_dump($newUsers->getInsertedIds());
The output would 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
.. seealso::
- :phpmethod:`MongoDB\\Collection::bulkWrite`
- :phpmethod:`MongoDB\\Collection::insertOne`
- :doc:`/tutorial/crud`
- :manual:`insert </reference/command/insert>` command reference
in the MongoDB manual
================================
MongoDB\\Collection::insertOne()
================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::insertOne
Inserts one document.
.. code-block:: php
function insertOne($document, array $options = []): MongoDB\InsertOneResult
``insertOne()`` supports 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
Output
------
Returns a ``MongoDB\InsertOneResult`` object.
Example
-------
The following operation inserts a document into the ``users``
collection in the ``example`` database:
.. include:: /includes/example-insertOne.rst
.. seealso::
- :phpmethod:`MongoDB\\Collection::bulkWrite`
- :phpmethod:`MongoDB\\Collection::insertMany`
- :doc:`/tutorial/crud`
- :manual:`insert </reference/command/insert>` command reference
in the MongoDB manual
==================================
MongoDB\\Collection::listIndexes()
==================================
.. default-domain:: mongodb
.. contents::
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::listIndexes($options)
Returns information for all indexes for the collection.
.. code-block:: php
function listIndexes(array $options = []): MongoDB\Model\IndexInfoIterator
:phpmethod:`MongoDB\\Collection::listIndexes` supports the
following parameter:
.. include:: /includes/apiargs/MongoDBCollection-method-listIndexes-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-listIndexes-option.rst
Output
------
Elements in the returned iterator are ``MongoDB\Model\IndexInfo``
objects.
Example
-------
The following lists information about the indexes on the collection
assigned to the ``$collection`` variable
.. code-block:: php
<?php
$database = new MongoDB\Client;
$collection = $database->selectCollection('example','restaurants');
$indexes = $collection->listIndexes();
foreach ($indexes 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(19) "example.restaurants"
}
object(MongoDB\Model\IndexInfo)#12 (4) {
["v"]=>
int(1)
["key"]=>
array(1) {
["cuisine"]=>
float(-1)
}
["name"]=>
string(10) "cuisine_-1"
["ns"]=>
string(19) "example.restaurants"
}
object(MongoDB\Model\IndexInfo)#8 (4) {
["v"]=>
int(1)
["key"]=>
array(1) {
["borough"]=>
float(1)
}
["name"]=>
string(9) "borough_1"
["ns"]=>
string(19) "example.restaurants"
}
.. seealso::
- :doc:`/tutorial/indexes`
- :manual:`listIndexes command </reference/command/listIndexes>` in the MongoDB manual.
- :manual:`Index documentation </core/indexes>` in the MongoDB manual.
- `MongoDB Specification: Enumerating Collections
<https://github.com/mongodb/specifications/blob/master/source/enumerate-indexes.rst>`_
=================================
MongoDB\\Collection::replaceOne()
=================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::replaceOne
Replaces at most one document that matches the filter.
.. code-block:: php
function replaceOne($filter, $replacement, array $options = []): MongoDB\UpdateResult
``replaceOne()`` supports 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
Output
------
Returns a ``MongoDB\UpdateResult`` object.
Example
-------
The following operation replaces the document with ``restaurant_id``
``40356068`` in the ``restaurants`` collection in the ``example`` database:
.. code-block:: php
<?php
$database = new MongoDB\Client;
$collection = $database->selectCollection('users','restaurants');
$replacement = $collection->replaceOne(
[ 'restaurant_id' => '40356068'],
[
'name' => 'New Restaurant',
'restaurant_id' => '99988877',
'borough' => 'Queens',
'cuisine' => 'Cafe',
'grades' => [],
]
);
var_dump($replacement);
The output would resemble:
.. code-block:: none
object(MongoDB\UpdateResult)#13 (2) {
["writeResult":"MongoDB\UpdateResult":private]=>
object(MongoDB\Driver\WriteResult)#12 (9) {
["nInserted"]=>
int(0)
["nMatched"]=>
int(1)
["nModified"]=>
int(1)
["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
}
}
["isAcknowledged":"MongoDB\UpdateResult":private]=>
bool(true)
}
.. seealso::
- :phpmethod:`MongoDB\\Collection::bulkWrite`
- :phpmethod:`MongoDB\\Collection::updateMany`
- :phpmethod:`MongoDB\\Collection::updateOne`
- :doc:`/tutorial/crud`
- :manual:`update </reference/command/update>` command reference
in the MongoDB manual
=================================
MongoDB\\Collection::updateMany()
=================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::updateMany
Updates all documents that match the filter criteria.
.. code-block:: php
function updateMany($filter, $update, array $options = []): MongoDB\UpdateResult
``updateMany()`` supports 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
Output
------
Returns a ``MongoDB\UpdateResult`` object.
Examples
--------
The following operation adds a an ``active`` field to all of the documents
with ``borough: Queens`` with value ``true``:
.. code-block:: php
$database = new MongoDB\Client;
$collection = $database->selectCollection('example','restaurants');
$update = $collection->updateMany(
[ 'borough' => 'Queens'],
[
'$set' => [
'active' => 'True'
]
]
);
var_dump($update);
The output would then resemble::
object(MongoDB\UpdateResult)#13 (2) {
["writeResult":"MongoDB\UpdateResult":private]=>
object(MongoDB\Driver\WriteResult)#12 (9) {
["nInserted"]=>
int(0)
["nMatched"]=>
int(5656)
["nModified"]=>
int(5656)
["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
}
}
["isAcknowledged":"MongoDB\UpdateResult":private]=>
bool(true)
}
.. seealso::
- :phpmethod:`MongoDB\\Collection::bulkWrite`
- :phpmethod:`MongoDB\\Collection::replaceOne`
- :phpmethod:`MongoDB\\Collection::updateOne`
- :doc:`/tutorial/crud`
- :manual:`update </reference/command/update>` command reference
in the MongoDB manual.
================================
MongoDB\\Collection::updateOne()
================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::updateOne
Finds a single document matching the query and updates it.
.. code-block:: php
function updateOne($filter, $update, array $options = []): MongoDB\UpdateResult
``updateOne()`` supports 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
Output
------
Returns a ``MongoDB\UpdateResult`` object.
Examples
--------
The following operation updates the ``name`` of the restaurant with
``restaurant_id: 40356151`` to "Brunos on Astoria":
.. code-block:: php
$database = new MongoDB\Client;
$collection = $database->selectCollection('example','restaurants');
$update = $collection->updateOne(
[ 'restaurant_id' => '40356151'],
[
'$set' => [
'name' => 'Brunos on Astoria'
]
]
);
var_dump($update);
The output would then resemble::
object(MongoDB\UpdateResult)#13 (2) {
["writeResult":"MongoDB\UpdateResult":private]=>
object(MongoDB\Driver\WriteResult)#12 (9) {
["nInserted"]=>
int(0)
["nMatched"]=>
int(1)
["nModified"]=>
int(1)
["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
}
}
["isAcknowledged":"MongoDB\UpdateResult":private]=>
bool(true)
}
.. seealso::
- :phpmethod:`MongoDB\\Collection::bulkWrite`
- :phpmethod:`MongoDB\\Collection::replaceOne`
- :phpmethod:`MongoDB\\Collection::updateMany`
- :doc:`/tutorial/crud`
- :manual:`update </reference/command/update>` command reference
in the MongoDB manual.
==================================
MongoDB\\Collection::withOptions()
==================================
.. default-domain:: mongodb
Definition
----------
.. phpmethod:: MongoDB\\Collection::withOptions($options)
Returns a clone of the collection, but with different options.
.. code-block:: php
function withOptions(array $options = []): MongoDB\Collection
:phpmethod:`MongoDB\\Collection::withOptions` supports the
following parameter:
.. include:: /includes/apiargs/MongoDBCollection-method-withOptions-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-withOptions-option.rst
Example
-------
The following example creates a new collection based on the
``restaurants`` collection in the ``example`` database with a custom
read preference:
.. code-block:: php
<?php
$database = new MongoDB\Client;
$sourceCollection = $database->selectCollection('example','restaurants');
$newCollection = $sourceCollection->withOptions([
'readPreference' => new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY),
]);
.. seealso::
- :phpmethod:`MongoDB\\Collection::__construct`
==================================
MongoDB\\Collection::__construct()
==================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::__construct($manager, $databaseName, $collectionName, $options)
Constructs a new :phpclass:`Collection <MongoDB\\Collection>` instance.
.. code-block:: php
function __construct(MongoDB\Driver\Manager $manager, $databaseName, $collectionName, array $options = [])
:phpmethod:`MongoDB\\Collection::__construct` has the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-construct-param.rst
:phpmethod:`MongoDB\\Collection::__construct` supports the following
options:
.. include:: /includes/apiargs/common-option.rst
If you construct the Collection explicitly, the Collection inherits
any options from the ``Manager`` object. If you select the Collection
from a :phpclass:`Client <MongoDB\\Client>` or :phpclass:`Database
<MongoDB\\Database>` object, the Collection inherits its options
from that object.
.. todo: add an example
.. seealso::
- :phpmethod:`MongoDB\\Collection::withOptions`
- :phpmethod:`MongoDB\\Database::selectCollection`
============================
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 </reference/command>` on the database.
.. code-block:: php
function command($command, array $options = []): MongoDB\Driver\Cursor
:phpmethod:`MongoDB\\Database::command` has the following parameters:
.. include:: /includes/apiargs/MongoDBDatabase-method-command-param.rst
``command`` supports the following options:
.. include:: /includes/apiargs/MongoDBDatabase-method-command-option.rst
Example
-------
The following operation creates a new user in the database using
the :dbcommand:`createUser` command:
.. code-block:: php
$database = (new MongoDB\Client)->example;
$newUser = $database->command(
[
'createUser' => 'admin',
'pwd' => 'admin123',
'roles' => [
'readWrite'
]
]
);
var_dump($newUser);
The output would resemble::
object(MongoDB\Driver\Cursor)#10 (2) {
["cursor"]=>
array(17) {
["stamp"]=>
int(0)
["is_command"]=>
bool(true)
["sent"]=>
bool(true)
["done"]=>
bool(false)
["end_of_event"]=>
bool(false)
["in_exhaust"]=>
bool(false)
["has_fields"]=>
bool(false)
["query"]=>
object(stdClass)#9 (3) {
["createUser"]=>
string(5) "admin"
["pwd"]=>
string(8) "admin123"
["roles"]=>
array(1) {
[0]=>
string(9) "readWrite"
}
}
["fields"]=>
object(stdClass)#3 (0) {
}
["read_preference"]=>
array(2) {
["mode"]=>
int(1)
["tags"]=>
array(0) {
}
}
["flags"]=>
int(0)
["skip"]=>
int(0)
["limit"]=>
int(1)
["count"]=>
int(1)
["batch_size"]=>
int(0)
["ns"]=>
string(12) "example.$cmd"
["current_doc"]=>
object(stdClass)#8 (1) {
["ok"]=>
float(1)
}
}
["server_id"]=>
int(1)
}
.. seealso::
- :doc:`/tutorial/commands`
- :manual:`Database Commands </reference/command>` in the
MongoDB manual
=====================================
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 ``createCollection()``
method, or using :dbcommand:`create` in the :program:`mongo` shell.
Explicitly creating collections enables you to create
:manual:`capped collections </core/capped-collections>`, specify
:manual:`document validation criteria </core/document-validation>`,
or configure your storage engine or indexing options.
:phpmethod:`MongoDB\\Database::createCollection` has the following
parameters:
.. include:: /includes/apiargs/MongoDBDatabase-method-createCollection-param.rst
The ``$options`` parameter accepts 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/command/create>` reference in the MongoDB manual for
compatibility considerations.
Output
------
Returns the command result document as an array.
Example
-------
The following example creates a ``users`` collection in the ``demo``
database with document validation criteria:
.. code-block:: php
$db = (new MongoDB\Client)->demo;
$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)
}
}
.. seealso::
:manual:`create </reference/command/create>` command reference in
the MongoDB manual
=========================
MongoDB\\Database::drop()
=========================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Database::drop
Drops the database.
.. code-block:: php
function dropCollection($collectionName, array $options = []): array|object
:phpmethod:`MongoDB\\Database::drop` has the following
parameters:
.. include:: /includes/apiargs/MongoDBDatabase-method-drop-param.rst
The ``$options`` parameter accepts the following options:
.. include:: /includes/apiargs/MongoDBDatabase-method-drop-option.rst
Output
------
Returns the command result document as an array.
Example
-------
The following example drops the ``demo`` database:
.. code-block:: php
$db = (new MongoDB\Client)->demo;
$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) "demo"
["ok"]=>
float(1)
}
}
.. seealso::
- :phpmethod:`MongoDB\\Client::dropDatabase`
- :manual:`dropDatabase </reference/command/dropDatabase>` command
reference in the MongoDB manual
===================================
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
:phpmethod:`MongoDB\\Database::dropCollection` has the following
parameters:
.. include:: /includes/apiargs/MongoDBDatabase-method-dropCollection-param.rst
The ``$options`` parameter accepts the following options:
.. include:: /includes/apiargs/MongoDBDatabase-method-dropCollection-option.rst
Output
------
Returns the command result document as an array.
Example
-------
The following example drops the ``users`` collection in the ``demo``
database:
.. code-block:: php
$db = (new MongoDB\Client)->demo;
$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) "demo.users"
["nIndexesWas"]=>
int(1)
["ok"]=>
float(1)
}
}
.. seealso::
- :phpmethod:`MongoDB\\Collection::drop`
- :manual:`drop </reference/command/drop>` command reference in
the MongoDB manual
====================================
MongoDB\\Database::getDatabaseName()
====================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Database::getDatabaseName
Drops the database.
.. code-block:: php
function getDatabaseName(): string
Output
------
Returns the name of the database as a string.
Example
-------
The following example gets the name of the database from the ``$db``
variable:
.. code-block:: php
$db = (new MongoDB\Client)->demo;
echo $db->getDatabaseName();
The output would then resemble::
demo
====================================
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
:phpmethod:`MongoDB\\Database::listCollections` has the following
parameters:
.. include:: /includes/apiargs/MongoDBDatabase-method-listCollections-param.rst
The ``$options`` parameter accepts the following options:
.. include:: /includes/apiargs/MongoDBDatabase-method-listCollections-option.rst
Output
------
Returns information for all collections in the database. The elements
in the returned iterator are ``MongoDB\Model\CollectionInfo`` objects.
Example
-------
The following example lists all of the collections in the ``example``
database:
.. code-block:: php
<?php
$database = (new MongoDB\Client)->example;
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)#11 (2) {
["name"]=>
string(5) "users"
["options"]=>
array(0) {
}
}
object(MongoDB\Model\CollectionInfo)#3 (2) {
["name"]=>
string(6) "restos"
["options"]=>
array(0) {
}
}
.. seealso::
- :manual:`listCollections </reference/command/listCollections`
command reference in the MongoDB manual.
- MongoDB Specification `Enumerating Collections
<https://github.com/mongodb/specifications/blob/master/source/enumerate-collections.rst>`_
\ No newline at end of file
=====================================
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. The collection inherits
options such as read preference and type map from the Database object
unless otherwise specified in the ``$options`` parameter.
.. code-block:: php
function selectCollection($collectionName, array $options = []): MongoDB\Collection
:phpmethod:`MongoDB\\Database::selectCollection` has the following
parameters:
.. include:: /includes/apiargs/MongoDBDatabase-method-selectCollection-param.rst
The ``$options`` parameter accepts the following options:
.. include:: /includes/apiargs/MongoDBDatabase-method-selectCollection-option.rst
Output
------
Returns a :phpclass:`MongoDB\\Collection` object.
Example
-------
The following example selects the ``users`` collection in the ``demo``
database with a custom read preference:
.. code-block:: php
$db = (new MongoDB\Client)->demo;
$users = $db->selectCollection(
'users',
[
'readPreference' => new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY),
]
);
var_dump($users);
The output would then resemble::
object(MongoDB\Collection)#8 (7) {
["collectionName"]=>
string(5) "users"
["databaseName"]=>
string(4) "demo"
["manager"]=>
object(MongoDB\Driver\Manager)#2 (2) {
["uri"]=>
string(25) "mongodb://localhost:27017"
["cluster"]=>
array(1) {
[0]=>
array(11) {
["host"]=>
string(9) "localhost"
["port"]=>
int(27017)
["type"]=>
int(0)
["is_primary"]=>
bool(false)
["is_secondary"]=>
bool(false)
["is_arbiter"]=>
bool(false)
["is_hidden"]=>
bool(false)
["is_passive"]=>
bool(false)
["tags"]=>
array(0) {
}
["last_is_master"]=>
array(0) {
}
["round_trip_time"]=>
int(-1)
}
}
}
["readConcern"]=>
object(MongoDB\Driver\ReadConcern)#5 (1) {
["level"]=>
NULL
}
["readPreference"]=>
object(MongoDB\Driver\ReadPreference)#3 (2) {
["mode"]=>
int(2)
["tags"]=>
array(0) {
}
}
["typeMap"]=>
array(3) {
["array"]=>
string(23) "MongoDB\Model\BSONArray"
["document"]=>
string(26) "MongoDB\Model\BSONDocument"
["root"]=>
string(26) "MongoDB\Model\BSONDocument"
}
["writeConcern"]=>
object(MongoDB\Driver\WriteConcern)#7 (4) {
["w"]=>
NULL
["wmajority"]=>
bool(false)
["wtimeout"]=>
int(0)
["journal"]=>
NULL
}
}
.. seealso::
- :phpmethod:`MongoDB\\Collection::__construct`
- :phpmethod:`MongoDB\\Database::__get`
================================
MongoDB\\Database::withOptions()
================================
.. default-domain:: mongodb
Definition
----------
.. phpmethod:: MongoDB\\Database::withOptions
Returns a clone of the Database object, but with different options.
.. code-block:: php
function withOptions(array $options = []): MongoDB\Database
:phpmethod:`MongoDB\\Database::withOptions` supports the
following parameter:
.. include:: /includes/apiargs/MongoDBCollection-method-withOptions-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-withOptions-option.rst
Example
-------
The following example clones the ``$newDb`` Database object with read
preference ``RP_SECONDARY``.
.. code-block:: php
<?php
$database = new MongoDB\Client;
$newDb = $database->withOptions('sample','restaurants');
$newCollection = $sourceCollection->withOptions([
'readPreference' => new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY),
]);
.. seealso::
- :phpmethod:`MongoDB\\Collection::__construct`
================================
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 <MongoDB\\Database>` instance.
.. code-block:: php
function __construct(MongoDB\Driver\Manager $manager, $databaseName, array $options = [])
:phpmethod:`MongoDB\\Database::__construct` has the following parameters:
.. include:: /includes/apiargs/MongoDBDatabase-method-construct-param.rst
:phpmethod:`MongoDB\\Database::__construct` supports the following
options:
.. include:: /includes/apiargs/MongoDBDatabase-method-construct-option.rst
If you construct the Database explicitly, the Database inherits any
options from the ``Manager`` object. If you select the Database
from a :phpclass:`Client <MongoDB\\Client>` object, the Database
inherits its options from that object.
.. seealso::
- :phpmethod:`MongoDB\\Database::withOptions`
==========================
MongoDB\\Database::__get()
==========================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Database::__get($collectionName)
Select a collection from the database.
.. code-block:: php
function __get($collectionName): MongoDB\Collection
:phpmethod:`MongoDB\\Database::__get` has the following parameters:
.. include:: /includes/apiargs/MongoDBDatabase-method-get-param.rst
Behavior
--------
The selected database inherits options such as read preference and
type mapping from the :phpclass:`Database <MongoDB\\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 databases whose names contain special characters.
Examples
--------
The following example selects the ``users`` and ``system.profile``
collections from the ``demo`` database:
.. code-block:: php
<?php
$db = (new MongoDB\Client)->demo;
$users = $db->users;
$systemProfile = $db->{'system.profile'};
.. seealso::
- :phpmethod:`MongoDB\\Database::selectCollection`
- :php:`Property Overloading <oop5.overloading>` in the PHP Manual.
Tutorials
=========
.. default-domain:: mongodb
.. toctree::
/tutorial/crud
/tutorial/commands
/tutorial/indexes
=========================
Execute Database Commands
=========================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol
Overview
--------
The |php-library| provides :ref:`helper methods <database-methods>`
for common :manual:`database commands </reference/command>`. In
addition, the |php-library| provides the
:phpmethod:`MongoDB\\Database::command` method to run database commands
with PHP that do not have helper methods.
Execute Database Commands
-------------------------
Basic Command
~~~~~~~~~~~~~
To execute a command on a :program:`mongod` instance, use the
:phpmethod:`MongoDB\\Database::command` method. For instance, the
following operation uses the :dbcommand:`geoNear` HERE command to search for
the three closest documents to longitude ``-74`` and latitude ``40`` in
the ``restos`` collection in the ``example`` database:
:readmode:`secondary`
.. code-block:: php
<?php
$database = (new MongoDB\Client)->example;
$results = $database->command(
[
'geoNear' => 'restos',
'near' => [
'type' => 'Point',
'coordinates' => [-74.0, 40.0]
],
'spherical' => 'true',
'num' => 3
]
);
var_dump($results);
The output would resemble::
object(MongoDB\Driver\Cursor)#10 (2) {
["cursor"]=>
array(17) {
["stamp"]=>
int(0)
["is_command"]=>
bool(true)
["sent"]=>
bool(true)
["done"]=>
bool(false)
["end_of_event"]=>
bool(false)
["in_exhaust"]=>
bool(false)
["has_fields"]=>
bool(false)
["query"]=>
object(stdClass)#3 (4) {
["geoNear"]=>
string(6) "restos"
["near"]=>
object(stdClass)#9 (2) {
["type"]=>
string(5) "Point"
["coordinates"]=>
array(2) {
[0]=>
float(-74)
[1]=>
float(40)
}
}
["spherical"]=>
string(4) "true"
["num"]=>
int(3)
}
["fields"]=>
object(stdClass)#8 (0) {
}
["read_preference"]=>
array(2) {
["mode"]=>
int(1)
["tags"]=>
array(0) {
}
}
["flags"]=>
int(0)
["skip"]=>
int(0)
["limit"]=>
int(1)
["count"]=>
int(1)
["batch_size"]=>
int(0)
["ns"]=>
string(12) "example.$cmd"
["current_doc"]=>
object(stdClass)#24 (4) {
["waitedMS"]=>
int(0)
["results"]=>
array(3) {
[0]=>
object(stdClass)#14 (2) {
["dis"]=>
float(66308.6190421)
["obj"]=>
object(stdClass)#13 (5) {
["_id"]=>
object(MongoDB\BSON\ObjectID)#11 (1) {
["oid"]=>
string(24) "57506d62f57802807471dd28"
}
["name"]=>
string(21) "XYZ Bagels Restaurant"
["contact"]=>
object(stdClass)#12 (3) {
["phone"]=>
string(12) "435-555-0190"
["email"]=>
string(31) "XYZBagelsRestaurant@example.net"
["location"]=>
array(2) {
[0]=>
float(-74.0707363)
[1]=>
float(40.5932157)
}
}
["stars"]=>
int(4)
["categories"]=>
array(3) {
[0]=>
string(6) "Bagels"
[1]=>
string(10) "Sandwiches"
[2]=>
string(6) "Coffee"
}
}
}
[1]=>
object(stdClass)#18 (2) {
["dis"]=>
float(69014.6014737)
["obj"]=>
object(stdClass)#17 (5) {
["_id"]=>
object(MongoDB\BSON\ObjectID)#15 (1) {
["oid"]=>
string(24) "57506d62f57802807471dd39"
}
["name"]=>
string(20) "Green Feast Pizzeria"
["contact"]=>
object(stdClass)#16 (3) {
["phone"]=>
string(12) "840-555-0102"
["email"]=>
string(30) "GreenFeastPizzeria@example.com"
["location"]=>
array(2) {
[0]=>
float(-74.1220973)
[1]=>
float(40.6129407)
}
}
["stars"]=>
int(2)
["categories"]=>
array(2) {
[0]=>
string(5) "Pizza"
[1]=>
string(7) "Italian"
}
}
}
[2]=>
object(stdClass)#22 (2) {
["dis"]=>
float(69975.5031089)
["obj"]=>
object(stdClass)#21 (5) {
["_id"]=>
object(MongoDB\BSON\ObjectID)#19 (1) {
["oid"]=>
string(24) "57506d62f57802807471dd35"
}
["name"]=>
string(14) "XYZ Coffee Bar"
["contact"]=>
object(stdClass)#20 (3) {
["phone"]=>
string(12) "644-555-0193"
["email"]=>
string(24) "XYZCoffeeBar@example.net"
["location"]=>
array(2) {
[0]=>
float(-74.0166091)
[1]=>
float(40.6284767)
}
}
["stars"]=>
int(5)
["categories"]=>
array(4) {
[0]=>
string(6) "Coffee"
[1]=>
string(4) "Cafe"
[2]=>
string(6) "Bakery"
[3]=>
string(10) "Chocolates"
}
}
}
}
["stats"]=>
object(stdClass)#23 (5) {
["nscanned"]=>
int(11)
["objectsLoaded"]=>
int(10)
["avgDistance"]=>
float(68432.9078749)
["maxDistance"]=>
float(69975.5031089)
["time"]=>
int(0)
}
["ok"]=>
float(1)
}
}
["server_id"]=>
int(1)
}
Commands with Custom Read Preference
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Some commands, such as :manual:`createUser
</reference/command/createUser/>`, may only be executed on a
:term:`primary` replica set member or a :term:`standalone`.
The command helper methods in the
|php-library|, such as :phpmethod:`MongoDB\\Database::drop`,
know to apply their own :term:`read preference` if necessary. However,
the :phpmethod:`MongoDB\\Database::command` method is a generic method and
defaults to the read preference of the
Database object on which it is invoked. To execute commands that require
specific read preference, specify the read preference in the ``$options``
parameter of the method.
The following example adds a user to the ``demo`` database
and specifies a custom read preference:
.. code-block:: php
<?php
$db = (new MongoDB\Client)->demo;
$cursor = $db->command(
[
'createUser' => 'username',
'pwd' => 'password',
'roles' => ['readWrite'],
],
[
'readPreference' => new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY),
]
);
var_dump($cursor->toArray()[0]);
The output would then resemble::
object(MongoDB\Model\BSONDocument)#8 (1) {
["storage":"ArrayObject":private]=>
array(1) {
["ok"]=>
float(1)
}
}
View Command Results
--------------------
View Single Result Documents
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The :phpmethod:`MongoDB\\Database::command()` method returns a
:php:`MongoDB\\Driver\\Cursor <mongodb-driver-cursor>` object.
Many MongoDB commands return their responses as a single document in an
array. To read the command response, you may either iterate on the
cursor and access the first document, or access the first result in the
array, as in the following:
.. code-block:: php
<?php
$database = (new MongoDB\Client)->demo;
$cursor = $database->command(['ping' => 1]);
var_dump($cursor->toArray()[0]);
The output would then resemble::
object(MongoDB\Model\BSONDocument)#2 (1) {
["storage":"ArrayObject":private]=>
array(1) {
["ok"]=>
float(1)
}
}
Iterate Results from a Cursor
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Some commands, such as :manual:`listCollections
</reference/command/listCollections/>`,
return their results via an iterable cursor. To view the results,
iterate through the cursor.
The following example lists the collections in the ``demo`` database by
iterating through the cursor returned by the ``listCollections`` command
using a ``foreach`` loop:
.. code-block:: php
<?php
$database = (new MongoDB\Client)->demo;
$cursor = $database->command(['listCollections' => 1]);
foreach ($cursor as $collection) {
echo $collection['name'], "\n";
}
The output would then be a list of the values for the ``name`` key,
for instance::
persons
posts
zips
.. note::
At the *protocol* level, commands that support a cursor
return a single result document with the essential ingredients for
constructing the command cursor (i.e. the cursor's ID, namespace, and
the first batch of results). In the PHP driver implementation, the
:php:`executeCommand() <mongodb-driver-manager.executecommand>`
method detects the single result and constructs the iterable command
cursor, which is returned rather than the base result document.
===============
CRUD Operations
===============
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol
CRUD operations *create*, *read*, *update*, and *delete* documents. The
|php-library|'s :phpclass:`MongoDB\\Collection` class implements
MongoDB's cross-driver `CRUD specification
<https://github.com/mongodb/specifications/blob/master/source/crud/crud.
rst>`_, providing access to methods for inserting, finding, updating,
and deleting documents in MongoDB.
This document provides a general introduction to inserting, querying,
updating, and deleting documents using the |php-library|. The MongoDB
Manual's :manual:`CRUD Section </crud>` provides a more thorough
introduction to CRUD operations with MongoDB.
Insert Documents
----------------
Insert One Document
~~~~~~~~~~~~~~~~~~~
The :phpmethod:`MongoDB\\Collection::insertOne` method inserts a single
document into MongoDB and returns an instance of ``MongoDB\InsertOneResult``,
which you can use to access the IDs of the inserted document.
.. basic insertOne example:
.. include:: /includes/example-insertOne.rst
The output includes the ``insertedId`` property, which contains the
ID of the inserted document.
If you include an ``_id`` value when inserting a document, MongoDB checks
to ensure that the ``_id`` value is unique for the collection. If the
``_id`` value is not unique, the insert operation fails due to a duplicate
key error.
The following example inserts a document while specifying the value for the ``_id``:
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->demo->users;
$insertOneResult = $collection->insertOne(['_id' => 1, 'name' => 'Alice']);
printf("Inserted %d document(s)\n", $insertOneResult->getInsertedCount());
var_dump($insertOneResult->getInsertedId());
The output would then resemble::
Inserted 1 document(s)
int(1)
.. seealso:: :phpmethod:`MongoDB\\Collection::insertOne` reference.
Insert Many Documents
~~~~~~~~~~~~~~~~~~~~~
The :phpmethod:`MongoDB\\Collection::insertMany` method allows you to
insert multiple documents in one write operation and returns an instance
of ``MongoDB\InsertManyResult``, which you can use to access the
IDs of the inserted documents.
.. this uses the insertMany example from the method reference:
.. include:: /reference/method/MongoDBCollection-insertMany.txt
:start-after: start-crud-include
:end-before: end-crud-include
.. seealso:: :phpmethod:`MongoDB\\Collection::insertMany` reference.
Query Documents
---------------
The |php-library| provides the :phpmethod:`MongoDB\\Collection::findOne`
and :phpmethod:`MongoDB\\Collection:findMany` methods for querying
documents and the :phpmethod:`MongoDB\\Collection:aggregate`
method for performing :manual:`aggregation operations
</core/aggregation-pipeline`.
Find One Document
~~~~~~~~~~~~~~~~~
:phpmethod:`MongoDB\\Collection::findOne` returns the :term:`first
document <natural order>` that matches the query or ``null`` if no
document matches the query.
The following example searches for the document with ``_id: 94301``:
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->demo->zips;
$document = $collection->findOne(['_id' => '94301']);
var_dump($document);
The output would then resemble::
object(MongoDB\Model\BSONDocument)#13 (1) {
["storage":"ArrayObject":private]=>
array(5) {
["_id"]=>
string(5) "94301"
["city"]=>
string(9) "PALO ALTO"
["loc"]=>
object(MongoDB\Model\BSONArray)#12 (1) {
["storage":"ArrayObject":private]=>
array(2) {
[0]=>
float(-122.149685)
[1]=>
float(37.444324)
}
}
["pop"]=>
int(15965)
["state"]=>
string(2) "CA"
}
}
.. seealso:: :phpmethod:`MongoDB\\Collection::findMany` reference
Find Many Documents
~~~~~~~~~~~~~~~~~~~
:phpmethod:`MongoDB\\Collection::find` returns a
:php:`MongoDB\\Driver\\Cursor <mongodb-driver-cursor>` object, which you
can iterate upon to access all matched documents.
The following example lists the documents in the ``zips`` collection
with the specified city and state values:
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->demo->zips;
$cursor = $collection->find(['city' => 'JERSEY CITY', 'state' => 'NJ']);
foreach ($cursor as $document) {
echo $document['_id'], "\n";
}
The output would resemble::
07302
07304
07305
07306
07307
07310
.. seealso:: :phpmethod:`MongoDB\\Collection::find` reference
.. _php-query-projection:
Query Projection
~~~~~~~~~~~~~~~~
By default, queries in MongoDB return all fields in matching documents.
To limit the amount of data that MongoDB sends to applications, you can
include a :manual:`projection document
</tutorial/project-fields-from-query-results>` in the query operation.
.. note::
MongoDB includes the ``_id`` field by default unless you explicitly
exclude it in a projection document.
The following example finds restaurants based on the ``cuisine`` and
``borough`` fields and uses a :manual:`projection
</tutorial/project-fields-from-query-results>` to limit the fields
that are returned. It also limits the results to 5 documents.
.. code-block:: php
<?php
$database = new MongoDB\Client;
$collection = $database->selectCollection('example','restaurants');
$restaurants = $collection->find(
[ 'cuisine' => 'Italian', 'borough' => 'Manhattan'],
[
'projection' => [
'name' => 1, 'borough' => 1, 'cuisine' => 1,
],
]
);
foreach($restaurants 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."
}
}
...
Limit, Sort, and Skip Options
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In addition to :ref:`projection criteria <php-query-projection>`,
you can specify options to limit, sort, and skip documents during queries.
The following example uses the ``limit`` and ``sort`` options to query
for the five most populous zip codes in the United States:
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->demo->zips;
$cursor = $collection->find(
[],
[
'limit' => 5,
'sort' => ['pop' => -1],
]
);
foreach ($cursor as $document) {
echo $document['_id'], "\n";
}
The output would then resemble::
60623: CHICAGO, IL
11226: BROOKLYN, NY
10021: NEW YORK, NY
10025: NEW YORK, NY
90201: BELL GARDENS, CA
Complex Queries with Aggregation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
MongoDB's :manual:`Aggregation Framework </core/aggregation-pipeline>`
allows you to issue complex queries that filter, transform, and group
collection data. The |php-library|\'s
:phpmethod:`MongoDB\\Collection::aggregate` method returns a
:php:`traversable <traversable>` object, which you can iterate upon to
access the results of the aggregation operation. Refer to the
:phpmethod:`MongoDB\\Collection::aggregate` method's :ref:`output
reference <php-agg-method-output>` for more about the method's output.
The following example lists the 5 US states with the most zip codes
associated with them:
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->demo->zips;
$cursor = $collection->aggregate([
['$group' => ['_id' => '$state', 'count' => ['$sum' => 1]]],
['$sort' => ['count' => -1]],
['$limit' => 5],
]);
foreach ($cursor as $state) {
printf("%s has %d zip codes\n", $state['_id'], $state['count']);
}
The output would then resemble::
TX has 1671 zip codes
NY has 1595 zip codes
CA has 1516 zip codes
PA has 1458 zip codes
IL has 1237 zip codes
.. seealso:: :phpmethod:`MongoDB\\Collection::aggregate` reference
Update Documents
----------------
Update One Document
~~~~~~~~~~~~~~~~~~~
Use the :phpmethod:`MongoDB\\Collection::updateOne` method to update a
single document matching a filter.
:phpmethod:`MongoDB\\Collection::updateOne` returns a
``MongoDB\UpdateResult`` object, which you can use to access statistics
about the update operation.
Update methods have two required parameters: the query filter that
identifies the document or documents to update, and an update document
that specifies what updates to perform. The :phpmethod:`MongoDB\\Collection::updateOne`
reference describes each parameter in detail.
The following example inserts two documents into an empty ``users`` collection
in the ``demo`` database using the :phpmethod:`MongoDB\\Collection::insertOne`
method, and then updates the documents where the value for the ``state``
field is ``"ny"`` to include
a ``country`` field set to ``"us"``:
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->demo->users;
$collection->drop();
$collection->insertOne(['name' => 'Bob', 'state' => 'ny']);
$collection->insertOne(['name' => 'Alice', 'state' => 'ny']);
$updateResult = $collection->updateOne(
['state' => 'ny'],
['$set' => ['country' => 'us']]
);
printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());
Since the update operation uses the
:phpmethod:`MongoDB\\Collection::updateOne` method, which updates the
first document to match the filter criteria, the results would then
resemble::
Matched 1 document(s)
Modified 1 document(s)
It is possible for a document to match the filter but *not be modified*
by an update, as is the case where the update sets a field's value to its
existing value, as in this example:
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->demo->users;
$collection->drop();
$collection->insertOne(['name' => 'Bob', 'state' => 'ny']);
$updateResult = $collection->updateOne(
['name' => 'Bob'],
['$set' => ['state' => 'ny']]
);
printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());
The number of matched documents and the number of *modified* documents
would therefore not be equal, and the output from the operation would
resemble::
Matched 1 document(s)
Modified 0 document(s)
.. seealso::
- :phpmethod:`MongoDB\\Collection::updateOne` reference
- :phpmethod:`MongoDB\\Collection::findOneAndUpdate` reference
Update Many Documents
~~~~~~~~~~~~~~~~~~~~~
:phpmethod:`MongoDB\\Collection::updateMany` updates one or more documents
matching the filter criteria and returns a ``MongoDB\UpdateResult`` object
that you can iterate to access statistics about the update operation.
Update methods have two required parameters: the query filter that
identifies the document or documents to update, and an update document
that specifies what updates to perform. The :phpmethod:`MongoDB\\Collection::updateMany`
reference describes each parameter in detail.
The following example inserts three documents into an empty ``users``
collection in the ``demo`` database and then uses the :query:`$set`
operator to update the documents matching the filter criteria to
include the ``country`` field with value ``"us"``:
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->demo->users;
$collection->drop();
$collection->insertOne(['name' => 'Bob', 'state' => 'ny', 'country' => 'us']);
$collection->insertOne(['name' => 'Alice', 'state' => 'ny']);
$collection->insertOne(['name' => 'Sam', 'state' => 'ny']);
$updateResult = $collection->updateMany(
['state' => 'ny'],
['$set' => ['country' => 'us']]
);
printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());
If an update operation results in no change to a document, such as
setting the value of the field to its current value, the number of
modified documents can be less than the number of *matched* documents.
Since the update document with ``name`` of ``"Bob"`` results in no changes
to the document, the output of the operation therefore resembles::
Matched 3 document(s)
Modified 2 document(s)
.. seealso:: :phpmethod:`MongoDB\\Collection::updateMany` reference
Replace Documents
~~~~~~~~~~~~~~~~~
Replacement operations are similar to update operations, but instead
of updating a document to include new fields or new field values, a
replacement operation replaces the entire document with a new document,
but retains the original document's ``_id`` value.
The :phpmethod:`MongoDB\\Collection::replaceOne` method replaces a single
document that matches the filter criteria and returns
an instance of ``MongoDB\UpdateResult`` that
you can use to access statistics about the replacement operation.
:phpmethod:`MongoDB\\Collection::replaceOne` has two required
parameters: the query filter that identifies the document or documents
to update, and a replacement document that will replace the original
document in MongoDB. The :phpmethod:`MongoDB\\Collection::replaceOne`
reference describes each parameter in detail.
.. important::
Replacement operations replace all of the fields in a document
except the ``_id`` value. To avoid accidentally overwriting or
deleting desired fields, use the
:phpmethod:`MongoDB\\Collection::updateOne` or
:phpmethod:`MongoDB\\Collection::updateMany` methods to update
individual fields in a document rather than replacing the entire
document.
The following example inserts one document into an empty ``users`` collection
in the ``demo`` database, and then replaces that document with a new one:
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->demo->users;
$collection->drop();
$collection->insertOne(['name' => 'Bob', 'state' => 'ny']);
$updateResult = $collection->replaceOne(
['name' => 'Bob'],
['name' => 'Robert', 'state' => 'ca']
);
printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());
The output would then resemble::
Matched 1 document(s)
Modified 1 document(s)
.. seealso::
- :phpmethod:`MongoDB\\Collection::replaceOne` reference
- :phpmethod:`MongoDB\\Collection::findOneAndReplace` reference
Upsert
~~~~~~
Update and replace operations support an :manual:`upsert
</tutorial/update-documents/#upsert-option>` option. When ``upsert`` is
``true`` *and* no documents match the specified filter, then the
operation creates a new document and inserts it. If there *are* matching
documents, then the operation modifies or replaces the matching
document or documents.
When a document is upserted, the ID is accessible via
``MongoDB\UpdateResult::getUpsertedId()``.
The following example uses :phpmethod:`MongoDB\\Collection::updateOne`
with the ``upsert`` option set to ``true`` into an empty ``users``
collection in the ``demo`` database, therefore inserting the document
into the database:
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->demo->users;
$collection->drop();
$updateResult = $collection->updateOne(
['name' => 'Bob'],
['$set' => ['state' => 'ny']],
['upsert' => true]
);
printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());
var_dump($collection->findOne(['_id' => $updateResult->getUpsertedId()]));
The output would then resemble::
Matched 0 document(s)
Modified 0 document(s)
object(MongoDB\Model\BSONDocument)#16 (1) {
["storage":"ArrayObject":private]=>
array(3) {
["_id"]=>
object(MongoDB\BSON\ObjectID)#15 (1) {
["oid"]=>
string(24) "57509c4406d7241dad86e7c3"
}
["name"]=>
string(3) "Bob"
["state"]=>
string(2) "ny"
}
}
Delete Documents
----------------
Delete One Document
~~~~~~~~~~~~~~~~~~~
The :phpmethod:`MongoDB\\Collection::deleteOne` method deletes a single
document that matches the filter criteria and returns a
``MongoDB\DeleteResult`` object that you can use to access statistics
about the delete operation. If multiple documents match the filter
criteria, :phpmethod:`MongoDB\\Collection::deleteOne` deletes the
:term:`first <natural order>` matching document.
:phpmethod:`MongoDB\\Collection::deleteOne` has one required parameter:
a query filter that specifies the document to delete. Refer to the
:phpmethod:`MongoDB\\Collection::deleteOne` reference for full method documentation.
The following operation deletes the first document where the ``state``
value is ``ny``:
.. 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::deleteOne` reference.
Delete Many Documents
~~~~~~~~~~~~~~~~~~~~~
:phpmethod:`MongoDB\\Collection::deleteMany` deletes all of the
documents that match the filter criteria and returns a
``MongodB\DeleteResult`` object that you can use to access statistics
about the delete op eration.
:phpmethod:`MongoDB\\Collection::deleteMany` has one required
parameter: a query filter that specifies the document to delete. Refer
to the :phpmethod:`MongoDB\\Collection::deleteMany` reference for full
method documentation.
The following operation deletes all of the documents where the
``state`` field has value ``"ny"``:
.. 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::deleteMany` reference
# Example Data
Some examples in this documentation use example data fixtures from
[zips.json][zips]. This is a dataset comprised of United States postal codes,
populations, and geographic locations.
Importing the dataset into MongoDB can be done in several ways. The following
example uses [mongodb extension][ext-mongodb]:
[zips]: http://media.mongodb.org/zips.json
[ext-mongodb]: http://php.net/mongodb
```
<?php
$file = 'http://media.mongodb.org/zips.json';
$zips = file($file, FILE_IGNORE_NEW_LINES);
$bulk = new MongoDB\Driver\BulkWrite;
foreach ($zips as $string) {
$document = json_decode($string);
$bulk->insert($document);
}
$manager = new MongoDB\Driver\Manager('mongodb://localhost');
$result = $manager->executeBulkWrite('demo.zips', $bulk);
printf("Inserted %d documents\n", $result->getInsertedCount());
```
Executing this script should yield the following output:
```
Inserted 29353 documents
```
You may also import the dataset using the [mongoimport][mongoimport] command,
which is included with MongoDB:
[mongoimport]: http://docs.mongodb.org/manual/reference/program/mongoimport/
```bash
$ mongoimport --db demo --collection zips --file zips.json --drop
```
=======
Indexes
=======
.. default-domain:: mongodb
Indexes support the efficient execution of queries in MongoDB. Without
indexes, MongoDB must perform a *collection scan*, i.e. scan every
document in a collection, to select those documents that match the
query statement. If an appropriate index exists for a query,
MongoDB can use the index to limit the number of documents it must
inspect.
The PHP driver supports managing indexes through the
:phpclass:`MongoDB\\Collection` class, which implements MongoDB's
cross-driver `Index Management
<https://github.com/mongodb/specifications/blob/master/source/index-management.rst>`_
and `Enumerating Indexes
<https://github.com/mongodb/specifications/blob/master/source/enumerate-indexes.rst>`_
specifications.
This document provides an introduction to creating, listing, and
dropping indexes using the |php-library|. The MongoDB Manual's
:manual:`Indexes Section </indexes>` provides more thorough
information about indexing in MongoDB.
Create Indexes
--------------
Create indexes with the :phpmethod:`MongoDB\\Collection::createIndex`
and :phpmethod:`MongoDB\\Collection::createIndexes` methods. Refer to
the method reference for more details about each method.
The following example creates an ascending index on the ``state`` field
using the :phpmethod:`createIndex` method:
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->demo->zips;
$result = $collection->createIndex(['state' => 1]);
var_dump($result);
When you create an index, the method returns its name, which is
automatically generated from its specification. The above example would
output something similar to::
string(7) "state_1"
List Indexes
------------
The :phpmethod:`MongoDB\\Collection::listIndexes` method provides
information about the indexes in a collection.
:phpmethod:`MongoDB\\Collection::listIndexes` method returns an
iterator of ``MongoDB\Model\IndexInfo`` objects, which you can use to
view information about each index. Refer to the method reference for
more details about each method.
The following example lists all indexes in the ``zips`` collection in
the ``demo`` database:
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->demo->zips;
foreach ($collection->listIndexes() as $indexInfo) {
var_dump($indexInfo);
}
The output would resemble::
object(MongoDB\Model\IndexInfo)#10 (4) {
["v"]=>
int(1)
["key"]=>
array(1) {
["_id"]=>
int(1)
}
["name"]=>
string(4) "_id_"
["ns"]=>
string(9) "demo.zips"
}
object(MongoDB\Model\IndexInfo)#13 (4) {
["v"]=>
int(1)
["key"]=>
array(1) {
["state"]=>
int(1)
}
["name"]=>
string(7) "state_1"
["ns"]=>
string(9) "demo.zips"
}
Drop Indexes
------------
The :phpmethod:`MongoDB\\Collection::dropIndex` lets you drop a single index while
:phpmethod:`MongoDB\\Collection::dropIndexes` drops all of the indexes on a collection.
Refer to the method reference for more details about each method.
The following example drops a single index by its name, ``state_1``:
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->demo->zips;
$result = $collection->dropIndex('state_1');
var_dump($result);
The operation's output would resemble::
object(MongoDB\Model\BSONDocument)#11 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["nIndexesWas"]=>
int(2)
["ok"]=>
float(1)
}
}
=========================
Install the |php-library|
=========================
.. default-domain:: mongodb
Prerequisites
-------------
The MongoDB PHP Library is a high-level abstraction for the
MongoDB PHP driver. As such, you must install the `mongodb`
extension to use the |php-library|:
.. code-block:: sh
pecl install mongodb
echo "extension=mongodb.so" >> `php --ini | grep "Loaded Configuration" | sed -e "s|.*:\s*||"`
Instructions for installing the `mongodb` extension on HHVM may be
found in the :php:`Installation with HHVM
<mongodb.installation.hhvm>` article
in the driver documentation.
Procedure
---------
Install the Library
~~~~~~~~~~~~~~~~~~~
The preferred method of installing |php-library| is with `Composer
<https://getcomposer.org/>`_ by running the following from your project
root:
.. code-block:: sh
composer require "mongodb/mongodb=^1.0.0"
While not recommended, you may also manually install the package via
the source tarballs attached to the `GitHub releases
<https://github.com/mongodb/mongo-php-library/releases>`_.
Configure Autoloading
~~~~~~~~~~~~~~~~~~~~~
Once you have installed the library, ensure that your application
includes Composer's autoloader. The ``require_once``
statement should point to Composer's autoloader, as in the following example:
.. code-block:: php
require_once __DIR__ . "/vendor/autoload.php";
Refer to Composer's `autoloading documentation
<https://getcomposer.org/doc/01-basic-usage.md#autoloading>`_ for more
information about setting up autoloading.
If you installed the library manually from a source tarball, you
will also need to manually configure autoloading:
#. Map the top-level ``MongoDB\`` namespace to the ``src/`` directory
using your preferred autoloader implementation.
#. Manually require the ``src/functions.php`` file, since PHP does not
yet support function autoloading.
=============
Upgrade Guide
=============
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
The MongoDB PHP Library and underlying :php:`mongodb
extension <mongodb>` have notable API differences from
the legacy :php:`mongo extension <mongo>`. This page will
summarizes those differences for the benefit of those
upgrading rom the legacy driver.
Additionally, a community-developed
`mongo-php-adapter <https://github.com/alcaeus/mongo-php-adapter>`__
library exists, which implements the `mongo
extension <http://php.net/mongo>`__ API using this library and the new
driver. While this adapter library is not officially supported by
MongoDB, it does bear mentioning.
Collection API
~~~~~~~~~~~~~~
This library's :phpclass:`MongoDB\\Collection` class
implements MongoDB's cross-driver
`CRUD <https://github.com/mongodb/specifications/blob/master/source/crud/crud.rst>`__
and `Index
Management <https://github.com/mongodb/specifications/blob/master/source/index-management.rst>`__
specifications. Although some method names have changed in accordance
with the new specifications, the new class provides the same
functionality as the legacy driver's
`MongoCollection <http://php.net/mongocollection>`__ class with some
notable exceptions.
Old and New Methods
~~~~~~~~~~~~~~~~~~~
.. list-table::
:header-rows: 1
* - :php:`MongoCollection <class.mongocollection>`
- :phpclass:`MongoDB\\Collection`
* - :php:`MongoCollection::aggregate() <mongocollection.aggregate>`
- :phpmethod:`MongoDB\\Collection::aggregate`
* - :php:`MongoCollection::aggregateCursor() <mongocollection.aggregatecursor>`
- :phpmethod:`MongoDB\\Collection::aggregate`
* - :php:`MongoCollection::batchInsert() <mongocollection.batchinsert>`
- :phpmethod:`MongoDB\\Collection::insertMany`
* - :php:`MongoCollection::count() <mongocollection.count>`
- :phpmethod:`MongoDB\\Collection::count`
* - :php:`MongoCollection::createDBRef() <mongocollection.createdbref>`
- Not yet implemented. See :issue:`PHPLIB-24`
* - :php:`MongoCollection::createIndex() <mongocollection.createindex>`
- :phpmethod:`MongoDB\\Collection::createIndex`
* - :php:`MongoCollection::deleteIndex() <mongocollection.deleteindex>`
- :phpmethod:`MongoDB\\Collection::dropIndex`
* - :php:`MongoCollection::deleteIndexes() <mongocollection.deleteindexes>`
- :phpmethod:`MongoDB\\Collection::dropIndexes`
* - :php:`MongoCollection::drop() <mongocollection.drop>`
- :phpmethod:`MongoDB\\Collection::drop`
* - :php:`MongoCollection::distinct() <mongocollection.distinct>`
- :phpmethod:`MongoDB\\Collection::distinct`
* - :php:`MongoCollection::ensureIndex() <mongocollection.ensureindex>`
- :phpmethod:`MongoDB\\Collection::createIndex`
* - :php:`MongoCollection::find() <mongocollection.find>`
- :phpmethod:`MongoDB\\Collection::find`
* - :php:`MongoCollection::findAndModify() <mongocollection.findandmodify>`
- :phpmethod:`MongoDB\\Collection::findOneAndDelete`,
:phpmethod:`MongoDB\\Collection::findOneAndReplace`, and
:phpmethod:`MongoDB\\Collection::findOneAndUpdate()`
* - :php:`MongoCollection::findOne() <mongocollection.findone>`
- :phpmethod:`MongoDB\\Collection::findOne`
* - :php:`MongoCollection::getDBRef() <mongocollection.getdbref>`
- Not implemented. See :issue:`PHPLIB-24`
* - :php:`MongoCollection::getIndexInfo() <mongocollection.getindexinfo>`
- :phpmethod:`MongoDB\\Collection::listIndexes`
* - :php:`MongoCollection::getName() <mongocollection.getname>`
- :phpmethod:`MongoDB\\Collection::getCollectionName`
* - :php:`MongoCollection::getReadPreference() <mongocollection.getreadpreference>`
- Not implemented.
* - :php:`MongoCollection::getSlaveOkay() <mongocollection.getslaveokay>`
- Not implemented.
* - :php:`MongoCollection::getWriteConcern() <mongocollection.getwriteconcern>`
- Not implemented.
* - :php:`MongoCollection::group() <mongocollection.group>`
- Not yet implemented. See :issue:`PHPLIB-177`.
Use :phpmethod:`MongoDB\\Database::command`.
* - :php:`MongoCollection::insert() <mongocollection.insert>`
- :phpmethod:`MongoDB\\Collection::insertOne`
* - :php:`MongoCollection::parallelCollectionScan() <mongocollection.parallelcollectionscan>`
- Not implemented.
* - :php:`MongoCollection::remove() <mongocollection.remove>`
- :phpmethod:`MongoDB\\Collection::deleteMany` and
:phpmethod:`MongoDB\\Collection::deleteOne`
* - :php:`MongoCollection::save() <mongocollection.save>`
- :phpmethod:`MongoDB\\Collection::insertOne` or
:phpmethod:`MongoDB\\Collection::replaceOne` with the ``upsert``
option.
* - :php:`MongoCollection::setReadPreference() <mongocollection.setreadpreference>`
- Not implemented. Use :phpmethod:`MongoDB\\Collection::withOptions()`
* - :php:`MongoCollection::setSlaveOkay() <mongocollection.getslaveokay>`
- Not implemented.
* - :php:`MongoCollection::setWriteConcern() <mongocollection.setwriteconcern>`
- Not implemented. Use :phpmethod:`MongoDB\\Collection::withOptions`
* - :php:`MongoCollection::update() <mongocollection.update>`
- :phpmethod:`MongoDB\\Collection::replaceOne`,
:phpmethod:`MongoDB\\Collection::updateMany`, and
:phpmethod:`MongoDB\\Collection::updateOne`.
* - :php:`MongoCollection::validate() <mongocollection.validate>`
- Not implemented.
A guiding principle in designing the new APIs was that explicit method
names are preferable to overloaded terms found in the old API. For
instance, :php:`MongoCollection::save() <mongocollection.save>` and
:php:`MongoCollection::findAndModify() <mongocollection.findandmodify>`
have different modes of operation, depending on their arguments.
Methods were also split to distinguish between :manual:`updating
specific fields </tutorial/modify-documents>` and :manual:`full-document
replacement </tutorial/modify-documents/#replace-the-document>`.
Group Command Helper
~~~~~~~~~~~~~~~~~~~~
:phpclass:`MongoDB\\Collection` does not
yet have a helper method for the :manual:`group
</reference/command/group>` command; however, it is planned in
:issue:`PHPLIB-177`. The following example demonstrates how to execute
a group command using the :phpmethod:`MongoDB\\Database::command()` method:
.. code-block:: php
<?php
$database = (new MongoDB\Client)->selectDatabase('db_name');
$cursor = $database->command([
'group' => [
'ns' => 'collection_name',
'key' => ['field_name' => 1],
'initial' => ['total' => 0],
'$reduce' => new MongoDB\BSON\Javascript('...'),
],
]);
$resultDocument = $cursor->toArray()[0];
MapReduce Command Helper
~~~~~~~~~~~~~~~~~~~~~~~~
:phpclass:`MongoDB\\Collection` does not yet have a helper method for
the :manual:`mapReduce </reference/command/mapReduce/>` command;
however, that is planned in :issue:`PHPLIB-53`. The following example
demonstrates how to execute a mapReduce command using the
:phpmethod:`MongoDB\\Database::command()` method:
.. code-block:: php
<?php
$database = (new MongoDB\Client)->selectDatabase('db_name');
$cursor = $database->command([
'mapReduce' => 'collection_name',
'map' => new MongoDB\BSON\Javascript('...'),
'reduce' => new MongoDB\BSON\Javascript('...'),
'out' => 'output_collection_name',
]);
$resultDocument = $cursor->toArray()[0];
?>
DBRef Helpers
~~~~~~~~~~~~~
:phpclass:`MongoDB\\Collection` does not yet
have helper methods for working with
:manual:`DBRef </reference/database-references>`
objects; however, that is planned in
:issue:`PHPLIB-24`.
MongoCollection::save() Removed
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:php:`MongoCollection::save() <mongocollection.save>`,
which was syntactic sugar for an insert or upsert operation, has been
removed in favor of explicitly using
:phpmethod:`MongoDB\\Collection::insertOne` or
:phpmethod:`MongoDB\\Collection::replaceOne` with the ``upsert``
option).
.. .. figure:: img/save-flowchart.png
.. :alt: save() flowchart
While the ``save``
method does have its uses for interactive environments, such as the
mongo shell, it was intentionally excluded from the
`CRUD <https://github.com/mongodb/specifications/blob/master/source/crud/crud.rst>`_
specification for language drivers. Generally, application code should
know if the document has an identifier and be able to explicitly insert
or replace the document and handle the returned InsertResult or
UpdateResult, respectively. This also helps avoid inadvertent and
potentially dangerous :manual:`full-document
replacements </tutorial/modify-documents>`.
Accessing IDs of Inserted Documents
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In the legacy driver, :php:`MongoCollection::insert()
<mongocollection.insert>`, :php:`MongoCollection::batchInsert()
<mongocollection.batchinsert`, and :php:`MongoCollection::save()
<mongocollection.save>` (when inserting) would modify their input
argument by injecting an ``_id`` key containing the generated ObjectId
(i.e. :php:`MongoId <class.mongoid>` object). This behavior was a bit
of a hack, as it did not rely on the argument being :php:`passed by
reference <language.references.pass>`; instead, it directly modified
memory through the extension API and could not be implemented in PHP
userland. As such, it is no longer done in the new driver and library.
IDs of inserted documents (whether generated or not) may be accessed
through the result objects returned by the write methods:
- ``MongoDB\InsertOneResult::getInsertedId()`` for
:phpmethod:`MongoDB\\Collection::insertOne`
- ``MongoDB\InsertManyResult::getInsertedIds()`` for
:phpmethod:`MongoDB\\Collection::insertMany`
- ``MongoDB\BulkWriteResult::getInsertedIds()`` for
:phpmethod:`MongoDB\\Collection::bulkWrite`
``MongoWriteBatch``
~~~~~~~~~~~~~~~~~~~
The legacy driver's
:php:`MongoWriteBatch <class.mongowritebatch>`
classes have been replaced with a general-purpose
:phpmethod:`MongoDB\\Collection::bulkWrite` method. Whereas the
legacy driver only allowed bulk operations of the same type, the new
method allows operations to be mixed (e.g. inserts, updates, and
deletes).
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