Php Mongodb 简明教程
PHP & MongoDB - Overview
PHP 开发人员团队为 PHP 提供了 MongoDB 驱动程序,并提供了各种可用的资源。
要使用 PHP 连接到 MongoDB,第一步是在 php ext 目录中拥有 mongodb php 驱动程序 DLL,并启用它,然后使用 mongodb API 连接到数据库。
Connecting to MongoDB database
假设已在本机安装 MongoDB,并且使用的是默认端口,则可以使用以下语法连接到 MongoDB 数据库。
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
MongoDB 驱动程序管理器是执行所有 MongoDB 数据库操作的中心类。要通过构建一个命令然后执行它来连接到 MongoDB 数据库,我们先准备一个命令然后执行它。
$statistics = new MongoDB\Driver\Command(["dbstats" => 1]);
$cursor = $manager->executeCommand("mydb", $statistics);
在执行命令后如果 mydb 数据库不存在,它将被创建,否则将被连接。
PHP & MongoDB - Environment Setup
Install MongoDB database
使用 MongoDB - Environment Setup 遵循 MongoDB 安装步骤
Install PHP
使用 PHP 7 - Environment Setup 按照 PHP 安装步骤进行操作
PHP MongoDB Driver
要在 PHP 中使用 MongoDB,你需要使用 MongoDB PHP 驱动器。从网址 Download PHP Driver 下载该驱动器。务必下载它的最新版本。现在解压缩该 archives,并将 php_mongo.dll 放到你的 PHP 扩展目录中(默认情况下为“ext”),然后在 php.ini 文件中添加以下行−
extension = php_mongo.dll
在 Windows 中,确保 libsasl.dll 位于 Windows 的 PATH 中。此 dll 在 PHP 安装目录中提供。
PHP & MongoDB - Connecting Database
执行任何操作的第一步是创建一个管理器实例。
// Connect to MongoDB using Manager Instance
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
第二步是准备并执行一个命令以创建一个数据库,如果数据库不存在,则 MongoDB 会自动创建它。
// Create a Command Instance
$statistics = new MongoDB\Driver\Command(["dbstats" => 1]);
// Execute the command on the database
$cursor = $manager->executeCommand("myDb", $statistics);
Example
尝试以下示例以连接到 MongoDB 服务器 −
将以下示例复制粘贴到 mongodb_example.php −
<?php
try {
// connect to mongodb
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
echo "Connection to database successfully";
$statistics = new MongoDB\Driver\Command(["dbstats" => 1]);
$cursor = $manager->executeCommand("myDb", $statistics);
$statistics = current($cursor->toArray());
echo "<pre>";
print_r($statistics);
echo "</pre>";
} catch (MongoDB\Driver\Exception\Exception $e) {
echo "Exception:", $e->getMessage(), "\n";
}
?>
Output
访问部署在 Apache Web 服务器上的 mongodb_example.php 并验证输出。
Connection to database successfully
stdClass Object
(
[db] => myDb
[collections] => 0
[views] => 0
[objects] => 0
[avgObjSize] => 0
[dataSize] => 0
[storageSize] => 0
[totalSize] => 0
[indexes] => 0
[indexSize] => 0
[scaleFactor] => 1
[fileSize] => 0
[fsUsedSize] => 0
[fsTotalSize] => 0
[ok] => 1
)
PHP & MongoDB - Show Databases
执行任何操作的第一步是创建一个管理器实例。
// Connect to MongoDB using Manager Instance
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
第二步是准备并执行一个数据库上的命令,以显示可用的数据库列表。
// Create a Command Instance
$databaseList = new MongoDB\Driver\Command(["listDatabases" => 1]);
// Execute the command on the database
$cursor = $manager->executeCommand("admin", $databaseList);
Example
尝试以下示例,以列出 MongoDB 服务器中默认情况下可用的数据库 −
将以下示例复制粘贴到 mongodb_example.php −
<?php
try {
// connect to mongodb
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
// Create a Command Instance
$databaseList = new MongoDB\Driver\Command(["listDatabases" => 1]);
// Execute the command on the database
$cursor = $manager->executeCommand("admin", $databaseList);
$databases = current($cursor->toArray());
foreach ($databases->databases as $database) {
echo $database->name . "<br/>";
}
} catch (MongoDB\Driver\Exception\Exception $e) {
echo "Exception:", $e->getMessage(), "\n";
}
?>
PHP & MongoDB - Drop Database
执行任何操作的第一步是创建一个管理器实例。
// Connect to MongoDB using Manager Instance
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
第二步是准备并执行一个命令以删除数据库。
// Create a Command Instance
$dropDatabase = new MongoDB\Driver\Command(["dropDatabase" => 1]);
// Execute the command on the database
$cursor = $manager->executeCommand("myDb", $dropDatabase);
Example
尝试以下示例以在 MongoDB 服务器中删除数据库 −
将以下示例复制粘贴到 mongodb_example.php −
<?php
try {
// connect to mongodb
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
// Create a Command Instance
$dropDatabase = new MongoDB\Driver\Command(["dropDatabase" => 1]);
// Execute the command on the database
$cursor = $manager->executeCommand("myDb", $dropDatabase);
echo "Database dropped."
} catch (MongoDB\Driver\Exception\Exception $e) {
echo "Exception:", $e->getMessage(), "\n";
}
?>
PHP & MongoDB - Create Collection
执行任何操作的第一步是创建一个管理器实例。
// Connect to MongoDB using Manager Instance
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
第二步是准备并执行一条创建集合的命令。
// Create a Command Instance
$createCollection = new MongoDB\Driver\Command(["create" => "sampleCollection"]);
// Execute the command on the database
$cursor = $manager->executeCommand("myDb", $createCollection);
Example
尝试使用以下示例在 MongoDB 服务器中创建集合 −
将以下示例复制粘贴到 mongodb_example.php −
<?php
try {
// connect to mongodb
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
// Create a Command Instance
$createCollection = new MongoDB\Driver\Command(["create" => "sampleCollection"]);
// Execute the command on the database
$cursor = $manager->executeCommand("myDb", $createCollection);
echo "Collection created.";
} catch (MongoDB\Driver\Exception\Exception $e) {
echo "Exception:", $e->getMessage(), "\n";
}
?>
PHP & MongoDB - Drop Collection
执行任何操作的第一步是创建一个管理器实例。
// Connect to MongoDB using Manager Instance
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
第二步是准备并执行一个命令,以删除集合。
// Create a Command Instance
$createCollection = new MongoDB\Driver\Command(["drop" => "sampleCollection"]);
// Execute the command on the database
$cursor = $manager->executeCommand("myDb", $createCollection);
Example
尝试以下示例,以删除 MongoDB 服务器中的集合 −
将以下示例复制粘贴到 mongodb_example.php −
<?php
try {
// connect to mongodb
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
// Create a Command Instance
$dropCollection = new MongoDB\Driver\Command(["drop" => "sampleCollection"]);
// Execute the command on the database
$cursor = $manager->executeCommand("myDb", $dropCollection);
echo "Collection dropped."
} catch (MongoDB\Driver\Exception\Exception $e) {
echo "Exception:", $e->getMessage(), "\n";
}
?>
PHP & MongoDB - Display Collections
执行任何操作的第一步是创建一个管理器实例。
// Connect to MongoDB using Manager Instance
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
第二步是准备并执行一个数据库上的命令,以显示可用的集合列表。
// Create a Command Instance
$collectionList = new MongoDB\Driver\Command(["listCollections" => 1]);
// Execute the command on the database
$cursor = $manager->executeCommand("myDb", $collectionList);
Example
尝试以下示例,以列出 MongoDB 服务器中的数据库的集合 −
将以下示例复制粘贴到 mongodb_example.php −
<?php
try {
// connect to mongodb
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
// Create a Command Instance
$collectionList = new MongoDB\Driver\Command(["listCollections" => 1]);
// Execute the command on the database
$cursor = $manager->executeCommand("myDb", $collectionList);
$collections = $cursor->toArray();
foreach ($collections as $collection) {
echo $collection->name . "<br/>";
}
} catch (MongoDB\Driver\Exception\Exception $e) {
echo "Exception:", $e->getMessage(), "\n";
}
?>
PHP & MongoDB - Insert Document
执行任何操作的第一步是创建一个管理器实例。
// Connect to MongoDB using Manager Instance
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
第二步是准备并执行一个 bulkWrite 对象,以在集合中插入记录。
// Create a BulkWrite Object
$bulk = new MongoDB\Driver\BulkWrite(['ordered' => true]);
$bulk->insert(['First_Name' => "Mahesh",
'Last_Name' => 'Parashar',
'Date_Of_Birth' => '1990-08-21',
'e_mail' => 'mahesh_parashar.123@gmail.com',
'phone' => '9034343345']);
// Execute the commands.
$result = $manager->executeBulkWrite('myDb.sampleCollection', $bulk);
Example
尝试以下示例,以在 MongoDB 服务器的集合中插入文档 −
将以下示例复制粘贴到 mongodb_example.php −
<?php
try {
$bulk = new MongoDB\Driver\BulkWrite(['ordered' => true]);
$bulk->insert(['First_Name' => "Mahesh",
'Last_Name' => 'Parashar',
'Date_Of_Birth' => '1990-08-21',
'e_mail' => 'mahesh_parashar.123@gmail.com',
'phone' => '9034343345']);
$bulk->insert(['First_Name' => "Radhika",
'Last_Name' => 'Sharma',
'Date_Of_Birth' => '1995-09-26',
'e_mail' => 'radhika_sharma.123@gmail.com',
'phone' => '9000012345']);
$bulk->insert(['First_Name' => "Rachel",
'Last_Name' => 'Christopher',
'Date_Of_Birth' => '1990-02-16',
'e_mail' => 'rachel_christopher.123@gmail.com',
'phone' => '9000054321']);
$bulk->insert(['First_Name' => "Fathima",
'Last_Name' => 'Sheik',
'Date_Of_Birth' => '1990-02-16',
'e_mail' => 'fathima_sheik.123@gmail.com',
'phone' => '9000012345']);
// connect to mongodb
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$result = $manager->executeBulkWrite('myDb.sampleCollection', $bulk);
printf("Inserted %d document(s).\n", $result->getInsertedCount());
} catch (MongoDB\Driver\Exception\Exception $e) {
echo "Exception:", $e->getMessage(), "\n";
}
?>
PHP & MongoDB - Select Document
执行任何操作的第一步是创建一个管理器实例。
// Connect to MongoDB using Manager Instance
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
第二步是准备并执行一个 Query 对象以选择集合中的记录。
// Create a Query Object
$query = new MongoDB\Driver\Query(['First_Name' => "Radhika"]);
// Execute the query
$rows = $manager->executeQuery("testdb.sampleCollection", $query);
Example
尝试以下示例以在 MongoDB 服务器中选择文档 −
将以下示例复制粘贴到 mongodb_example.php −
<?php
try {
// connect to mongodb
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$filter = [];
// Create a Query Object
$query = new MongoDB\Driver\Query($filter);
// Execute the query
$rows = $manager->executeQuery("myDb.sampleCollection", $query);
foreach ($rows as $row) {
printf("First Name: %s, Last Name: %s.<br/>", $row->First_Name, $row->Last_Name);
}
} catch (MongoDB\Driver\Exception\Exception $e) {
echo "Exception:", $e->getMessage(), "\n";
}
?>
PHP & MongoDB - Update Document
执行任何操作的第一步是创建一个管理器实例。
// Connect to MongoDB using Manager Instance
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
第二步是准备并执行一个 bulkWrite 对象,以更新集合中的记录。
// Create a BulkWrite Object
$bulk = new MongoDB\Driver\BulkWrite(['ordered' => true]);
$bulk->update(['First_Name' => "Mahesh"],['$set' => ['e_mail' => 'maheshparashar@gmail.com']]);
// Execute the commands.
$result = $manager->executeBulkWrite('myDb.sampleCollection', $bulk);
Example
尝试以下示例,以更新 MongoDB 服务器中的文档 −
将以下示例复制粘贴到 mongodb_example.php −
<?php
try {
$bulk = new MongoDB\Driver\BulkWrite(['ordered' => true]);
$bulk->update(['First_Name' => "Mahesh"],['$set' => ['e_mail' => 'maheshparashar@gmail.com']]);
// connect to mongodb
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$result = $manager->executeBulkWrite('myDb.sampleCollection', $bulk);
printf("Updated %d document(s).\n", $result->getModifiedCount());
} catch (MongoDB\Driver\Exception\Exception $e) {
echo "Exception:", $e->getMessage(), "\n";
}
?>
PHP & MongoDB - Delete Document
执行任何操作的第一步是创建一个管理器实例。
// Connect to MongoDB using Manager Instance
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
第二步是准备并执行一个 bulkWrite 对象,以删除集合中的记录。
// Create a BulkWrite Object
$bulk = new MongoDB\Driver\BulkWrite(['ordered' => true]);
$bulk->delete(['First_Name' => "Mahesh"]);
// Execute the commands.
$result = $manager->executeBulkWrite('myDb.sampleCollection', $bulk);
Example
尝试以下示例,以删除 MongoDB 服务器中的集合中的文档 −
将以下示例复制粘贴到 mongodb_example.php −
<?php
try {
$bulk = new MongoDB\Driver\BulkWrite(['ordered' => true]);
$bulk->delete(['First_Name' => "Mahesh"]);
// connect to mongodb
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$result = $manager->executeBulkWrite('myDb.sampleCollection', $bulk);
echo "Document deleted."
} catch (MongoDB\Driver\Exception\Exception $e) {
echo "Exception:", $e->getMessage(), "\n";
}
?>
PHP & MongoDB - Insert Embedded Documents
执行任何操作的第一步是创建一个管理器实例。
// Connect to MongoDB using Manager Instance
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
第二步是准备并执行一个 bulkWrite 对象,以在集合中插入带有嵌入式文档的记录。
// Create a BulkWrite Object
$bulk = new MongoDB\Driver\BulkWrite(['ordered' => true]);
$bulk->insert(['title' => "MongoDB Overview",
'description' => 'MongoDB is no SQL database',
'by' => 'tutorials point',
'url' => 'http://www.tutorialspoint.com',
'comments' => [
['user' => "user1", 'message' => "My First Comment", 'dateCreated' => "20/2/2020", 'like' => 0],
['user' => "user2", 'message' => "My Second Comment", 'dateCreated' => "20/2/2020", 'like' => 0],
]]);
// Execute the commands.
$result = $manager->executeBulkWrite('myDb.sampleCollection', $bulk);
Example
尝试以下示例以在 MongoDB 服务器中的集合中插入带有嵌入式文档的文档 −
将以下示例复制粘贴到 mongodb_example.php −
<?php
try {
// connect to mongodb
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$bulk = new MongoDB\Driver\BulkWrite(['ordered' => true]);
$bulk->insert(['title' => "MongoDB Overview",
'description' => 'MongoDB is no SQL database',
'by' => 'tutorials point',
'url' => 'http://www.tutorialspoint.com',
'comments' => [
['user' => "user1", 'message' => "My First Comment", 'dateCreated' => "20/2/2020", 'like' => 0],
['user' => "user2", 'message' => "My Second Comment", 'dateCreated' => "20/2/2020", 'like' => 0],
]]);
$result = $manager->executeBulkWrite('myDb.sampleCollection', $bulk);
printf("Inserted %d document(s).\n", $result->getInsertedCount());
} catch (MongoDB\Driver\Exception\Exception $e) {
echo "Exception:", $e->getMessage(), "\n";
}
?>
PHP & MongoDB - Error Handling
MongoDB 驱动器操作会抛出数据库操作异常,并且可以使用以下语法轻松地捕获这些异常:
try {
} catch (MongoDB\Driver\Exception\Exception $e) {
echo "Exception:", $e->getMessage(), "<br/>";
echo "File:", $e->getFile(), "<br/>";
echo "Line:", $e->getLine(), "<br/>";
}
Example
尝试以下示例以检查 MongoDB 服务器中的数据库操作错误 −
将以下示例复制粘贴到 mongodb_example.php −
<?php
try {
// connect to mongodb
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
// Create a Command Instance
$createCollection = new MongoDB\Driver\Command(["create" => "sampleCollection"]);
// Execute the command on the database
$cursor = $manager->executeCommand("myDb", $createCollection);
echo "Collection created.";
} catch (MongoDB\Driver\Exception\Exception $e) {
echo "Exception:", $e->getMessage(), "<br/>";
echo "File:", $e->getFile(), "<br/>";
echo "Line:", $e->getLine(), "<br/>";
}
?>
PHP & MongoDB - Limit Records
执行任何操作的第一步是创建一个管理器实例。
// Connect to MongoDB using Manager Instance
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
第二步是准备并执行一个 Query 对象,以记录集合中的记录,并传递它过滤器和选项以限制搜索结果。
$filter = [];
$options = ['limit' => 1];
// Create a Query Object
$query = new MongoDB\Driver\Query($filter, $options);
// Execute the query
$rows = $manager->executeQuery("testdb.sampleCollection", $query);
Example
尝试以下示例以限制 MongoDB 服务器中的搜索结果 −
将以下示例复制粘贴到 mongodb_example.php −
<?php
try {
// connect to mongodb
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$filter = [];
$options = ['limit' => 1];
// Create a Query Object
$query = new MongoDB\Driver\Query($filter, $options);
// Execute the query
$rows = $manager->executeQuery("myDb.sampleCollection", $query);
foreach ($rows as $row) {
printf("First Name: %s, Last Name: %s.<br/>", $row->First_Name, $row->Last_Name);
}
} catch (MongoDB\Driver\Exception\Exception $e) {
echo "Exception:", $e->getMessage(), "\n";
}
?>
PHP & MongoDB - Sorting Records
执行任何操作的第一步是创建一个管理器实例。
// Connect to MongoDB using Manager Instance
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
第二步是准备并执行一个 Query 对象以选择集合中的记录,并传递筛选器和选项以对记录进行排序。
$filter = [];
// Sort in Descending Order, For ascending order pass 1
$options = ['sort' => ['First_Name' => -1]];
// Create a Query Object
$query = new MongoDB\Driver\Query($filter, $options);
// Execute the query
$rows = $manager->executeQuery("testdb.sampleCollection", $query);
Example
尝试以下示例以限制 MongoDB 服务器中的搜索结果 −
将以下示例复制粘贴到 mongodb_example.php −
<?php
try {
// connect to mongodb
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$filter = [];
$options = ['limit' => 3, 'sort' => ['First_Name' => -1]];
// Create a Query Object
$query = new MongoDB\Driver\Query($filter, $options);
// Execute the query
$rows = $manager->executeQuery("myDb.sampleCollection", $query);
foreach ($rows as $row) {
printf("First Name: %s, Last Name: %s.<br/>", $row->First_Name, $row->Last_Name);
}
} catch (MongoDB\Driver\Exception\Exception $e) {
echo "Exception:", $e->getMessage(), "\n";
}
?>