class MongoCollection (View source)

Represents a database collection.

Constants

ASCENDING

DESCENDING

Properties

MongoDB $db
int $w
int $wtimeout

Methods

__construct(MongoDB $db, string $name)

Creates a new collection

string
__toString()

String representation of this collection

__get(string $name)

Gets a collection

array
aggregate(array $pipeline, array $op, array $pipelineOperators)

(PECL mongo >= 1.3.0)

The MongoDB https://docs.mongodb.org/manual/applications/aggregation/ aggregation framework provides a means to calculate aggregated values without having to use MapReduce. While MapReduce is powerful, it is often more difficult than necessary for many simple aggregation tasks, such as totaling or averaging field values.

aggregateCursor(array $pipeline, array $options)

(PECL mongo >= 1.5.0)

string
getName()

Returns this collection's name

bool
getSlaveOkay()

(PECL mongo >= 1.1.0)

See https://secure.php.net/manual/en/mongo.queries.php the query section of this manual for information on distributing reads to secondaries.

bool
setSlaveOkay(bool $ok = true)

(PECL mongo >= 1.1.0)

See https://secure.php.net/manual/en/mongo.queries.php the query section of this manual for information on distributing reads to secondaries.

array
getReadPreference()

(PECL mongo >= 1.3.0)

bool
setReadPreference(string $read_preference, array $tags)

(PECL mongo >= 1.3.0)

array
drop()

Drops this collection

array
validate(bool $scan_data = false)

Validates this collection

bool|array
insert(array|object $a, array $options = [])

Inserts an array into the collection

array|bool
batchInsert(array $a, array $options = [])

Inserts multiple documents into this collection

bool
update(array $criteria, array $newobj, array $options = [])

Update records based on a given criteria

bool|array
remove(array $criteria = [], array $options = [])

(PECL mongo >= 0.9.0)
Remove records from this collection

find(array $query = [], array $fields = [])

Querys this collection

array|false
distinct(string $key, array $query = null)

Retrieve a list of distinct values for the given key across a collection

array
findAndModify(array $query, array $update = null, array $fields = null, array $options = null)

Update a document and return it

array|null
findOne(array $query = [], array $fields = [], array $options = [])

Querys this collection, returning a single element

array
createIndex(array $keys, array $options = [])

Creates an index on the given field(s), or does nothing if the index already exists

true
ensureIndex(array $keys, array $options = [])

Creates an index on the given field(s), or does nothing if the index already exists

array
deleteIndex(string|array $keys)

Deletes an index from this collection

array
deleteIndexes()

Delete all indexes for this collection

array
getIndexInfo()

Returns an array of index names for this collection

int
count(array|stdClass $query = [])

Counts the number of documents in this collection

array|bool
save(array|object $a, array $options = [])

Saves an object to this collection

array
createDBRef(array $a)

Creates a database reference

array
getDBRef(array $ref)

Fetches the document pointed to by a database reference

static string
toIndexString(mixed $keys)

No description

array
group(mixed $keys, array $initial, MongoCode $reduce, array $condition = [])

Performs an operation similar to SQL's GROUP BY command

Details

__construct(MongoDB $db, string $name)

Creates a new collection

Parameters

MongoDB $db

Parent database.

string $name

Name for this collection.

Exceptions

Exception

string __toString()

String representation of this collection

Return Value

string

Returns the full name of this collection.

MongoCollection __get(string $name)

Gets a collection

Parameters

string $name

The next string in the collection name.

Return Value

MongoCollection

array aggregate(array $pipeline, array $op, array $pipelineOperators)

(PECL mongo >= 1.3.0)

The MongoDB https://docs.mongodb.org/manual/applications/aggregation/ aggregation framework provides a means to calculate aggregated values without having to use MapReduce. While MapReduce is powerful, it is often more difficult than necessary for many simple aggregation tasks, such as totaling or averaging field values.

This method accepts either a variable amount of pipeline operators, or a single array of operators constituting the pipeline.

Parameters

array $pipeline

An array of pipeline operators, or just the first operator.

array $op

[optional]

The second pipeline operator.

array $pipelineOperators

[optional]

Additional pipeline operators.

Return Value

array

The result of the aggregation as an array. The ok will be set to 1 on success, 0 on failure.

MongoCommandCursor aggregateCursor(array $pipeline, array $options)

(PECL mongo >= 1.5.0)

