0

I'm using laravel 5.2 and MongoDB 3.2.

I want to test if connection with is ok before my app starts (i can't use DB facade), in the monolog configuration. If connection is not ok, i will use logging in file.

By recommendation, i'm testing MongoClient, Mongo and MongoDB\Client, and using whatever is enabled.

I'm trying to test mongo connect as the following:

$mongoClient = new \MongoDB\Client('mongodb://localhost:27017');
$mongoClient->selectCollection('mydb', 'mycollection');

That's the return:

Client {   
    +manager: Manager {#21}
    +uri: "mongodb://localhost:27017"   
    +typeMap: [
        array => "MongoDB\Model\BSONArray",
        document => "MongoDB\Model\BSONDocument",
        root => "MongoDB\Model\BSONDocument"   
    ]
}

Finnaly, my questions:

  • Exists a way to use DB facade before app starts?
  • How and what is the right way to test MongoDB connection with PHP?

If you has another suggestion, i will be thankful.

1
  • 1
    Finnaly i get the exception when fire: $mongoClient->mydb->mycollection->findOne(). This solve my problem, but my questions persist. :) Commented Nov 10, 2016 at 13:48

2 Answers 2

2

According to PHP document, the driver connects to the database lazily (http://php.net/manual/en/mongodb-driver-manager.getservers.php), the only way to test connection should be actually execute commands like findOne() stated in yours comment.

In addition, if the name of DB or Collection is uncertain at the point, you can use listDatabases() method which also throws exceptions if connection fails.

Sign up to request clarification or add additional context in comments.

Comments

0

using this way you can check MongoDB connection with PHP:

$connection = new MongoClient(); // connects to localhost:27017
$connection = new MongoClient( "mongodb://example.com" ); // connect to a remote host (default port: 27017)
$connection = new MongoClient( "mongodb://example.com:65432" ); // connect to a remote host at a given port

1 Comment

No, this will not trigger any errors or exceptions. (Remember I need to do something that works for the 3 classes I listed)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.