我最近从PHP 5.5和旧的Mongo驱动程序升级到PHP7和MongoDB驱动程序。我已经将所有函数从update()更改为updateOne()和updateMany(),以及remove()函数。
但是,我的应用程序第一次尝试执行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;
}
我得到的错误是:
致命错误:未捕获错误:调用未定义的方法 MongoDB \ Driver \ BulkWrite :: updateOne()in /Users/Idan/Sites/MyApp/include/vendor/mongodb/mongodb/src/Operation/Update.php:140 堆栈跟踪:0 /Users/Idan/Sites/MyApp/include/vendor/mongodb/mongodb/src/Operation/UpdateOne.php(77): MongoDB \ Operation \ Update->执行(对象(MongoDB \ Driver \ Server))1 /Users/Idan/Sites/MyApp/include/vendor/mongodb/mongodb/src/Collection.php(828): MongoDB的\操作\ UpdateOne->执行(对象(MongoDB的\驱动\服务器)) 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}抛出 /Users/Idan/Sites/MyApp/include/vendor/mongodb/mongodb/src/Operation/Update.php 的 在线 140
var_dump $ this-> connection-> MyApp->设置显示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 :(得分:1)
您提供的代码使用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);