MongoDB PHP 扩展学习笔记
简介
MongoDB是一个非关系型数据库,PHP扩展提供了MongoDB的支持。使用MongoDB PHP扩展可以进行数据的增删改查,以及其他操作。
安装MongoDB PHP扩展
- 下载MongoDB PHP扩展
- 打开php.ini文件,添加以下内容
Copy Codeextension=mongodb.so
- 重启Web服务器
连接MongoDB
使用MongoDB PHP扩展可以很方便地连接MongoDB。
phpCopy Code<?php
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
?>
以上代码将创建一个MongoDB连接。
插入数据
使用MongoDB PHP扩展插入数据也很简单。
phpCopy Code<?php
$bulk = new MongoDB\Driver\BulkWrite;
$doc = ['_id' => new MongoDB\BSON\ObjectID, 'name' => 'John Doe', 'age' => 30];
$bulk->insert($doc);
$manager->executeBulkWrite('testdb.testcoll', $bulk);
?>
以上代码将插入一条数据到testdb数据库的testcoll集合中。
查询数据
使用MongoDB PHP扩展查询数据也很简单。
phpCopy Code<?php
$filter = ['name' => 'John Doe'];
$options = [];
$query = new MongoDB\Driver\Query($filter, $options);
$rows = $manager->executeQuery('testdb.testcoll', $query);
foreach($rows as $row){
echo $row->name;
}
?>
以上代码将查询testdb数据库的testcoll集合中name为John Doe的数据。
更新数据
使用MongoDB PHP扩展更新数据也很简单。
phpCopy Code<?php
$bulk = new MongoDB\Driver\BulkWrite;
$filter = ['name' => 'John Doe'];
$newObj = ['$set' => ['age' => 40]];
$bulk->update($filter, $newObj);
$manager->executeBulkWrite('testdb.testcoll', $bulk);
?>
以上代码将更新testdb数据库的testcoll集合中name为John Doe的数据的age字段为40。
删除数据
使用MongoDB PHP扩展删除数据也很简单。
phpCopy Code<?php
$bulk = new MongoDB\Driver\BulkWrite;
$filter = ['name' => 'John Doe'];
$bulk->delete($filter);
$manager->executeBulkWrite('testdb.testcoll', $bulk);
?>
以上代码将删除testdb数据库的testcoll集合中name为John Doe的数据。
以上是MongoDB PHP扩展学习笔记的例子。