How to use PDO to access NoSQL databases (e.g., MongoDB) from PHP?

PDO stands for PHP Data Objects, and it is a database access abstraction layer in PHP that provides a consistent way to interact with various databases, including MySQL, PostgreSQL, and SQLite. However, PDO does not support NoSQL databases like MongoDB natively.

To access MongoDB from PHP using PDO, you can follow these steps:

  1. Install the MongoDB driver: Start by installing the MongoDB extension for PHP. You can use the following command to install it using PECL:
pecl install mongodb
  1. Enable the MongoDB extension: After installing the extension, you need to enable it in the PHP configuration. Open the php.ini file and add the following line:
extension=mongodb.so
  1. Connect to the MongoDB server: You can use the MongoDB PHP Library to connect to the MongoDB server. Here's an example of connecting and selecting a database:
// Replace the connection details with your own $dsn = 'mongodb://username:password@localhost:27017'; $database = 'mydatabase'; $mongoClient = new MongoDB\Client($dsn); $collection = $mongoClient->$database->mycollection;
  1. Perform CRUD operations: Now you can use PDO-like methods provided by the MongoDB PHP Library to perform CRUD operations on the database. Here are some examples:

Insert a document:

$document = ['name' => 'John Doe', 'age' => 25]; $collection->insertOne($document);

Fetch documents:

$documents = $collection->find(); foreach ($documents as $document) { echo $document['name'] . ' ' . $document['age'] . "\n"; }

Update a document:

$filter = ['name' => 'John Doe']; $update = ['$set' => ['age' => 30]]; $collection->updateOne($filter, $update);

Delete a document:

$filter = ['name' => 'John Doe']; $collection->deleteOne($filter);

These are just a few examples of how to use PDO-like methods to interact with a MongoDB database from PHP. You can refer to the official MongoDB PHP Library documentation for more detailed usage instructions and available methods.