Tutorial
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.

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

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

Powyższy przykład wyświetli:

array(6) {
  ["_id"]=>
  object(MongoId)#8 (1) {
    ["$id"]=>
    string(24) "4e2995576803fab768000000"
  }
  ["name"]=>
  string(7) "MongoDB"
  ["type"]=>
  string(8) "database"
  ["count"]=>
  int(1)
  ["info"]=>
  array(2) {
    ["x"]=>
    int(203)
    ["y"]=>
    int(102)
  }
  ["versions"]=>
  array(3) {
    [0]=>
    string(5) "0.9.7"
    [1]=>
    string(5) "0.9.8"
    [2]=>
    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:

<?php
$connection 
= 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.


Tutorial
PHP Manual