未定义的属性:MongoDB的\驱动程序\管理:: $分贝

问题描述 投票:0回答:1

我有WAMP运行在Windows 10,一个本地的MongoDB数据库我使用的PHP版本7.2.10,阿帕奇35年4月2日,和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为未定义?

php mongodb wamp
1个回答
1
投票

工作的PHP代码,如下看起来这样。请注意存在一个链接到“供应商/ autoload.php”:

  $DB_CONNECTION_STRING="mongodb://YourCredentials";
  require '../../vendor/autoload.php';
  $manager = new MongoDB\Driver\Manager( $DB_CONNECTION_STRING );

然后,如果你使用的MongoDB \驱动程序\经理,MongoDB的驱动的现代版,你的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和多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);
© www.soinside.com 2019 - 2024. All rights reserved.