With this method you can execute Aggregation Framework pipelines and retrieve the results through a cursor, instead of getting just one document back as you would with https://php.net/manual/en/mongocollection.aggregate.php MongoCollection::aggregate(). This method returns a https://php.net/manual/en/class.mongocommandcursor.php MongoCommandCursor object. This cursor object implements the https://php.net/manual/en/class.iterator.php Iterator interface just like the https://php.net/manual/en/class.mongocursor.php MongoCursor objects that are returned by the https://php.net/manual/en/mongocollection.find.php MongoCollection::find() method

Parameters

array $pipeline

The Aggregation Framework pipeline to execute.

array $options

[optional]

Options for the aggregation command

Return Value

MongoCommandCursor

Returns a https://php.net/manual/en/class.mongocommandcursor.php MongoCommandCursor object

string getName()

Returns this collection's name

Return Value

string

bool getSlaveOkay()

(PECL mongo >= 1.1.0)

See https://secure.php.net/manual/en/mongo.queries.php the query section of this manual for information on distributing reads to secondaries.

Return Value

bool

Returns the value of slaveOkay for this instance.

bool setSlaveOkay(bool $ok = true)

(PECL mongo >= 1.1.0)

See https://secure.php.net/manual/en/mongo.queries.php the query section of this manual for information on distributing reads to secondaries.

Parameters

bool $ok

[optional]

If reads should be sent to secondary members of a replica set for all possible queries using this https://secure.php.net/manual/en/class.mongocollection.php MongoCollection instance.

Return Value

bool

Returns the former value of slaveOkay for this instance.

array getReadPreference()

(PECL mongo >= 1.3.0)

Return Value

array

