Everything in between MongoDB and PHP
suggest changeRequirements
- A MongoDB server, usually on port 27017. Start it with
mongodfrom a command prompt. - PHP installed as CGI or FPM, plus the MongoDB extension. That extension is not part of a default PHP build.
- The Composer library
mongodb/mongodb. From the project root,php composer.phar require "mongodb/mongodb=^1.0.0"installs the 1.x library used by these examples. Check the library docs before requiring a current 2.x release, because some APIs differ.
If everything is ok you are ready to move on.
Check the PHP installation
If you are not sure PHP is installed, run php -v. It returns 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
The examples below were checked with the legacy mongo shell (mongo --version, for example MongoDB shell version: 3.2.6). Current server installs use mongosh instead.
Check For Composer installation
Check Composer with php composer.phar --version. An older development build looked like 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 code above loads the mongodb/mongodb library through vendor/autoload.php and connects to MongoDB on port 27017. listDatabases() returns a traversable list of database info. A connection failure throws an exception, and the catch block prints its message.
CREATE(Inserting) into MongoDB
<?php
// MongoDB uses collections rather than tables.
//Use $mongo instance to select the database and collection
//NOTE: if database(here demo) and collection(here beers) are not found in MongoDB both will be created automatically by MongoDB.
$collection = $mongo->demo->beers;
//Using $collection we can insert one document into MongoDB
//document is similar to row in SQL.
$result = $collection->insertOne( [ 'name' => 'Hinterland', 'brewery' => 'BrewDog' ] );
//Every inserted document will have a unique id.
echo "Inserted with Object ID '{$result->getInsertedId()}'";
?>
This uses the $mongo client from the connection example. The library converts the PHP array to BSON. MongoDB stores BSON, not JSON text. Each document has an _id. getInsertedId() returns the id of the inserted document.
READ(Find) in MongoDB
<?php
//use find() method to query for records, where parameter will be array containing key value pair we need to find.
$result = $collection->find( [ 'name' => 'Hinterland', 'brewery' => 'BrewDog' ] );
// find() returns a cursor, not an array. foreach reads each matching document.
foreach ($result as $entry) {
echo $entry['_id'], ': ', $entry['name'], "\n";
}
?>
Drop in MongoDB
<?php
// drop() removes the whole collection. It does not take a document filter.
// To delete matching documents, use deleteMany(['name' => 'Hinterland']).
$result = $collection->drop();
// The command result is an array. ok is 1 when the drop succeeded.
print_r($result['ok']);
?>
There are many methods that can be performed on $collection see Official documentation from MongoDB