The find is the way you query data in MongoDB. Its similar to "select" statement in SQL query language.

Lets prepare the database for our demonstration.

 
$conn  = new Mongo();
 
$db = $conn->selectDB('testfind');
 
$collection = $db->post;
 
$collection->save(array(
    "title" => "post title",
    "content" => "post content", 
    "date" => strtotime(date("r")),
    "author" => "david",
    "readcount" => 3
));
 

We create a database and a collection in the db, then insert some documents into it.

The simplest find will return the whole collection.

 
$result = $collection->find();
 

The find returns a cursor. Just like cursors in RDBMS, the result set will no be sent back in one trip. This is reasonable, if one collection contains a millions records, a single find() query can crash the server.

The official document on cursor.

And Cursor methods

How to loop through MongoDB cursor with PHP

Generally there are two ways to loop through the MongoDB cursor. The first one:

 
while ( $result->hasNext() ) {
    $doc = $result->getNext();  
    $result->next();  
    print_r( $doc );
    echo "find one doc in cursor\n";
 
}
 

The second is using foreach.

 
foreach($result as $mongoid => $doc) {
    echo "mongoid is " . $mongoid;
    print_r($doc);
}
 

The property is the _id field of the document.

To see more MongoDB find query examples, we need more test data.

 
 
$collection->save(array(
    "title" => "Python",
    "content" => "post content", 
    "date" => strtotime(date("r")),
    "author" => "david",
    "readcount" => 3
));
 
$collection->save(array(
    "title" => "javascript example",
    "content" => "post content", 
    "date" => strtotime(date("r")),
    "author" => "john",
    "readcount" => 30
));
$collection->save(array(
    "title" => "mongodb tutorial",
    "content" => "post content", 
    "date" => strtotime(date("r")),
    "author" => "Jones",
    "readcount" => 300
));
$collection->save(array(
    "title" => "mysql tutorial ",
    "content" => "post content", 
    "date" => strtotime(date("r")),
    "author" => "louis",
    "readcount" => 13
));
 
 

Simple find

Find all documents with author "david".

 
 
$result = $collection->find(array(
    'author' => 'david'
));
 

Find in range

We want to find documents with readcount great than 20.

 
$result = $collection->find(array( 'readcount' => array (
        '$gt' => 20
    )    
));
 

Find documents inserted before 3 hours ago.

 
$result = $collection->find(array( 'date' => array (
        '$lt' => strtotime(date("r")) - (  60 * 60 * 3  ) 
    )    
));
 

Find matching regular expression

To query similar to "like" query in MySQL.

 
$result = $collection->find(array( 'title' => array (
        '$regex' => 'mysql'
    )    
));
 

This query return all documents that has title containing 'mysql'.