MongoDB环境配置已经完成,如下图所示,但是程序中(PHP7.4.12)始终无法加载 MongoClient类,下面用了其它方案来解决这个问题。
<?php $m = new MongoClient(); // 连接默认主机和端口为:mongodb://localhost:27017 $db = $m->test; // 获取名称为 "test" 的数据库 exit; 使用如上代码测试MongoDb连接的时候: Fatal error: Uncaught Error: Class 'MongoClient' not foun
如何处理上述问题呢,在另外一篇博文中找到了答案,先用 get_declared_classes() 查看当前已经加载的类
<?php $list = get_declared_classes(); foreach ($list as $v){ if(strpos($v, 'MongoDB') !== false){ echo $v .PHP_EOL; } }
运行结果
MongoDB\BSON\Binary MongoDB\BSON\DBPointer MongoDB\BSON\Decimal128 MongoDB\BSON\Int64 MongoDB\BSON\Javascript MongoDB\BSON\MaxKey MongoDB\BSON\MinKey MongoDB\BSON\ObjectId MongoDB\BSON\Regex MongoDB\BSON\Symbol MongoDB\BSON\Timestamp MongoDB\BSON\Undefined MongoDB\BSON\UTCDateTime MongoDB\Driver\BulkWrite MongoDB\Driver\ClientEncryption MongoDB\Driver\Command MongoDB\Driver\Cursor MongoDB\Driver\CursorId MongoDB\Driver\Manager MongoDB\Driver\Query MongoDB\Driver\ReadConcern MongoDB\Driver\ReadPreference MongoDB\Driver\Server MongoDB\Driver\ServerApi MongoDB\Driver\ServerDescription MongoDB\Driver\TopologyDescription MongoDB\Driver\Session MongoDB\Driver\WriteConcern MongoDB\Driver\WriteConcernError MongoDB\Driver\WriteError MongoDB\Driver\WriteResult MongoDB\Driver\Exception\RuntimeException MongoDB\Driver\Exception\ServerException MongoDB\Driver\Exception\ConnectionException MongoDB\Driver\Exception\WriteException MongoDB\Driver\Exception\AuthenticationException MongoDB\Driver\Exception\BulkWriteException MongoDB\Driver\Exception\CommandException MongoDB\Driver\Exception\ConnectionTimeoutException MongoDB\Driver\Exception\EncryptionException MongoDB\Driver\Exception\ExecutionTimeoutException MongoDB\Driver\Exception\InvalidArgumentException MongoDB\Driver\Exception\LogicException MongoDB\Driver\Exception\SSLConnectionException MongoDB\Driver\Exception\UnexpectedValueException MongoDB\Driver\Monitoring\CommandFailedEvent MongoDB\Driver\Monitoring\CommandStartedEvent MongoDB\Driver\Monitoring\CommandSucceededEvent MongoDB\Driver\Monitoring\ServerChangedEvent MongoDB\Driver\Monitoring\ServerClosedEvent MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent MongoDB\Driver\Monitoring\ServerOpeningEvent MongoDB\Driver\Monitoring\TopologyChangedEvent MongoDB\Driver\Monitoring\TopologyClosedEvent MongoDB\Driver\Monitoring\TopologyOpeningEvent
当前环境 PHP 7.4.12 (cli),由此可见压根没有MongoClient类,于是根据上述结果,找了另外处理方式
<?php $manager = new MongoDB\Driver\Manager("mongodb://localhost:27017"); $filter = array(); $options = []; $query = new MongoDB\Driver\Query($filter, $options); $cursor = $manager->executeQuery("mydb.col", $query); foreach($cursor as $document) { var_dump($document); } exit;
运行结果:终于拿到了想要的结果