PHP 想要往 MongoDB 里增删查改数据,需要先安装 mongodb 或 mongo 扩展模块,一般两个都装上:
cd /usr/local/src/ wget https://pecl.php.net/get/mongodb-1.3.0.tgz tar zxvf mongodb-1.3.0.tgz cd mongodb-1.3.0 /usr/local/php/bin/phpize ./configure --with-php-config=/usr/local/php/bin/php-config make && make install echo 'extension = "mongodb.so"' >> /usr/local/php/etc/php.ini /usr/local/php/bin/php -m | grep mongo /etc/init.d/php-fpm restart
cd /usr/local/src/ wget https://pecl.php.net/get/mongo-1.6.16.tgz tar xf mongo-1.6.16.tgz cd mongo-1.6.16/ /usr/local/php/bin/phpize ./configure --with-php-config=/usr/local/php/bin/php-config make && make install echo 'extension = "mongo.so"' >> /usr/local/php/etc/php.ini /usr/local/php/bin/php -m | grep mongo /etc/init.d/php-fpm restart
测试 PHP 是否能连接并操作 MongoDB:
[root@localhost ~]$ cat /data/www/1.php // 将该文件放到 nginx 数据目录 <?php $m = new MongoClient(); // 连接默认主机和端口为:mongodb://localhost:27017 $db = $m->test; // 获取名称为 "test" 的数据库 $collection = $db->createCollection("runoob"); // 创建一个集合 echo "集合创建成功"; ?>
[root@localhost ~]$ curl http://localhost/1.php
集合创建成功