未定义属性:MongoDBDriverManager::$db

2022-03-28 00:00:00 mongodb wamp php

我有一个在Windows10的WAMP上运行的本地MongoDB数据库,我使用的是PHP版本7.2.10、Apache 2.4.35和MongoDB扩展1.5.3。我正在测试一个非常简单的Web应用程序,当我尝试通过php脚本将数据发送到数据库时,收到以下错误:

PHP Notice:  Undefined property: MongoDBDriverManager::$db in 
C:wamp64wwwphp	est.php

有关文件test.php的相关部分如下所示:

$objectId = new MongoDBBSONObjectId();
$dbhost = "127.0.0.1:27017";
$dbname = "db";
$m = new MongoDBDriverManager("mongodb://localhost:27017");
var_dump($m);
$db = $m->$dbname;
属性未定义会导致另一个错误:Fatal error: Uncaught Error: Call to a member function selectCollection() on null,这会导致脚本失败。

是什么原因导致属性MongoDBDriverManager::$db未定义?

php

运行推荐答案代码如下所示。请注意是否存在指向‘Vendor/autoload.php’的链接:

  $DB_CONNECTION_STRING="mongodb://YourCredentials";
  require '../../vendor/autoload.php';
  $manager = new MongoDBDriverManager( $DB_CONNECTION_STRING );

如果您使用的是MongoDB驱动程序的现代版本MongoDBDriverManager,您的CRUD操作将如下所示:

在集合中创建文档:

$bulkWrite = new MongoDBDriverBulkWrite;
$doc = ['name' => 'John', age => 33, profession => 'Guess what?'];
$bulkWrite->insert($doc);
$manager->executeBulkWrite('db.MyCollection', $bulkWrite);

按名称读取集合中的文档,但有限制:

$filter = ['name' => 'John'];
$options = ['limit' => 2];
$query = new MongoDBDriverQuery($filter, $options);
$manager->executeQuery('db.MyCollection', $query);

由mongoDB_id读取集合中的文档,但有限制:

$filter = ['_id' => new MongoDBBSONObjectID( '5bdf54e6d722dc000f0aa6c2' )];
$options = ['limit' => 2];
$query = new MongoDBDriverQuery($filter, $options);
$manager->executeQuery('db.MyCollection', $query);    

更新集合中的文档:(阅读有关选项upsert和multihere的详细信息)

$bulkWrite = new MongoDBDriverBulkWrite;
$filter = ['name' => 'John'];
$update = ['$set' => ['name' => 'Smith', age: 35, profession => 'Guess what?']];
$options = ['multi' => false, 'upsert' => false];
$bulkWrite->update($filter, $update, $options);
$manager->executeBulkWrite('db.MyCollection', $bulkWrite);    

删除集合中的单据-删除:

$bulkWrite = new MongoDBDriverBulkWrite;
$filter = ['name' => 'John', age => 35];
$options = ['limit' => 1];
$bulkWrite->delete($filter, $options);
$manager->executeBulkWrite('db.MyCollection', $bulkWrite);

相关文章