Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
2 views
in SQL by (6.1k points)

I want to establish a connection between PHP 7 and MongoDB, by using pecl, I installed the "new" MongoDB driver. The MongoDB version is 1.1.8 which I can see from phpInfo() output, but I am unable to figure out how to initiate a connection from PHP code :p . I have listed the code which includes so many attempts to connect.

// new fashion way

$connection = new MongoDB\Driver\Client();

// or by using old fashion way

$conn = new MongoClient();

// random try :p

$randConn = new MongoDB\Client();

and in both cases, it is displaying: defined class exception. I am using Ubuntu 14.04 LTS OS. please help me out with this issue. 

1 Answer

0 votes
by (11.7k points)

Whatever information you have provided, says that you are using a low-level PHP driver for MongoDB. You can go through the documentation for both of them and you can read it here.

This driver helps to talk to MongoDB and is written to be a bare bone layer. Which has resulted in it having missed so many important features. Instead, these conventional methods have been split out into a layer written in PHP, the MongoDB Library. You can interact with MongoDB by using this library. 

This library has to be installed with Composer which is a package manager for PHP. See also Get Composer: Installation on Linux/OSX

For Instance:

composer require "mongodb/mongodb=^1.0.0"

Once you have it installed, you can try connecting using:

<?php

 require 'vendor/autoload.php';

 $collection = (new MongoDB\Client("mongodb://127.0.0.1:27017"))->dbname->coll;

?>

You can also go through the following articles. 

Related questions

0 votes
0 answers
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Mar 6, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer

Browse Categories

...