duanlan4801 2013-11-06 13:44
浏览 144
已采纳

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?
  • 写回答

1条回答 默认 最新

  • duanguangsong2380 2013-11-06 15:00
    关注

    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.
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?