downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | conferences | my php.net

search for in the

MongoCollection::__get> <MongoCollection::find
[edit] Last updated: Fri, 24 Jun 2011

view this page in

MongoCollection::findOne

(PECL mongo >=0.9.0)

MongoCollection::findOneQuerys this collection, returning a single element

Description

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

Parameters

query

The fields for which to search.

fields

Fields of the results to return.

Return Values

Returns record matching the search or NULL.

Errors/Exceptions

Throws MongoConnectionException if it cannot reach the database.

Examples

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);

?>

The above example will output something similar to:

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.



add a note add a note User Contributed Notes MongoCollection::findOne - [1 notes]
up
0
dominik at dokdok dot com
2 years ago
There is also a notation to retrieve all fields, but the specified ones

<?php

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

?>

Will return all fields of the user, but the password field.

 
show source | credits | sitemap | contact | advertising | mirror sites