MongoClient类与MongoDB的\驱动程序\管理类

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

我希望得到您的建议对我的web项目。我使用PHP和MongoDB,但我迷茫的时候,我读了PHP文档这句话。

这个扩展,定义了这个类已被弃用。相反,应该使用MongoDB的扩展。替代这个类包括:MongoDB的\驱动程序\经理

我已经使用MongoClient班CRUD但看完这句话后,我试图MongoClient迁移到MongoDB的\驱动程序\经理。使用MongoDB的\驱动程序\管理器的连接被successed但我不能再:(

我的PHP版本是29年6月5日。蒙戈扩展的版本是1.7.0 MongoDB的扩展版本是1.2.9

我的问题是:我一定要使用MongoDB的\驱动程序\管理类?它比MongoClient班好?

php mongodb
2个回答
2
投票

下面是有关不推荐使用的语言功能一个很好的答案:What does PHP do with deprecated functions?

这里是与MongoDB的PHP中的正确用法:

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$filter = [];
$options = [
    'sort' => ['_id' => 1],
];

$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery('db.collection', $query);

foreach ($cursor as $document) {
//...
}

有很多教程使用PHP和MongoDB,例如CRUD操作:MongoDB PHP tutorial

总之:你不应该使用过时的功能,由于安全原因,因为它可以摆脱在未来PHP删除。因此,更好地更新你的代码。


0
投票

我个人碰到一个没有链接到“供应商/ 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.