2017-01-08 89 views
1

我最近升級到了PHP7以及PHP5.5的MongoDB驅動程序和舊的Mongo驅動程序。我已將所有函數從update()更改爲updateOne()和updateMany()以及remove()函數。MongoDB PHP驅動程序在執行updateOne時出錯

但是,我的應用程序第一次嘗試執行updateOne錯誤時,出現錯誤。數據庫連接代碼如下所示。 請注意,我添加了一個updateOne功能的構造函數考一次,我看到我收到的錯誤:

if (!extension_loaded('mongodb')) die("MongoDB is not installed!"); 
     try { 
      $this->connection = new MongoDB\Client('mongodb://'.$auth.self::HOST.':'.self::PORT.$authDb); 
      $this->database = $this->connection->selectDatabase(self::DBNAME); 

      # Test function, added due to errors 

      $this->connection->WIOC->settings->updateOne(array('_id' => 'xxx'), array('$set' => array('test' => 'yes'))); 
     } catch (MongoConnectionException $e) { 
      throw $e; 
     } 

我得到的錯誤是這樣的:

Fatal error: Uncaught Error: Call to undefined method MongoDB\Driver\BulkWrite::updateOne() in /Users/Idan/Sites/MyApp/include/vendor/mongodb/mongodb/src/Operation/Update.php:140 Stack trace: 0 /Users/Idan/Sites/MyApp/include/vendor/mongodb/mongodb/src/Operation/UpdateOne.php(77): MongoDB\Operation\Update->execute(Object(MongoDB\Driver\Server)) 1 /Users/Idan/Sites/MyApp/include/vendor/mongodb/mongodb/src/Collection.php(828): MongoDB\Operation\UpdateOne->execute(Object(MongoDB\Driver\Server)) 2 /Users/Idan/Sites/MyApp/include/mongoConnect.php(30): MongoDB\Collection->updateOne(Array, Array) 3 /Users/Idan/Sites/MyApp/include/mongoConnect.php(40): DBConnection->__construct() 4 /Users/Idan/Sites/MyApp/include/framework.php(6): DBConnection::instantiate() 5 /Users/Idan/Sites/MyApp/index.php(3): require('/Users/Idan/Sit...') 6 {main} thrown in /Users/Idan/Sites/MyApp/include/vendor/mongodb/mongodb/src/Operation/Update.php on line 140

的var_dump $ this-> connection-> MyApp-> settings顯示一個MongoDB \ Collection,所以我假設我使用了合適的較新的驅動程序。 甚至陌生人,這裏是爲對象的方法列表:

Array 
(
    [0] => __construct 
    [1] => __debugInfo 
    [2] => __toString 
    [3] => aggregate 
    [4] => bulkWrite 
    [5] => count 
    [6] => createIndex 
    [7] => createIndexes 
    [8] => deleteMany 
    [9] => deleteOne 
    [10] => distinct 
    [11] => drop 
    [12] => dropIndex 
    [13] => dropIndexes 
    [14] => find 
    [15] => findOne 
    [16] => findOneAndDelete 
    [17] => findOneAndReplace 
    [18] => findOneAndUpdate 
    [19] => getCollectionName 
    [20] => getDatabaseName 
    [21] => getManager 
    [22] => getNamespace 
    [23] => insertMany 
    [24] => insertOne 
    [25] => listIndexes 
    [26] => replaceOne 
    [27] => updateMany 
    [28] => updateOne 
    [29] => withOptions 
) 

任何想法有什麼不好?謝謝!

回答

0

您提供的代碼使用legacy MongoDB driver,因此與new one不兼容。

如果您實際安裝了最新的驅動程序,則通過使用MongoDB\Driver\Manager::executeBulkWrite方法可以實現任何類型更新(更新/插入/刪除)的正確方法。

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017'); 
$bulk = new MongoDB\Driver\BulkWrite; 
$bulk->update([ '_id' => 'xxx' ], [ '$set' => [ 'test' => 'yes' ]]); 
$manager->executeBulkWrite('DB.Collection', $bulk); 

完整樣本代碼在下文提供