Php/docs/mongocollection.findone
MongoCollection::findOne
(PECL mongo >=0.9.0)
MongoCollection::findOne — Queries this collection, returning a single element
说明
public MongoCollection::findOne
([ array $query
= array()
[, array $fields
= array()
[, array $options
= array()
]]] ) : 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.
参数
query
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.
Warning
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
Fields of the results to return. The array is in the format
array('fieldname' => true, 'fieldname2' => true)
. The_id
field is always returned.options
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 on the server (does not include idle time). If the operation is not completed by the server within the timeout period, a MongoExecutionTimeoutException will be thrown.
返回值
Returns record matching the search or null
.
更新日志
版本 | 说明 |
---|---|
PECL mongo 1.5.0 | Added optional options argument.
|
范例
Example #1 MongoCollection::findOne() document by its id.
This example demonstrates how to find a single document in a collection by its id.
<?php$articles = $mongo->my_db->articles;$article = $articles->findOne(array('_id' => new MongoId('47cc67093475061e3d9536d2')));?>
Example #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.
<?php$users = $mongo->my_db->users;$user = $users->findOne(array('username' => 'jwage'), array('password'));print_r($user);?>
以上例程的输出类似于:
Array ( [_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.
参见
- MongoCollection::find() - 查询该集合,并返回结果集的 MongoCursor
- MongoCollection::insert() - 插入文档到集合中
- MongoDB core docs on » find.