(PECL mongo >=0.9.0)

MongoCollection::findOneQueries this collection, returning a single element


public array MongoCollection::findOne ([ array $query = array() [, array $fields = array() [, array $options = array() ]]] )

As opposed to MongoCollection::find(), this method will return only the first result from the result set, and not a MongoCursor that can be iterated over.

Список параметров


The fields for which to search. MongoDB's query language is quite extensive. The PHP driver will in almost all cases pass the query straight through to the server, so reading the MongoDB core docs on » find is a good idea.


Please make sure that for all special query operaters (starting with $) you use single quotes so that PHP doesn't try to replace "$exists" with the value of the variable $exists.


Fields of the results to return. The array is in the format array('fieldname' => true, 'fieldname2' => true). The _id field is always returned.


This parameter is an associative array of the form array("name" => <value>, ...). Currently supported options are:

  • "maxTimeMS"

    Specifies a cumulative time limit in milliseconds for processing the operation (does not include idle time). If the operation is not completed within the timeout period, a MongoExecutionTimeoutException will be thrown.

Возвращаемые значения

Returns record matching the search or NULL.


Throws MongoConnectionException if it cannot reach the database.

Список изменений

Версия Описание
1.5.0 Added optional options argument.


Пример #1 MongoCollection::findOne() document by its id.

This example demonstrates how to find a single document in a collection by its id.



$article $articles->findOne(array('_id' => new MongoId('47cc67093475061e3d9536d2')));


Пример #2 MongoCollection::findOne() document by some condition.

This example demonstrates how to find a single document in a collection by some condition and limiting the returned fields.


$user $users->findOne(array('username' => 'jwage'), array('password'));


Результатом выполнения данного примера будет что-то подобное:

    [_id] => MongoId Object

    [password] => test

Notice how even though the document does have a username field, we limited the results to only contain the password field.

Смотрите также


There is also a notation to retrieve all fields, but the specified ones


$user $users->findOne(array('username' => 'jwage'), array('password' => 0));


Will return all fields of the user, but the password field.
2010-09-30 14:44:04

    Поддержать сайт на родительском проекте КГБ