PHP提供mongodb驱动程序来连接mongoDB数据库。安装后, 我们可以使用php执行数据库操作。在这里, 我们使用Ubuntu 16.04创建示例。此示例包括以下步骤。
1)安装驱动程序
$ pecl install mongodb

2)编辑php.ini文件
它存储在apache服务器目录/etc/php/7.0/apache2/php.ini中
$ extension = mongodb.so

3)安装mongo-php库
以下是通过Composer安装此库的首选方法。
$ composer require mongodb/mongodb

4)创建PHP脚本
// connect.php
<?php
require 'vendor/autoload.php';
// Creating Connection
$con = new MongoDB\Client("mongodb://localhost:27017");
// Creating Database
$db = $con->srcmini;
// Creating Document
$collection = $db->employee;
// Insering Record
$collection->insertOne( [ 'name' =>'Peter', 'email' =>'peter@abc.com' ] );
// Fetching Record
$record = $collection->find( [ 'name' =>'Peter'] );
foreach ($record as $employe) {
echo $employe['name'], ': ', $employe['email']."<br>";
}
?>
5)执行PHP脚本
在本地主机服务器上执行此脚本。它将创建数据库并将数据存储到mongodb中。
localhost/php/connect.php

6)进入Mongo Shell
执行php脚本后, 我们可以在mongodb中看到创建的数据库。
$ mongo

6.1。显示数据库
以下命令用于显示数据库。
> show dbs

6.2。显示收藏
以下命令用于显示集合。
> show collections

6.3。访问记录
> db.employee.find()

好了, 一切正常。我们还可以执行其他数据库操作。
来源:
https://www.srcmini02.com/27172.html