PHP Manual

Finding Documents using MongoCollection::findOne()

To show that the document we inserted in the previous step is stored in the database, we can do a simple MongoCollection::findOne() operation to get a single document from the collection. This method is useful when there is only one document matching the query or you are only interested in one result.

= new MongoClient();
$collection $connection->database->collectionName;

$document $collection->findOne();
var_dump$document );

The above example will output:

array(6) {
  object(MongoId)#8 (1) {
    string(24) "4e2995576803fab768000000"
  string(7) "MongoDB"
  string(8) "database"
  array(2) {
  array(3) {
    string(5) "0.9.7"
    string(5) "0.9.8"
    string(5) "0.9.9"

Note that there is an _id field that has been added automatically to your document. _id is the "primary key" field. If your document does not specify one, the driver will add one automatically.

If you specify your own _id field, it must be unique to the collection. See the example here:

= new MongoClient();
$db $connection->database;

$db->foo->insert(array("_id" => 1));
// this will throw an exception
$db->foo->insert(array("_id" => 1));

// this is fine, as it is a different collection
$db->bar->insert(array("_id" => 1));

By default the driver will ensure the server has acknowledged the write before returning. You can optionally turn this behaviour off by passing array("w" => 0) as the second argument. This means that the driver should not wait for the database to acknowledge the write and would not throw the duplicate _id exception.

See Also

MongoCollection::findOne() for more information about finding data.

MongoId goes into more detail on unique ids.

The writes section covers writes in more depth, and the Write Concerns chapter goes into details of the various Write Concern options.

PHP Manual