折腾了很久,网上的大多都过时了,不是下载的版本不对就是下载的包不对,基本都会在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

顺利的话会直接提示

  1. Build complete.
  2. Don’t forget to run ‘make test’.
  3. 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;

插入方法:

  1. <?php
  2. $collection = (new MongoDB\Client)->test->users;
  3. $insertOneResult = $collection->insertOne([
  4. ‘username’ => ‘admin’,
  5. ’email’ => ‘admin@example.com’,
  6. ‘name’ => ‘Admin User’,
  7. ]);
  8. printf(“Inserted %d document(s)\n”, $insertOneResult->getInsertedCount());
  9. var_dump($insertOneResult->getInsertedId())

查找方法:

  1. <?php
  2. $collection = (new MongoDB\Client)->test->zips;
  3. $document = $collection->findOne([‘_id’ => ‘94301’]);
  4. var_dump($document);

limit,skip相当于limit方法:

  1. $collection = (new MongoDB\Client)->test->restaurants;
  2. $cursor = $collection->find(
  3. [
  4. ‘cuisine’ => ‘Italian’,
  5. ‘borough’ => ‘Manhattan’,
  6. ],
  7. [
  8. ‘projection’ => [
  9. ‘name’ => 1,
  10. ‘borough’ => 1,
  11. ‘cuisine’ => 1,
  12. ],
  13. ‘limit’ => 4,
  14. ]
  15. );
  16. foreach($cursor as $restaurant) {
  17. var_dump($restaurant);
  18. };