PHP MongoDB Connection
Hello everyone
PHP is a popular programming language that is often used for web development. One of the most common tasks in web development is connecting to a database to store and retrieve data. MongoDB is a popular NoSQL database that is often used in conjunction with PHP. This medium post will discuss how to connect to a MongoDB database using PHP.
Get Sercan KARA’s stories in your inbox
Join Medium for free to get updates from this writer.
To connect to a MongoDB database using PHP, you will need to install the PHP MongoDB driver. This can be done using the following command:
pecl install mongodbOnce the PHP MongoDB driver is installed, you can connect to a MongoDB database using the following code:
<?php
// Connect to the MongoDB server
$client = new MongoDB\Client("mongodb://localhost:27017");
// Select a database
$db = $client->mydatabase;
// Select a collection
$collection = $db->mycollection;
// Insert a document
$document = array( "title" => "Calvin and Hobbes", "author" => "Bill Watterson" );
$collection->insertOne($document);
// Find all documents
$cursor = $collection->find();
// Iterate over the result set
foreach ($cursor as $document) {
echo $document["title"] . "\n";
}In the code above, we create a new MongoDB\Client object and pass the connection string to the MongoDB server. The connection string has the format mongodb://<host>:<port>. We then select the database and collection that we want to work with using the -> operator.
Once we have a reference to the collection, we can use the insertOne method to insert a new document into the collection. We can then use the find method to retrieve all records in the collection and iterate over the result set using a foreach loop.
That’s all there is to it! With just a few lines of code, you can connect to a MongoDB database and start storing and retrieving data using PHP.






