Devs.site

Connect to MongoDB with PHP and query documents

MongoDB has a satisfying range of drivers that can connect applications with the database server and in this tutorial we will see how to do that with PHP 7.3, for which there's an extension that can be installed and enabled in a matter of minutes


We will do it all from the beginning:



Code

    <?php
    /**
    * Testing PHP connection with MongoDB
    * and getting documents from a database
    */

    // making sure the extension is loaded
    if (extension_loaded("mongodb")) {
        // catch exception and output details if it occurs
        try {
            // create the manager with the default server address
            $manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

            // this is the query that will get all documents
            $query = new MongoDB\Driver\Query([]);

            // execute query and return a cursor that can iterate over the results
            $cursor = $manager->executeQuery("mydb.users", $query);

            // show each returned document
            foreach ($cursor as $document) {
                var_dump($document);
            }
        } catch (MongoConnectionException $e) {
            var_dump($e);
        }
    }

Links


Requirements

This tutorial was tested with PHP 7.3 and MongoDB 4.0 on a Windows 10 system.

Visual Studio Code was used to edit the code

0 comments

Specify your e-mail if you want to receive notifications about new comments and replies