Skip to content

Commit bb128ed

Browse files
committed
PHP-1335: Add Collection::findOne() helper
1 parent 0509f3c commit bb128ed

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

src/Collection.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,31 @@ function find(array $filter = array(), array $options = array()) {
7878
return $cursor;
7979
}
8080

81+
/**
82+
* Performs a find (query) on the collection, returning at most one result
83+
*
84+
* @see http://docs.mongodb.org/manual/core/read-operations-introduction/
85+
* @see MongoDB\Collection::getFindOptions() for supported $options
86+
*
87+
* @param array $filter The find query to execute
88+
* @param array $options Additional options
89+
* @return array|false The matched document, or false on failure
90+
*/
91+
function findOne(array $filter = array(), array $options = array()) {
92+
$options = array_merge($this->getFindOptions(), array("limit" => 1), $options);
93+
94+
$query = $this->_buildQuery($filter, $options);
95+
96+
$cursor = $this->manager->executeQuery($this->ns, $query, $this->rp);
97+
98+
$array = iterator_to_array($cursor);
99+
if ($array) {
100+
return $array[0];
101+
}
102+
103+
return false;
104+
}
105+
81106
/**
82107
* Retrieves all find options with their default values.
83108
*

0 commit comments

Comments
 (0)