Mongo PHP写操作是同步还是异步?

I would like to find out how Mongo writes to disk by default. Async or Sync?

When I do:

$collection->insert(array("a" => 42));

is it sync? The documentation says the param w is set to 1 by default and that should cause the insert to return only when data has been written to disk. As opposed to w => 0 (Unacknowledged) where data are actually written in an asynchronous way (fire and forget).

So my questions are

  1. Can anyone confirm my observations above?
  2. It seems to me it follows that insert only throws MongoCursorException when in sync mode (w => 1), am I right?

Your assumptions are correct.

Since I was writing mondodb unit tests anyway, I put one together to test this.

public function testWriteConcern()
{
    $mongo = new MongoClient("mongodb://localhost/");

    $db = $mongo->test;
    $collection = $db->test;
    $collection->remove();
    $collection->insert(array("_id"=>"unique"));
    try {
        $collection->insert(array("_id"=>"unique"));
        $this->fail("Expected duplicate key exception (w=1)");
    }
    catch (MongoCursorException $e) {}

    try {
        $collection->insert(array("_id"=>"unique"), array("w" => 0));
        $this->fail("Expected duplicate key exception (w=0)");
    }
    catch (MongoCursorException $e) {}  

    $db->drop();
    $mongo->close();
}

As you expected, no MongoCursorException is thrown when the write concern is set to 0.

There was 1 failure:

1) MongoDBTest::testWriteConcern
Expected duplicate key exception (w=0)

FAILURES!
Tests: 1, Assertions: 0, Failures: 1.