折腾了很久,网上的大多都过时了,不是下载的版本不对就是下载的包不对,基本都会在configure阶段报错,后来根据官方的文档才找到解决方案
php mogodb扩展:https://pecl.php.net/package/mongodb
mongodb说明:https://docs.mongodb.com/ecosystem/drivers/php/
根据说明:需要安装mongodb-1.4或者1.3
安装1.4
下载wget https://pecl.php.net/get/mongodb-1.4.4.tgz
解压tar zxf mongodb-1.4.4.tgz
进入 cd mongodb-1.4.4/
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
增加:
网上的大多数php版本的5.X的,对于5.X来说需要的扩展文件是mongo.so文件,对应的下载链接:https://pecl.php.net/package/mongo
都是比较老的版本,对于7.X版本需要生成的扩展文件是mongodb.so文件,对应的下载链接在这里:https://pecl.php.net/package/mongodb
原文:
Drivers
The currently maintained driver is the mongodb extension available from PECL. This driver can be used stand-alone, although it is very bare-bones. You should consider using the driver with the complimentary PHP library, which implements a more full-featured API on top of the bare-bones driver. Further information on this architecture may be found in the PHP.net documentation.
The mongo extension available from PECL is an older, legacy driver for PHP 5.x. The mongo
extension is no longer maintained and new projects are advised to use the mongodb
extension and PHP library. A community-developed Mongo PHP Adapter project implements the legacy mongo
extension’s API using the new mongodb
extension and PHP library, which may be useful for those wishing to migrate existing applications.
原文链接:https://docs.mongodb.com/ecosystem/drivers/php/
对于7.X的mongodb驱动,需要下载mongodb library,也就是说除了so文件扩展,还需要库来驱动使用mongodb,注意7.X的mongodb.so与5.X的mongo.so是不兼容的,他们的方法不通用,在网上找到的mongodb的使用代码目前大部分是不能运行的。library下载链接:https://github.com/mongodb/mongo-php-library
可以使用composer更方便:
$ composer require mongodb/mongodb
有关library的使用方法见文档:https://docs.mongodb.com/php-library/current/tutorial/crud/
例如:
对于指定的链接可以这样写:
$collection = (new MongoDB\Client("mongodb://username:password@ip:port"))->database->table;
插入方法:
<?php
$collection = (new MongoDB\Client)->test->users;
$insertOneResult = $collection->insertOne([
'username' => 'admin',
'email' => '[email protected]',
'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);
};