PHP操作MongoDB数据库需要使用MongoDB扩展,可以通过以下步骤安装:
pecl install mongodb
安装完成后,在php.ini文件中添加以下行:
extension=mongodb.so
连接MongoDB数据库需要使用MongoDB\Client类,示例代码如下:
$client = new MongoDB\Client("mongodb://localhost:27017");
其中,mongodb://localhost:27017表示MongoDB服务器的地址和端口。
选择数据库和集合需要使用MongoDB\Database和MongoDB\Collection类,示例代码如下:
$db = $client->testdb;
$collection = $db->testcollection;
其中,testdb表示数据库名称,testcollection表示集合名称。
插入数据需要使用MongoDB\Collection的insertOne或insertMany方法,示例代码如下:
$result = $collection->insertOne(['name' => 'John', 'age' => 30]);
其中,insertOne方法插入一条数据,insertMany方法插入多条数据。
查询数据需要使用MongoDB\Collection的find方法,示例代码如下:
$result = $collection->find(['name' => 'John']);
其中,find方法返回一个MongoDB\Driver\Cursor对象,可以使用foreach循环遍历结果。
更新数据需要使用MongoDB\Collection的updateOne或updateMany方法,示例代码如下:
$collection->updateOne(['name' => 'John'], ['$set' => ['age' => 31]]);
其中,updateOne方法更新符合条件的一条数据,updateMany方法更新符合条件的多条数据。
删除数据需要使用MongoDB\Collection的deleteOne或deleteMany方法,示例代码如下:
$collection->deleteOne(['name' => 'John']);
其中,deleteOne方法删除符合条件的一条数据,deleteMany方法删除符合条件的多条数据。