Search code examples
phpmongodbmamp

Cannot connect mongoDB and PHP


I am successfully running mongoDB v3.2.10 in terminal on macOS 10.11.6 and MAMP server running php 7.0.8.

When I try to reach mongo via php code like:

<?php
  // connect to mongodb
  $m = new MongoClient(); 
?>

at url: http://localhost:8888/Mongo/login.php

I get:

This site can’t be reached

localhost refused to connect.

When I reach mongo on the native port at url: http://localhost:27017/Mongo/login.php

I get:

It looks like you are trying to access MongoDB over HTTP on the native driver port.

Any idea what am I missing here?


Solution

  • Looks like you are using the built-in PHP Mongo DB clients. There is a new MongoDB driver that replace that. You will have to install it.

    http://php.net/manual/en/set.mongodb.php

    The newer MongoDB extension replaces the built-in PHP Mongo DB client. You'll also want to use the composer PHPLIB MongoDB client from here: http://php.net/manual/en/mongodb.tutorial.library.php

    use MongoDB\Client;
    
    try {
        $mongoDbClient = new Client('mongodb://localhost:27017');
    } catch (Exception $error) {
        echo $error->getMessage(); die(1);
    }