Database Reference
In-Depth Information
To use the hint() function, you must apply it to the cursor, as in the following example:
// Connect to the database
$c = new MongoClient();
// Select the collection 'people' from the database 'contacts'
$collection = $c->contacts->people;
// Execute the query and store it under the $cursor variable
$cursor = $collection->find(array("Last Name" => "Moran"));
// Use the hint function to specify which index to use
$cursor->hint(array("Last Name" => -1));
//Print the result
while($document = $cursor->getNext())
{
print_r($document);
}
See Chapter 4 for more details on how to create an index. It is also possible to use the php driver's
ensureIndex() function to create an index, as discussed there.
Note
Refining Queries with Conditional Operators
You can use conditional operators to refine your queries. PHP comes with a nice set of default conditional operators,
such as < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to). Now for the bad
news: you cannot use these operators with the PHP driver. Instead, you will need to use MongoDB's version of these
operators. Fortunately, MongoDB itself comes with a vast set of conditional operators (you can find more information
about these operators in Chapter 4). You can use all of these operators when querying for data through PHP, passing
them on through the find() function.
While you can use all these operators with the PHP driver, you must use specific syntax to do so; that is, you must
place them in an array, and pass this array to the find() function. The following sections will walk you through how to
use several commonly used operators.
Using the $lt, $gt, $lte, and $gte Operators
MongoDB's $lt , $gt , $lte , and $gte operators allow you to perform the same actions as the < , > , <= , and >=
operators, respectively. These operators are useful in situations where you want to search for documents that store
integer values.
You can use the $lt (less than) operator to find any kind of data for which the integer value is less than n ,
as shown in the following example:
// Connect to the database
$c = new MongoClient();
// Select the collection 'people' from the database 'contacts'
$collection = $c->contacts->people;
// Specify the conditional operator
$cond = array('Age' => array('$lt' => 30));
// Execute the query and store it under the $cursor variable
$cursor = $collection->find($cond);
 
 
Search WWH ::




Custom Search