Hướng dẫn dùng mongodb driver trong PHP

Php cung cấp trình điều khiển mongodb để kết nối với cơ sở dữ liệu mongoDB. Sau khi cài đặt nó, chúng ta có thể thực hiện các hoạt động cơ sở dữ liệu bằng cách sử dụng php. Ở đây, chúng tôi đang sử dụng Ubuntu 16.04 để tạo một ví dụ. Ví dụ này bao gồm các bước sau.

Các bài viết liên quan:

  • Connection Methods trong MongoDB
  • MongoDB BI connector là gì? Cách sử dụng
  • Kết nối MongoDB với Java
  • Tạo Collection trong MongoDB
  • Marketing 4.0 là gì? tìm hiểu về marketing 4.0

Tóm tắt nội dung

Cài đặt trình điều khiển

$ pecl install mongodb  

Hướng dẫn dùng mongodb driver trong PHP

Chỉnh sửa tệp php.ini

Nó được lưu trữ trong thư mục máy chủ apache /etc/php/7.0/apache2/php.ini

$ extension = mongodb.so  

Hướng dẫn dùng mongodb driver trong PHP

Cài đặt thư viện mongo-php

Sau đây là cách ưa thích để cài đặt thư viện này với Composer.

$ composer require mongodb/mongodb  

Hướng dẫn dùng mongodb driver trong PHP

Tạo tập lệnh Php

// connect.php

<?php  
require 'vendor/autoload.php';  
// Creating Connection  
$con = new MongoDB\Client("mongodb://localhost:27017");  
// Creating Database  
$db = $con->javatpoint;  
// Creating Document  
$collection = $db->employee;  
// Insering Record  
$collection->insertOne( [ 'name' =>'Peter', 'email' =>'[email protected]' ] );  
// Fetching Record  
$record = $collection->find( [ 'name' =>'Peter'] );  
foreach ($record as $employe) {  
echo $employe['name'], ': ', $employe['email']."<br>";  
}  
?>  

Thực thi Php Script

Thực thi tập lệnh này trên máy chủ localhost. Nó sẽ tạo cơ sở dữ liệu và lưu trữ dữ liệu vào mongodb.

localhost/php/connect.php  

Hướng dẫn dùng mongodb driver trong PHP

Nhập Mongo Shell

Sau khi thực thi tập lệnh php, chúng ta có thể thấy cơ sở dữ liệu đã tạo trong mongodb.

$ mongo

Hiển thị cơ sở dữ liệu

Lệnh sau được sử dụng để hiển thị cơ sở dữ liệu.

> show dbs  

Hiển thị Collection

Lệnh sau được sử dụng để hiển thị các Collection.

> show collections  

Truy cập hồ sơ

> db.employee.find ()

Tất cả đã được thiết lập, điều này đang hoạt động tốt. Chúng tôi cũng có thể thực hiện các hoạt động cơ sở dữ liệu khác.

Để sử dụng MongoDB với PHP, bạn cần sử dụng MongoDB PHP Driver. Tải Driver từ Tải PHP Driver. Bạn nên tải phiên bản mới nhất. Sau đó unzip và đặt php_mongo.dll vào trong thư mục PHP Extension của bạn (ext theo mặc định) và thêm dòng sau vào php.ini file:


extension=php_mongo.dll

Tạo kết nối và Chọn một Database

Để tạo kết nối, bạn cần xác định tên của Database, nếu nó không tồn tại thì MongoDB sẽ tự động tạo nó.

Bạn theo dõi code sau:


mydb;
   echo "Database mydb selected";
?>

Khi code trên được biên dịch và thực thi, kết quả là:


Connection to database successfully
Database mydb selected

Tạo một Collection

Bạn theo dõi code sau để tạo một Collection:


mydb;
   echo "Database mydb selected";
   $collection = $db->createCollection("mycol");
   echo "Collection created succsessfully";
?>

Khi code trên được biên dịch và thực thi, kết quả là:


Connection to database successfully
Database mydb selected
Collection created succsessfully

Chèn một Document

Để chèn một Document vào trong MongoDB, bạn sử dụng phương thức insert().

Bạn theo dõi code sau:

mydb;
   echo "Database mydb selected";
   $collection = $db->mycol;
   echo "Collection selected succsessfully";
   $document = array( 
      "title" => "MongoDB", 
      "description" => "database", 
      "likes" => 100,
      "url" => "http://www.tutorialspoint.com/mongodb/",
      "by", "tutorials point"
   );
   $collection->insert($document);
   echo "Document inserted successfully";
?>

Khi code trên được biên dịch và thực thi, kết quả là:


Connection to database successfully
Database mydb selected
Collection selected succsessfully
Document inserted successfully

Tìm tất cả Document

Để chọn tất cả Document từ Collection, bạn sử dụng phương thức find().

Bạn theo dõi code sau:


mydb;
   echo "Database mydb selected";
   $collection = $db->mycol;
   echo "Collection selected succsessfully";

   $cursor = $collection->find();
   // iterate cursor to display title of documents
   foreach ($cursor as $document) {
      echo $document["title"] . "\n";
   }
?>

Khi code trên được biên dịch và thực thi, kết quả là:


Connection to database successfully
Database mydb selected
Collection selected succsessfully
{
   "title": "MongoDB"
}

Cập nhật một Document

Để cập nhật một Document, bạn cần sử dụng phương thức update().

Trong ví dụ dưới, chúng ta sẽ cập nhật title của Document đã chèn. Chương trình sau minh họa điều này.


mydb;
   echo "Database mydb selected";
   $collection = $db->mycol;
   echo "Collection selected succsessfully";

   // now update the document
   $collection->update(array("title"=>"MongoDB"), array('$set'=>array("title"=>"MongoDB Tutorial")));
   echo "Document updated successfully";
   // now display the updated document
   $cursor = $collection->find();
   // iterate cursor to display title of documents
   echo "Updated document";
   foreach ($cursor as $document) {
      echo $document["title"] . "\n";
   }
?>

Khi code trên được biên dịch và thực thi, kết quả là:


mydb;
   echo "Database mydb selected";
?>
0

Xóa một Document

Để xóa một Document, bạn cần sử dụng phương thức remove().

Trong ví dụ dưới, chúng ta sẽ xóa các Document mà có title là MongoDB Tutorial. Chương trình sau minh họa điều này.


mydb;
   echo "Database mydb selected";
?>
1

Khi code trên được biên dịch và thực thi, kết quả là:


mydb;
   echo "Database mydb selected";
?>
2

Trong ví dụ trên, tham số thứ hai là kiểu Boolean và được sử dụng cho trường justOne của phương thức remove().

Các phương thức findOne(), save(), limit(), skip(), sort(), ... của MongoDB sẽ làm việc tương tự như đã trình bày ở trên.