Database Reference
In-Depth Information
[6] => pmoran@example.com
[7] => pmoran@office.com
)
[Phone] => 617-546-8428
[Age] => 60
)
Listing All Documents
While you can use the findOne() function to list a single document, you will use the find() function for pretty much
everything else. Don't misunderstand, please: you can find a single document with the find() function by limiting
your results; but if you are unsure about the number of documents to be returned, or if you are expecting more than
one document, then the find() function is your friend.
As detailed in the previous chapters, the find() function has many, many options that you can use to filter your
results to suit just about any circumstance you can imagine. We'll start off with a few simple examples and build from there.
First, let's see how you can display all the documents in a certain collection using PHP and the find() function.
The only thing that you should be wary of when printing out multiple documents is that each document is returned
in an array, and that each array needs to be printed individually. You can do this using PHP's while() function.
As just indicated, you will need to instruct the function to print each document before proceeding with the next one.
The getNext() command gets the next document in the cursor from MongoDB; this command effectively returns the
next object in the cursor and advances the cursor. The following snippet lists all the documents found in a collection:
// 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();
// For each document it finds within the collection, print the contents
while ($document = $cursor->getNext())
{
print_r($document);
}
You can implement the syntax for the preceding example several different ways. For example, a faster way
to execute the preceding command would look like this: $cursor = $c->contacts->people->find() . For the
sake of clarity, however, code examples like this one will be split up into two lines in this chapter, leaving more room
for comments.
Note
At this stage, the resulting output would still show only two arrays, assuming you have added the documents described
previously in this chapter (and nothing else). If you were to add more documents, then each document would be printed in
its own array. Granted, this doesn't look pretty; however, that's nothing you can't fix with a little additional code.
 
 
Search WWH ::




Custom Search