Requirements
mongod
on command prompt to run mongodb server)php composer.phar require "mongodb/mongodb=^1.0.0"
to install the MongoDB library)If everything is ok you are ready to move on.
Check For Php installation
if not sure check Php installation by running php -v
on command prompt will return something like this
PHP 7.0.6 (cli) (built: Apr 28 2016 14:12:14) ( ZTS ) Copyright (c) 1997-2016 The PHP Group Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies
Check For MongoDB installation
Check MongoDB installation by running mongo --version
will return MongoDB shell version: 3.2.6
Check For Composer installation
Check for Composer installation by running php composer.phar --version
will return Composer version 1.2-dev (3d09c17b489cd29a0c0b3b11e731987e7097797d) 2016-08-30 16:12:39
`
Connecting to MongoDB from php
<?php
//This path should point to Composer's autoloader from where your MongoDB library will be loaded
require 'vendor/autoload.php';
// when using custom username password
try {
$mongo = new MongoDB\\Client('mongodb://username:password@localhost:27017');
print_r($mongo->listDatabases());
} catch (Exception $e) {
echo $e->getMessage();
}
// when using default settings
try {
$mongo = new MongoDB\\Client('mongodb://localhost:27017');
print_r($mongo->listDatabases());
} catch (Exception $e) {
echo $e->getMessage();
}
The above code will connect using MongoDB composer library(mongodb/mongodb
) included as vendor/autoload.php
to connect to the MongoDB server running on port
: 27017
. If everything is ok it will connect and list an array, if exception occurs connecting to MongoDB server the message will be printed.
CREATE(Inserting) into MongoDB