我使用的是Windows 10 64位,xampp 3.2.2,PHP 5.6.30,PHP Extension Build VC11,MongoDB服务器版本:3.4.3。
我收到的错误如“致命错误:第4行的D:\ xampp \ htdocs \ test \ test1.php中找不到类'MongoClient'。”
以下是我正在使用的代码
CODE
<?php
// connect
$m = new MongoClient();
// select a database
$db = $m->cabin;
// select a collection (analogous to a relational database's table)
$collection = $db->user;
// find everything in the collection
$cursor = $collection->find();
// iterate through the results
foreach ($cursor as $document) {
echo $document["title"] . "\n";
}
?>
我在文件夹(D:\xampp\php\ext)
中添加了dll文件,并在php.ini (D:\xampp\php)
“extension = php_mongodb.dll”中添加了扩展名。但问题没有解决。
MongoDB (Mongo db正在运行)
user@DESKTOP-JCDJQ65 MINGW64 /d
$ mongo
MongoDB shell version v3.4.3
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.3
use cabin
switched to db cabin
show tables
bmessages
booking
cabins
club
country
customer
email
facilities
land
mschool
region
role
rooms
settings
tempuser
tour
user
userold
visit
答案 0 :(得分:2)
MongoClient
属于久已弃用的Mongo extension。新MongoDB extension使用Manager连接到数据库,例如
$m = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$cursor = $manager->executeQuery("cabin.user", new MongoDB\Driver\Query([]));
foreach ($cursor as $document) {
echo $document["title"] . "\n";
}
或使用任何更高级别的抽象库。例如。 https://github.com/mongodb/mongo-php-library提供与旧版驱动程序类似的界面。
答案 1 :(得分:1)
MongoDB \ Driver \ Manager负责维护与MongoDB的连接。
<强>连接强>
$mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");
列出数据库
$listdatabases = new MongoDB\Driver\Command(["listDatabases" => 1]);
$res = $mng->executeCommand("admin", $listdatabases);
阅读所有数据
$query = new MongoDB\Driver\Query([]);
$rows = $mng->executeQuery("database_name.collection_name", $query);
foreach ($rows as $row) {
echo "$row->name\n";
}
批量写入(同时执行两项或多项操作)
$bulk = new MongoDB\Driver\BulkWrite;
$doc = ['_id' => new MongoDB\BSON\ObjectID, 'name' => 'Toyota', 'price' => 26700];
$bulk->insert($doc);
$bulk->update(['name' => 'Audi'], ['$set' => ['price' => 52000]]);
$bulk->delete(['name' => 'Hummer']);
$mng->executeBulkWrite('testdb.cars', $bulk);