This function returns an array describing the read preference. The array contains the values type for the string read preference mode (corresponding to the https://secure.php.net/manual/en/class.mongoclient.php MongoClient constants), and tagsets containing a list of all tag set criteria. If no tag sets were specified, tagsets will not be present in the array.

bool setReadPreference(string $read_preference, array $tags)

(PECL mongo >= 1.3.0)

Parameters

string $read_preference

The read preference mode: MongoClient::RP_PRIMARY, MongoClient::RP_PRIMARY_PREFERRED, MongoClient::RP_SECONDARY, MongoClient::RP_SECONDARY_PREFERRED, or MongoClient::RP_NEAREST.

array $tags

[optional]

An array of zero or more tag sets, where each tag set is itself an array of criteria used to match tags on replica set members.

Return Value

bool

Returns TRUE on success, or FALSE otherwise.

array drop()

Drops this collection

Return Value

array

Returns the database response.

array validate(bool $scan_data = false)

Validates this collection

Parameters

bool $scan_data

Only validate indices, not the base collection.

Return Value

array

Returns the database's evaluation of this object.

bool|array insert(array|object $a, array $options = [])

Inserts an array into the collection

Parameters

array|object $a

An array or object. If an object is used, it may not have protected or private properties. Note: If the parameter does not have an _id key or property, a new MongoId instance will be created and assigned to it. This special behavior does not mean that the parameter is passed by reference.

array $options

Options for the insert.

"w"
See WriteConcerns. The default value for MongoClient is 1.
"fsync"
Boolean, defaults to FALSE. Forces the insert to be synced to disk before returning success. If TRUE, an acknowledged insert is implied and will override setting w to 0.
"timeout"
Integer, defaults to MongoCursor::$timeout. If "safe" is set, this sets how long (in milliseconds) for the client to wait for a database response. If the database does not respond within the timeout period, a MongoCursorTimeoutException will be thrown.
"safe"
Deprecated. Please use the WriteConcern w option.

Return Value

bool|array

Returns an array containing the status of the insertion if the "w" option is set. Otherwise, returns TRUE if the inserted array is not empty (a MongoException will be thrown if the inserted array is empty). If an array is returned, the following keys may be present:

ok
This should almost be 1 (unless last_error itself failed).
err
If this field is non-null, an error occurred on the previous operation. If this field is set, it will be a string describing the error that occurred.
code
If a database error occurred, the relevant error code will be passed back to the client.
errmsg
This field is set if something goes wrong with a database command. It is coupled with ok being 0. For example, if w is set and times out, errmsg will be set to "timed out waiting for slaves" and ok will be 0. If this field is set, it will be a string describing the error that occurred.
n
If the last operation was an update, upsert, or a remove, the number of documents affected will be returned. For insert operations, this value is always 0.
wtimeout
If the previous option timed out waiting for replication.
waited
How long the operation waited before timing out.
wtime
If w was set and the operation succeeded, how long it took to replicate to w servers.
upserted
If an upsert occurred, this field will contain the new record's _id field. For upserts, either this field or updatedExisting will be present (unless an error occurred).
updatedExisting
If an upsert updated an existing element, this field will be true. For upserts, either this field or upserted will be present (unless an error occurred).

Exceptions

MongoException
MongoCursorException
MongoCursorTimeoutException

array|bool batchInsert(array $a, array $options = [])

Inserts multiple documents into this collection

Parameters

array $a

An array of arrays.

array $options

Options for the inserts.

Return Value

array|bool

if "safe" is set, returns an associative array with the status of the inserts ("ok") and any error that may have occurred ("err"). Otherwise, returns TRUE if the batch insert was successfully sent, FALSE otherwise.

Exceptions

MongoCursorException

bool update(array $criteria, array $newobj, array $options = [])

Update records based on a given criteria

Parameters

array $criteria

Description of the objects to update.

array $newobj

The object with which to update the matching records.

array $options

This parameter is an associative array of the form array("optionname" => boolean, ...).

Currently supported options are: "upsert": If no document matches $$criteria, a new document will be created from $$criteria and $$new_object (see upsert example).

"multiple": All documents matching $criteria will be updated. MongoCollection::update has exactly the opposite behavior of MongoCollection::remove- it updates one document by default, not all matching documents. It is recommended that you always specify whether you want to update multiple documents or a single document, as the database may change its default behavior at some point in the future.

"safe" Can be a boolean or integer, defaults to false. If false, the program continues executing without waiting for a database response. If true, the program will wait for the database response and throw a MongoCursorException if the update did not succeed. If you are using replication and the master has changed, using "safe" will make the driver disconnect from the master, throw and exception, and attempt to find a new master on the next operation (your application must decide whether or not to retry the operation on the new master). If you do not use "safe" with a replica set and the master changes, there will be no way for the driver to know about the change so it will continuously and silently fail to write. If safe is an integer, will replicate the update to that many machines before returning success (or throw an exception if the replication times out, see wtimeout). This overrides the w variable set on the collection.

"fsync": Boolean, defaults to false. Forces the update to be synced to disk before returning success. If true, a safe update is implied and will override setting safe to false.

"timeout" Integer, defaults to MongoCursor::$timeout. If "safe" is set, this sets how long (in milliseconds) for the client to wait for a database response. If the database does not respond within the timeout period, a MongoCursorTimeoutException will be thrown

Return Value

bool

Exceptions

MongoCursorException

bool|array remove(array $criteria = [], array $options = [])

(PECL mongo >= 0.9.0)
Remove records from this collection

Parameters

array $criteria

[optional]

Query criteria for the documents to delete.

array $options

[optional]

An array of options for the remove operation. Currently available options include:

  • "w"

    See https://secure.php.net/manual/en/mongo.writeconcerns.php Write Concerns. The default value for MongoClient is 1.

  • "justOne"

    Specify ```TRUE``` to limit deletion to just one document. If ```FALSE``` or omitted, all documents matching the criteria will be deleted.

  • "fsync"

    Boolean, defaults to FALSE. If journaling is enabled, it works exactly like "j". If journaling is not enabled, the write operation blocks until it is synced to database files on disk. If ```TRUE```, an acknowledged insert is implied and this option will override setting "w" to 0.

    Note: If journaling is enabled, users are strongly encouraged to use the "j" option instead of "fsync". Do not use "fsync" and "j" simultaneously, as that will result in an error.

  • "j"

    Boolean, defaults to FALSE. Forces the write operation to block until it is synced to the journal on disk. If ```TRUE```, an acknowledged write is implied and this option will override setting "w" to 0.

    Note: If this option is used and journaling is disabled, MongoDB 2.6+ will raise an error and the write will fail; older server versions will simply ignore the option.

  • "socketTimeoutMS"

    This option specifies the time limit, in milliseconds, for socket communication. If the server does not respond within the timeout period, a MongoCursorTimeoutException will be thrown and there will be no way to determine if the server actually handled the write or not. A value of -1 may be specified to block indefinitely. The default value for MongoClient is 30000 (30 seconds).

  • "w"

    See https://secure.php.net/manual/en/mongo.writeconcerns.php Write Concerns. The default value for MongoClient is 1.

  • "wTimeoutMS"

    This option specifies the time limit, in milliseconds, for https://secure.php.net/manual/en/mongo.writeconcerns.php write concern} acknowledgement. It is only applicable when "w" is greater than 1, as the timeout pertains to replication. If the write concern is not satisfied within the time limit, a MongoCursorException will be thrown. A value of 0 may be specified to block indefinitely. The default value for {@link https://secure.php.net/manual/en/class.mongoclient.php MongoClient is 10000 (ten seconds).

The following options are deprecated and should no longer be used:

  • "safe"

    Deprecated. Please use the https://secure.php.net/manual/en/mongo.writeconcerns.php write concern "w" option.

  • "timeout"

    Deprecated alias for "socketTimeoutMS".

  • "wtimeout"

    Deprecated alias for "wTimeoutMS".

Return Value

bool|array

Returns an array containing the status of the removal if the "w" option is set. Otherwise, returns TRUE.

Fields in the status array are described in the documentation for MongoCollection::insert().

Exceptions

MongoCursorException
MongoCursorTimeoutException

MongoCursor find(array $query = [], array $fields = [])

Querys this collection

Parameters

array $query

The fields for which to search.

array $fields

Fields of the results to return.

Return Value

MongoCursor

array|false distinct(string $key, array $query = null)

Retrieve a list of distinct values for the given key across a collection

Parameters

string $key

The key to use.

array $query

An optional query parameters

Return Value

array|false

Returns an array of distinct values, or FALSE on failure

array findAndModify(array $query, array $update = null, array $fields = null, array $options = null)

Update a document and return it

Parameters

array $query

The query criteria to search for.

array $update

The update criteria.

array $fields

Optionally only return these fields.

array $options

An array of options to apply, such as remove the match document from the DB and return it.

Return Value

array

Returns the original document, or the modified document when new is set.

array|null findOne(array $query = [], array $fields = [], array $options = [])

Querys this collection, returning a single element

Parameters

array $query

The fields for which to search.

array $fields

Fields of the results to return.

array $options

This parameter is an associative array of the form array("name" => <value>, ...).

Return Value

array|null

array createIndex(array $keys, array $options = [])

Creates an index on the given field(s), or does nothing if the index already exists

Parameters

array $keys

Field or fields to use as index.

array $options

[optional] This parameter is an associative array of the form array("optionname" => <boolean>, ...).

Return Value

array

Returns the database response.

true ensureIndex(array $keys, array $options = [])

Creates an index on the given field(s), or does nothing if the index already exists

Parameters

array $keys

Field or fields to use as index.

array $options

[optional] This parameter is an associative array of the form array("optionname" => <boolean>, ...).

Return Value

true

always true

See also

MongoCollection::createIndex

array deleteIndex(string|array $keys)

Deletes an index from this collection

Parameters

string|array $keys

Field or fields from which to delete the index.

Return Value

array

Returns the database response.

array deleteIndexes()

Delete all indexes for this collection

Return Value

array

Returns the database response.

array getIndexInfo()

Returns an array of index names for this collection

Return Value

array

Returns a list of index names.

int count(array|stdClass $query = [])

Counts the number of documents in this collection

Parameters

array|stdClass $query

Return Value

int

Returns the number of documents matching the query.

array|bool save(array|object $a, array $options = [])

Saves an object to this collection

Parameters

array|object $a

Array to save. If an object is used, it may not have protected or private properties. Note: If the parameter does not have an _id key or property, a new MongoId instance will be created and assigned to it. See MongoCollection::insert() for additional information on this behavior.

array $options

Options for the save.

"w"
See WriteConcerns. The default value for MongoClient is 1.
"fsync"
Boolean, defaults to FALSE. Forces the insert to be synced to disk before returning success. If TRUE, an acknowledged insert is implied and will override setting w to 0.
"timeout"
Integer, defaults to MongoCursor::$timeout. If "safe" is set, this sets how long (in milliseconds) for the client to wait for a database response. If the database does not respond within the timeout period, a MongoCursorTimeoutException will be thrown.
"safe"
Deprecated. Please use the WriteConcern w option.

Return Value

array|bool

If w was set, returns an array containing the status of the save. Otherwise, returns a boolean representing if the array was not empty (an empty array will not be inserted).

Exceptions

MongoException
MongoCursorException
MongoCursorTimeoutException

array createDBRef(array $a)

Creates a database reference

Parameters

array $a

Object to which to create a reference.

Return Value

array

Returns a database reference array.

array getDBRef(array $ref)

Fetches the document pointed to by a database reference

Parameters

array $ref

A database reference.

Return Value

array

Returns the database document pointed to by the reference.

static protected string toIndexString(mixed $keys)

No description

Parameters

mixed $keys

Return Value

string

array group(mixed $keys, array $initial, MongoCode $reduce, array $condition = [])

Performs an operation similar to SQL's GROUP BY command

Parameters

mixed $keys

Fields to group by. If an array or non-code object is passed, it will be the key used to group results.

array $initial

Initial value of the aggregation counter object.

MongoCode $reduce

A function that aggregates (reduces) the objects iterated.

array $condition

An condition that must be true for a row to be considered.

Return Value

array