Querying
Querying by _id Every object inserted is automatically assigned a unique _id field, which is often a useful field to use in queries. Suppose that we wish to find the document we just inserted. Inserting adds and _id field to the document, so we can query by that: "joe"); $people->insert($person); // now $joe has an _id field $joe = $people->findOne(array("_id" => $person['_id'])); ?> ]]> Unless the user has specified otherwise, the _id field is a MongoId. The most common mistake is attepting to use a string to match a MongoId. Keep in mind that these are two different datatypes, and will not match each other in the same way that the string "array()" is not the same as an empty array. For example: "joe"); $people->insert($person); // convert the _id to a string $pid = $person['_id'] . ""; // FAILS - $pid is a string, not a MongoId $joe = $people->findOne(array("_id" => $pid)); ?> ]]>
Arrays Suppose that we wish to find all documents with an array element of a given value. For example, documents with a "gold" award, such as: This can be done with a simple query, ignoring the fact that "awards" is an array: find(array("awards" => "gold")); ?> ]]> Suppose we are querying for a more complex object, if each element of the array were an object itself, such as: Still ignoring that this is an array, we can use dot notation to query the subobject: find(array("awards.first place" => "gold")); ?> ]]> Notice that it doesn't matter that there is a space in the the field name (although it may be best not to use spaces, just to make things more readable).