使用PHP7使用新的MongoDB驱动程序

以前,在CentOS 6 + PHP 5.6的环境下,有一个用PHP操作MongoDB的脚本,但是在CentOS 7+PHP 7中运行时出现了错误。我注意到竟然没有安装驱动程序,因此尝试安装时发现了一些微妙的变化,特此记录。

以下的内容也在手册中提供了。

MongoDB 驱动程序 (旧版)

如上所述,迄今为止存在的事物被视为旧版本。

安装PHP和驱动程序。

我使用remi存储库来处理PHP相关事务。
如果是PHP7.0的情况,需要启用名为remi-php70的存储库,并且对于php-*模块,应该在其前面加上php70-。
总之,最小配置只需要cli、mongodb和多字节支持。

sudo yum --enablerepo=remi,remi-php70 install php70-php-cli php70-php-mbstring php70-php-pecl-mongodb

环境变量

当安装完成后,从Shell中输入php即可。

$ php -v
PHP 5.6.xx (cli) (built: xxxx)
Copyright (c) 1997-2016 The PHP Group
Zend Engine vx.x.x, Copyright (c) 1998-2016 Zend Technologies

要使用php7,需要先激活预先安装的php5.6。

$ source /opt/remi/php70/enable

据说需要设置环境变量。如果你决定不再使用7以外的版本,最好在.bashrc等文件中写下来,这样或许会更幸福。

放入图书馆

当您查看教程时,建议您根据您使用纯PHP的情况,使用这个库进行安装。所以,请按照建议,在composer中进行安装。

范例 lì)

如果做到这个地步,接下来的重点是方法在One和Many中基本上是分开的,与旧版本几乎相同。

<?php
require_once dirname(__FILE__) . '/vendor/autoload.php';

$client = new MongoDB\Client("mongodb://localhost:27017");
$db = $client->selectDatabase('example');
$collection = $db->selectCollection('gochiusa');


$collection->insertOne([ 'name' => '宇治松千夜', 'shop' => '甘兎庵', 'cv' => '佐藤聡美' ]);
$collection->insertOne([ 'name' => '桐間紗路', 'shop' => 'フルール・ド・ラパン', 'cv' => '内田真礼']);
$collection->insertMany([
    [ 'name' => '保登心愛', 'shop' => 'ラビットハウス', 'cv' => '佐倉綾音' ],
    [ 'name' => '香風智乃', 'shop' => 'ラビットハウス', 'cv' => '水瀬いのり' ],
    [ 'name' => '天々座理世', 'shop' => 'ラビットハウス', 'cv' => '種田梨沙' ],
]);

$chiya = $collection->findOne(['name' => '宇治松千夜']);

$rabbithouse = $collection->find(['shop' => 'ラビットハウス']);
foreach($rabbithouse as $rabbit){
    print_r($rabbit);
}
bannerAds