注意: php不同的版本对应的mongodb版本是不同的,用法也完全不同
php mogodb扩展下载地址:https://pecl.php.net/package/mongodb
mongodb说明:https://docs.mongodb.com/php-library/current/tutorial/crud/
安装1.6
下载wget https://pecl.php.net/get/mongodb-1.6.0.tgz
解压tar zxf mongodb-1.6.0.tgz
进入 cd mongodb-1.6.0/
phpize
./configure --with-php-config=php-config
顺利的话会直接提示
Build complete.
Don't forget to run 'make test'.
Installing shared extensions: /usr/lib64/php/modules/
至此,生成so文件成功
下一步打开php扩展就ok了
主要就是在配置文件中加一行代码
extension=mongodb.so
安装mongodb驱动:
composer require mongodb/mongodb
对于指定的链接可以这样写:
$collection = (new MongoDB\Client("mongodb://username:password@ip:port"))->database->table;
插入方法:
<?php
$collection = (new MongoDB\Client)->test->users;
$insertOneResult = $collection->insertOne([
'username' => 'admin',
'email' => 'admin@example.com',
'name' => 'Admin User',
]);
printf("Inserted %d document(s)\n", $insertOneResult->getInsertedCount());
var_dump($insertOneResult->getInsertedId())
查找方法:
<?php
$collection = (new MongoDB\Client)->test->zips;
$document = $collection->findOne(['_id' => '94301']);
var_dump($document);
limit,skip相当于limit方法:
$collection = (new MongoDB\Client)->test->restaurants;
$cursor = $collection->find(
[
'cuisine' => 'Italian',
'borough' => 'Manhattan',
],
[
'projection' => [
'name' => 1,
'borough' => 1,
'cuisine' => 1,
],
'limit' => 4,
]
);
foreach($cursor as $restaurant) {
var_dump($restaurant);