Database Reference
In-Depth Information
Using Query Operators
Whatever you can do in the MongoDB shell, you can also accomplish using the PHP driver. As you've seen in the
previous chapters, the shell includes dozens of options for filtering your results. For example, you can use dot
notation; sort or limit the results; skip, count, or group a number of items; or even use regular expressions, among
many other things. The following sections will walk you through how to use most of these options with the PHP driver.
Querying for Specific Information
As you might remember from Chapter 4, you can use dot notation to query for specific information in an embedded
object in a document. For instance, if you want to find one of your contacts for which you know a portion of the
address details, you can use dot notation to find this, as in the following example:
// Connect to the database
$c = new MongoClient();
// Select the collection 'people' from the database 'contacts'
$collection = $c->contacts->people;
// Use dot notation to search for a document in which the place
// is set to "Newton"
$address = array("Address.Place" => "Newton");
// Execute the query and store it under the $cursor variable
$cursor = $collection->find($address);
// For each document it finds within the collection, print the ID
// and its contents
while ($document = $cursor->getNext())
{
print_r($document);
}
In a similar fashion, you can search for information in a document's array by specifying one of the items in that
array, such as an e-mail address. Because an e-mail address is (usually) unique, the findOne() function will suffice in
this example:
// Connect to the database
$c = new MongoClient();
// Select the collection 'people' from the database 'contacts'
$collection = $c->contacts->people;
// Define the e-mail address you want to search for under $email
$email = array("E-Mail" => " vw@example.com ");
// Find the very first person in the collection matching the e-mail address
print_r($collection->findOne($email));
As expected, this example returns the first document that matches the e-mail address vw@example.com —the
address of Victoria Wood in this case. The document is returned in the form of an array:
Array (
[_id] => MongoId Object ( )
[First Name] => Victoria
[Last Name] => Wood
[Address] => Array (
[Street] => 50 Ash lane
[Place] => Ystradgynlais
 
Search WWH ::




Custom Search