PHP+ MongoDB

时间:2023-03-09 16:23:41
PHP+ MongoDB

环境:

uname -v
# SMP Debian 3.2.-+deb7u2

php -v
PHP 5.4.-~dotdeb. (cli) (built: Jun ::)
Copyright (c) - The PHP Group
Zend Engine v2.4.0, Copyright (c) - Zend Technologies

安装MongoDB驱动:

1、安装PECL(PHP 扩展模块)

sudo apt-get install php5-dev php5-cli php-pear

2、通过pecl安装驱动

sudo pecl install mongo

安装过程中有个提示,默认回车即可。

编辑php.ini文件:

sudo vi /etc/php5/fpm/php.ini

在文件最后添加一行:

extension=mongo.so

最后重启php服务:

sudo service php5-fpm restart 

测试

新建一个php文件:test.php,内容如下:

<?php
$user = array(
'first_name' => 'MongoDB',
'last_name' => 'Fan',
'tags' => array('developer','user')
);
// Configuration
$dbhost = 'localhost';
$dbname = 'test'; // Connect to test database
$m = new Mongo("mongodb://$dbhost");
$db = $m->$dbname; // Get the users collection
$c_users = $db->users; // Insert this new document into the users collection
$c_users->save($user);
?>

这是在mongodb的test数据库中的users表中插入一条记录。按mongodb的说法是,在数据库test的集合users中插入一个文档。

在浏览器中打开这个test.php页面,数据就插入到数据库中了。回到mongodb中看看是否有数据:

mongo test
MongoDB shell version: 2.6.
connecting to: test
> db.users.findOne()
{
"_id" : ObjectId("53b79360b2c88865388b4567"),
"first_name" : "MongoDB",
"last_name" : "Fan",
"tags" : [
"developer",
"user"
]
}
>

是的,可以看到php中的代码已经生效了。

在php中怎么读取mongodb的数据呢?

新建一个test2.php文件,内容如下:

<?php
// Configuration
$dbhost = 'localhost';
$dbname = 'test'; // Connect to test database
$m = new Mongo("mongodb://$dbhost");
$db = $m->$dbname; // Get the users collection
$c_users = $db->users; // Find the user with first_name 'MongoDB' and last_name 'Fan'
$user = array(
'first_name' => 'MongoDB',
'last_name' => 'Fan'
); $user = $c_users->findOne($user);
var_dump($user);
?>

在浏览器中打开test2.php就可以看到结果了。