我在Windows 10的WAMP上运行一个本地MongoDB数据库。我使用的是PHP版本7.2.10,Apache 2.4.35和MongoDB扩展1.5.3。我有一个正在测试的非常简单的Web应用程序,当我尝试通过php脚本将数据发送到数据库时,出现此错误:
PHP Notice: Undefined property: MongoDB\Driver\Manager::$db in
C:\wamp64\www\php\test.php
相关文件test.php
的相关部分如下所示:
$objectId = new MongoDB\BSON\ObjectId();
$dbhost = "127.0.0.1:27017";
$dbname = "db";
$m = new MongoDB\Driver\Manager("mongodb://localhost:27017");
var_dump($m);
$db = $m->$dbname;
属性未定义会导致另一个错误:Fatal error: Uncaught Error: Call to a member function selectCollection() on null
,该错误会导致脚本失败。
是什么导致属性MongoDB\Driver\Manager::$db
未定义?
答案 0 :(得分:1)
工作的php代码如下所示。请注意'vendor / autoload.php'的链接:
$DB_CONNECTION_STRING="mongodb://YourCredentials";
require '../../vendor/autoload.php';
$manager = new MongoDB\Driver\Manager( $DB_CONNECTION_STRING );
然后,如果您使用MongoDB驱动程序的现代版本MongoDB \ Driver \ Manager,则CRUD操作将如下所示:
创建集合中的文档:
$bulkWrite = new MongoDB\Driver\BulkWrite;
$doc = ['name' => 'John', age => 33, profession => 'Guess what?'];
$bulkWrite->insert($doc);
$manager->executeBulkWrite('db.MyCollection', $bulkWrite);
阅读文档集中的文档的名称,并带有限制:
$filter = ['name' => 'John'];
$options = ['limit' => 2];
$query = new MongoDB\Driver\Query($filter, $options);
$manager->executeQuery('db.MyCollection', $query);
由MongoDb _id读取集合中的文档,但有以下限制:
$filter = ['_id' => new MongoDB\BSON\ObjectID( '5bdf54e6d722dc000f0aa6c2' )];
$options = ['limit' => 2];
$query = new MongoDB\Driver\Query($filter, $options);
$manager->executeQuery('db.MyCollection', $query);
集合中的更新文档:((有关选项upsert和multi here的更多信息)
$bulkWrite = new MongoDB\Driver\BulkWrite;
$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 MongoDB\Driver\BulkWrite;
$filter = ['name' => 'John', age => 35];
$options = ['limit' => 1];
$bulkWrite->delete($filter, $options);
$manager->executeBulkWrite('db.MyCollection', $bulkWrite);