PHP & MongoDB Examples
- PHP & MongoDB - Connect Database
- PHP & MongoDB - Show Databases
- PHP & MongoDB - Drop Database
- PHP & MongoDB - Create Collection
- PHP & MongoDB - Drop Collection
- PHP & MongoDB - Display Collections
- PHP & MongoDB - Insert Document
- PHP & MongoDB - Select Document
- PHP & MongoDB - Update Document
- PHP & MongoDB - Delete Document
- PHP & MongoDB - Embedded Documents
- PHP & MongoDB - Error Handling
- PHP & MongoDB - Limiting Records
- PHP & MongoDB - Sorting Records
PHP & MongoDB Useful Resources
PHP & MongoDB - Quick Guide
PHP & MongoDB - Overview
PHP developer team has provided MongoDB Driver for PHP and have various resources available for it.
First step in connecting to MongoDB using PHP is to have mongodb PHP driver dll in php ext directory and enable it in php.ini and then use mongodb API to connect to the database.
Connecting to MongoDB database
Suppose, MongoDB is installed locally and using default port then following syntax connects to MongoDB database.
$uri = "mongodb://localhost:27017"; // connect to mongodb $client = new MongoDB\Client($uri); echo "Connection to database successful.
";
MongoDB Driver Manager is the central class to do all the operations on mongodb database. To connect to mongodb database, we connect to database by first preparing a command and then executing it.
<?php
require __DIR__ . '\vendor\autoload.php';
$uri = "mongodb://localhost:27017";
// connect to mongodb
$client = new MongoDB\Client($uri);
echo "Connection to database successful.<br/>";
// select a database
$db = $client->myDb;
$stats=$db->command(array('dbStats' => 1));
// Convert the cursor to an array and get the first result document
$statistics = $stats->toArray()[0];
// Output the statistics
echo "Database Statistics:\n";
print_r($statistics)
?>
Once command is executed, if mydb database is not present, it will be created otherwise, it will be connected.
Output
Connection to database successful. Database Statistics: MongoDB\Model\BSONDocument Object ( [storage:ArrayObject:private] => Array ( [db] => myDb [collections] => 4 [views] => 0 [objects] => 7 [avgObjSize] => 58 [dataSize] => 406 [storageSize] => 81920 [indexes] => 4 [indexSize] => 81920 [totalSize] => 163840 [scaleFactor] => 1 [fsUsedSize] => 157193351168 [fsTotalSize] => 295202451456 [ok] => 1 ) )
PHP & MongoDB - Environment Setup
Install MongoDB database
Follow the MongoDB installation steps using MongoDB - Environment Setup
Install PHP
Follow the PHP installation steps using PHP - Installation
PHP MongoDB Driver Installation
Before you start using MongoDB in your PHP programs, you need to make sure that you have MongoDB Extension and Mongo Driver and PHP set up on the machine. You can check PHP - Installation for PHP installation on your machine. Now, let us check how to set up MongoDB CLIENT.
Install PIE and Composer
Install MongoDB Extension
We need to install PIE as pie.phar from https://github.com/php/pie/releases in order to install mongodb extensions in PHP.
Run the following command to install mongodb extensions.
php pie.phar install mongodb/mongodb-extension
Manually, we've downloaded php_mongodb-2.1.4-8.5-ts-vs17-x86_64.zip and extracted php_mongodb-2.1.4-8.5-ts-vs17-x86_64.dll, renamed to php_mongodb.dll and placed under ext directory.
php.ini is modified to have mongodb extension.
extension=php_mongodb.dll
Install MongoDB Driver for PHP
Create a PHP project and run the following command to configure mongodb dependencies.
composer require mongodb/mongodb
Composer will manage all dependencies and create a autoload.php file under vendor sub folder.
Connect to Database
To connect database, you need to specify the database name, if the database doesn't exist then MongoDB creates it automatically.
Following is the code snippet to connect to the database −
<?php
require __DIR__ . '\vendor\autoload.php';
try {
$uri = "mongodb://localhost:27017";
// connect to mongodb
$client = new MongoDB\Client($uri);
echo "Connection to database successful.";
// select a database
$db = $client->mydb;
echo "Database mydb selected.";
} catch (MongoDB\Driver\Exception\Exception $e) {
echo "Exception:", $e->getMessage(), "\n";
}
?>
Output
Now, let's compile and run the above program to create our database myDb.
On executing, the above program gives you the following output.
Database mydb selected
PHP & MongoDB - Connect Database
Steps to Connect MongoDB Database
First step to do any operation is to create a MongoDB Client instance.
$uri = "mongodb://localhost:27017"; // connect to mongodb $client = new MongoDB\Client($uri);
Second step is to prepare and execute a command on a database if the database doesn't exist then MongoDB creates it automatically.
// select a database
$db = $client->myDb;
// execute a command
$cursor=$db->command(array('dbStats' => 1));
Example - Connecting MongoDB Database and Printing Database Statistics
Try the following example to connect to a MongoDB server −
index.php
<?php
require __DIR__ . '\vendor\autoload.php';
$uri = "mongodb://localhost:27017";
// connect to mongodb
$client = new MongoDB\Client($uri);
echo "Connection to database successfully";
// select a database
$db = $client->myDb;
// execute a command
$cursor=$db->command(array('dbStats' => 1));
$statistics = current($cursor->toArray());
echo "<pre>";
print_r($statistics);
echo "</pre>";
?>
Output
Access the index.php deployed on apache web server and verify the output.
Connection to database successfully
MongoDB\Model\BSONDocument Object
(
[storage:ArrayObject:private] => Array
(
[db] => myDb
[collections] => 4
[views] => 0
[objects] => 7
[avgObjSize] => 58
[dataSize] => 406
[storageSize] => 81920
[indexes] => 4
[indexSize] => 81920
[totalSize] => 163840
[scaleFactor] => 1
[fsUsedSize] => 158140493824
[fsTotalSize] => 295202451456
[ok] => 1
)
)
PHP & MongoDB - Show Databases
Steps to Show Databases
First step to do any operation is to create a MongoDB Client instance.
$uri = "mongodb://localhost:27017"; // connect to mongodb $client = new MongoDB\Client($uri);
Second step is to prepare and execute a command on admin database to show the list of databases available.
// select admin database
$db = $client->admin;
// execute a command
$cursor=$db->command(array('listDatabases' => 1));
Example - Getting List of MongoDB Databases
Try the following example to get list of databases on a MongoDB server −
index.php
<?php
require __DIR__ . '\vendor\autoload.php';
$uri = "mongodb://localhost:27017";
// connect to mongodb
$client = new MongoDB\Client($uri);
// select admin database
$db = $client->admin;
// execute a command
$cursor=$db->command(array('listDatabases' => 1));
$databases = current($cursor->toArray());
foreach ($databases->databases as $database) {
echo $database->name . "<br/>";
}
?>
Output
Access the index.php deployed on apache web server and verify the output.
admin config local myDb mydata newdata sampleDB test
PHP & MongoDB - Drop Database
Steps to Drop Database
First step to do any operation is to create a MongoDB Client instance.
$uri = "mongodb://localhost:27017"; // connect to mongodb $client = new MongoDB\Client($uri);
Second step is to prepare and execute a command to drop a database.
// select a database
$db = $client->myDb;
// execute a command
$cursor=$db->command(array('dropDatabase' => 1));
Example - Dropping a MongoDB Databases
Try the following example to drop a database from a MongoDB server −
index.php
<?php
require __DIR__ . '\vendor\autoload.php';
$uri = "mongodb://localhost:27017";
// connect to mongodb
$client = new MongoDB\Client($uri);
// select a database
$db = $client->myDb;
// execute a command
$cursor=$db->command(array('dropDatabase' => 1));
echo "Database dropped."
?>
Output
Access the index.php deployed on apache web server and verify the output.
Database dropped.
PHP & MongoDB - Create Collection
Steps to Create a Collection
First step to do any operation is to create a MongoDB Client instance.
$uri = "mongodb://localhost:27017"; // connect to mongodb $client = new MongoDB\Client($uri);
Second step is to prepare and execute a command to create a collection.
// select a database
$db = $client->myDb;
// execute a command
$cursor=$db->command(array('create' => 'sampleCollection'));
Example - Create a MongoDB Collection
Try the following example to create a collection in a MongoDB database −
index.php
<?php
require __DIR__ . '\vendor\autoload.php';
$uri = "mongodb://localhost:27017";
// connect to mongodb
$client = new MongoDB\Client($uri);
// select a database
$db = $client->myDb;
// execute a command
$cursor=$db->command(array('create' => 'sampleCollection'));
echo "Collection created."
?>
Output
Access the index.php deployed on apache web server and verify the output.
Collection created.
PHP & MongoDB - Drop Collection
Steps to Drop a Collection
First step to do any operation is to create a MongoDB Client instance.
$uri = "mongodb://localhost:27017"; // connect to mongodb $client = new MongoDB\Client($uri);
Second step is to prepare and execute a command to drop a collection.
// select a database
$db = $client->myDb;
// execute a command
$cursor=$db->command(array('drop' => 'sampleCollection'));
Example - Drop a MongoDB Collection
Try the following example to drop a collection from a MongoDB database −
index.php
<?php
require __DIR__ . '\vendor\autoload.php';
$uri = "mongodb://localhost:27017";
// connect to mongodb
$client = new MongoDB\Client($uri);
// select a database
$db = $client->myDb;
// execute a command
$cursor=$db->command(array('drop' => 'sampleCollection'));
echo "Collection dropped."
?>
Output
Access the index.php deployed on apache web server and verify the output.
Collection dropped.
PHP & MongoDB - Display Collections
Steps to Display a List of Collections
First step to do any operation is to create a MongoDB Client instance.
$uri = "mongodb://localhost:27017"; // connect to mongodb $client = new MongoDB\Client($uri);
Second step is to prepare and execute a command to get list of collections.
// select a database
$db = $client->myDb;
// execute a command
$cursor=$db->command(array('listCollections' => 1));
Example - List MongoDB Collections
Try the following example to list collections of a MongoDB database −
index.php
<?php
require __DIR__ . '\vendor\autoload.php';
$uri = "mongodb://localhost:27017";
// connect to mongodb
$client = new MongoDB\Client($uri);
// select a database
$db = $client->myDb;
// create a collection
$cursor=$db->command(array('create' => 'sampleCollection'));
// execute a command
$cursor=$db->command(array('listCollections' => 1));
$collections = $cursor->toArray();
foreach ($collections as $collection) {
echo $collection->name . "<br/>";
}
?>
Output
Access the index.php deployed on apache web server and verify the output.
sampleCollection
PHP & MongoDB - Inserting Documents
Steps to Insert a Document in a collection
First step to do any operation is to create a MongoDB Client instance.
$uri = "mongodb://localhost:27017"; // connect to mongodb $client = new MongoDB\Client($uri);
Second step is to prepare and execute a command to select a collection and insert document using insertOne() command.
// select a collection of a database
$collection = $client->selectCollection('myDb', 'sampleCollection');
// Define a Document
$document = [
'First_Name' => 'Mahesh',
'Last_Name' => 'Parashar',
'Date_Of_Birth' => '1990-08-21',
'e_mail' => 'mahesh_parashar.123@gmail.com',
'phone' => '9034343345'];
// insert the document in the collection
$result = $collection->insertOne($document);
// Print result
printf("Inserted document ID: %s\n", $result->getInsertedId())
Example - Inserting a Document in a MongoDB Collection
Try the following example to insert a single document in a MongoDB collection −
index.php
<?php
require __DIR__ . '\vendor\autoload.php';
$uri = "mongodb://localhost:27017";
// connect to mongodb
$client = new MongoDB\Client($uri);
// select a collection of a database
$collection = $client->selectCollection('myDb', 'sampleCollection');
// Define a Document
$document = [
'First_Name' => 'Mahesh',
'Last_Name' => 'Parashar',
'Date_Of_Birth' => '1990-08-21',
'e_mail' => 'mahesh_parashar.123@gmail.com',
'phone' => '9034343345'
];
// insert the document in the collection
$result = $collection->insertOne($document);
// Print result
printf("Inserted document ID: %s\n", $result->getInsertedId())
?>
Output
Access the index.php deployed on apache web server and verify the output.
Inserted document ID: 696c20bffed319cd950058c4
Steps to Insert Multiple Documents in a collection
Prepare and execute a command to select a collection and insert documents using insertMany() command.
// select a collection of a database
$collection = $client->selectCollection('myDb', 'sampleCollection');
// Define Documents
$documents = [
[
'First_Name' => 'Mahesh',
'Last_Name' => 'Parashar',
'Date_Of_Birth' => '1990-08-21',
'e_mail' => 'mahesh_parashar.123@gmail.com',
'phone' => '9034343345'
],
[
'First_Name' => "Radhika",
'Last_Name' => 'Sharma',
'Date_Of_Birth' => '1995-09-26',
'e_mail' => 'radhika_sharma.123@gmail.com',
'phone' => '9000012345'
],
[
'First_Name' => "Rachel",
'Last_Name' => 'Christopher',
'Date_Of_Birth' => '1990-02-16',
'e_mail' => 'rachel_christopher.123@gmail.com',
'phone' => '9000054321'
],
[
'First_Name' => "Fathima",
'Last_Name' => 'Sheik',
'Date_Of_Birth' => '1990-02-16',
'e_mail' => 'fathima_sheik.123@gmail.com',
'phone' => '9000012345'
]
];
// insert the documents in the collection
$result = $collection->insertMany($documents);
// Print result
printf("Inserted %d document(s).\n", $result->getInsertedCount());
Example - Inserting a Document in a MongoDB Collection
Try the following example to insert a single document in a MongoDB collection −
index.php
<?php
require __DIR__ . '\vendor\autoload.php';
$uri = "mongodb://localhost:27017";
// connect to mongodb
$client = new MongoDB\Client($uri);
// select a collection of a database
$collection = $client->selectCollection('myDb', 'sampleCollection');
// Define Documents
$documents = [
[
'First_Name' => 'Mahesh',
'Last_Name' => 'Parashar',
'Date_Of_Birth' => '1990-08-21',
'e_mail' => 'mahesh_parashar.123@gmail.com',
'phone' => '9034343345'
],
[
'First_Name' => "Radhika",
'Last_Name' => 'Sharma',
'Date_Of_Birth' => '1995-09-26',
'e_mail' => 'radhika_sharma.123@gmail.com',
'phone' => '9000012345'
],
[
'First_Name' => "Rachel",
'Last_Name' => 'Christopher',
'Date_Of_Birth' => '1990-02-16',
'e_mail' => 'rachel_christopher.123@gmail.com',
'phone' => '9000054321'
],
[
'First_Name' => "Fathima",
'Last_Name' => 'Sheik',
'Date_Of_Birth' => '1990-02-16',
'e_mail' => 'fathima_sheik.123@gmail.com',
'phone' => '9000012345'
]
];
// insert the documents in the collection
$result = $collection->insertMany($documents);
// Print result
printf("Inserted %d document(s).\n", $result->getInsertedCount());
?>
Output
Access the index.php deployed on apache web server and verify the output.
Inserted 4 document(s).
PHP & MongoDB - Selecting Documents
Steps to Select a Document in a collection
First step to do any operation is to create a MongoDB Client instance.
$uri = "mongodb://localhost:27017"; // connect to mongodb $client = new MongoDB\Client($uri);
Second step is to prepare and execute a filter to select a document and select document using findOne() command.
// select a collection of a database
$collection = $client->selectCollection('myDb', 'sampleCollection');
// Define a Filter
$filter = ['e_mail' => 'mahesh_parashar.123@gmail.com'];
// execute the query
$document = $collection->findOne($filter);
// Print result
if ($document) {
echo "Found document for Mahesh Parashar:"."<br/>";
echo "<pre>";
echo json_encode($document, JSON_PRETTY_PRINT);
echo "</pre>"
} else {
echo "No document found for Mahesh Parashar."."<br/>";
}
Example - Selecting a Document from a MongoDB Collection
Try the following example to select a single document from a MongoDB collection −
index.php
<?php
require __DIR__ . '\vendor\autoload.php';
$uri = "mongodb://localhost:27017";
// connect to mongodb
$client = new MongoDB\Client($uri);
// select a collection of a database
$collection = $client->selectCollection('myDb', 'sampleCollection');
// Define a Filter
$filter = ['e_mail' => 'mahesh_parashar.123@gmail.com'];
// execute the query
$document = $collection->findOne($filter);
// Print result
if ($document) {
echo "Found document for Mahesh Parashar:"."<br/>";
echo "<pre>";
echo json_encode($document, JSON_PRETTY_PRINT);
echo "</pre>";
} else {
echo "No document found for Mahesh Parashar."."<br/>";
}
?>
Output
Access the index.php deployed on apache web server and verify the output.
Found document for Mahesh Parashar:
{
"_id": {
"$oid": "696c20bffed319cd950058c4"
},
"First_Name": "Mahesh",
"Last_Name": "Parashar",
"Date_Of_Birth": "1990-08-21",
"e_mail": "mahesh_parashar.123@gmail.com",
"phone": "9034343345"
}
Steps to Select Multiple Documents from a collection
Prepare and execute a command to select a collection and select documents using find() command.
// Define the minimum length
$minLength = 6;
// Define the query filter for size of first name
$filter = [
'First_Name' => ['$exists' => true],
'$expr' => [
'$gt' => [
['$strLenCP' => '$First_Name'], $minLength
]
]
];
// execute the query
$cursor = $collection->find($filter);
// Iterate over the cursor to access each document
foreach ($cursor as $document) {
echo "<pre>";
echo json_encode($document, JSON_PRETTY_PRINT);
echo "</pre>";
}
Example - Selecting Multiple Documents from a MongoDB Collection
Try the following example to select multiple documents from a MongoDB collection −
index.php
<?php
require __DIR__ . '\vendor\autoload.php';
$uri = "mongodb://localhost:27017";
// connect to mongodb
$client = new MongoDB\Client($uri);
// select a collection of a database
$collection = $client->selectCollection('myDb', 'sampleCollection');
// Define the minimum length
$minLength = 6;
// Define the query filter for size of first name
$filter = [
'First_Name' => ['$exists' => true],
'$expr' => [
'$gt' => [
['$strLenCP' => '$First_Name'], $minLength
]
]
];
// execute the query
$cursor = $collection->find($filter);
foreach ($cursor as $document) {
echo "<pre>";
echo json_encode($document, JSON_PRETTY_PRINT);
echo "</pre>";
}
?>
Output
Access the index.php deployed on apache web server and verify the output.
{
"_id": {
"$oid": "696c230afed319cd950058c6"
},
"First_Name": "Radhika",
"Last_Name": "Sharma",
"Date_Of_Birth": "1995-09-26",
"e_mail": "radhika_sharma.123@gmail.com",
"phone": "9000012345"
}
{
"_id": {
"$oid": "696c230afed319cd950058c8"
},
"First_Name": "Fathima",
"Last_Name": "Sheik",
"Date_Of_Birth": "1990-02-16",
"e_mail": "fathima_sheik.123@gmail.com",
"phone": "9000012345"
}
Steps to Select All Documents from a collection
Prepare and execute a command to select a collection and select all documents using find() command.
// execute the query
$cursor = $collection->find();
foreach ($cursor as $document) {
echo "<pre>";
echo json_encode($document, JSON_PRETTY_PRINT);
echo "</pre>";
}
Example - Selecting All Documents from a MongoDB Collection
Try the following example to select all documents from a MongoDB collection −
index.php
<?php
require __DIR__ . '\vendor\autoload.php';
$uri = "mongodb://localhost:27017";
// connect to mongodb
$client = new MongoDB\Client($uri);
// select a collection of a database
$collection = $client->selectCollection('myDb', 'sampleCollection');
// execute the query
$cursor = $collection->find();
// Iterate over the cursor to access each document
foreach ($cursor as $document) {
echo "<pre>";
echo json_encode($document, JSON_PRETTY_PRINT);
echo "</pre>";
}
?>
Output
Access the index.php deployed on apache web server and verify the output.
{
"_id": {
"$oid": "696c20bffed319cd950058c4"
},
"First_Name": "Mahesh",
"Last_Name": "Parashar",
"Date_Of_Birth": "1990-08-21",
"e_mail": "mahesh_parashar.123@gmail.com",
"phone": "9034343345"
}
{
"_id": {
"$oid": "696c230afed319cd950058c5"
},
"First_Name": "Mahesh",
"Last_Name": "Parashar",
"Date_Of_Birth": "1990-08-21",
"e_mail": "mahesh_parashar.123@gmail.com",
"phone": "9034343345"
}
{
"_id": {
"$oid": "696c230afed319cd950058c6"
},
"First_Name": "Radhika",
"Last_Name": "Sharma",
"Date_Of_Birth": "1995-09-26",
"e_mail": "radhika_sharma.123@gmail.com",
"phone": "9000012345"
}
{
"_id": {
"$oid": "696c230afed319cd950058c7"
},
"First_Name": "Rachel",
"Last_Name": "Christopher",
"Date_Of_Birth": "1990-02-16",
"e_mail": "rachel_christopher.123@gmail.com",
"phone": "9000054321"
}
{
"_id": {
"$oid": "696c230afed319cd950058c8"
},
"First_Name": "Fathima",
"Last_Name": "Sheik",
"Date_Of_Birth": "1990-02-16",
"e_mail": "fathima_sheik.123@gmail.com",
"phone": "9000012345"
}
PHP & MongoDB - Updating Documents
Steps to Update a Document in a collection
First step to do any operation is to create a MongoDB Client instance.
$uri = "mongodb://localhost:27017"; // connect to mongodb $client = new MongoDB\Client($uri);
Second step is to prepare and execute a filter to select a document and update document using updateOne() command.
// select a collection of a database
$collection = $client->selectCollection('myDb', 'sampleCollection');
// Define a Filter
$filter = ['e_mail' => 'mahesh_parashar.123@gmail.com'];
$update = ['$set' => ['e_mail' => 'mahesh_parashar@gmail.com']];
$options = [];
// update the document
$updatedResult = $collection->updateOne($filter, $update, $options);
Example - Updating a Document of a MongoDB Collection
Try the following example to update a single document of a MongoDB collection −
index.php
<?php
require __DIR__ . '\vendor\autoload.php';
$uri = "mongodb://localhost:27017";
// connect to mongodb
$client = new MongoDB\Client($uri);
// select a collection of a database
$collection = $client->selectCollection('myDb', 'sampleCollection');
// Define a Filter
$filter = ['e_mail' => 'mahesh_parashar.123@gmail.com'];
$update = ['$set' => ['e_mail' => 'mahesh_parashar@gmail.com']];
$options = [];
// update the document
$updatedResult = $collection->updateOne($filter, $update, $options);
printf("Matched %d document.<br/>", $updatedResult->getMatchedCount());
printf("Modified %d document.", $updatedResult->getModifiedCount());
?>
Output
Access the index.php deployed on apache web server and verify the output.
Matched 1 document. Modified 1 document.
Steps to Update Multiple Documents from a collection
Prepare and execute a command to update a collection and update documents using updateMany() command.
// select a collection of a database
$collection = $client->selectCollection('myDb', 'sampleCollection');
// Define a Filter
$filter = ['phone' => '9000012345'];
$update = ['$set' => [phone => '90000123451']];
$options = [];
// update the documents
$updatedResult = $collection->updateMany($filter, $update, $options);
Example - Updating Multiple Documents of a MongoDB Collection
Try the following example to update multiple documents of a MongoDB collection −
index.php
<?php
require __DIR__ . '\vendor\autoload.php';
$uri = "mongodb://localhost:27017";
// connect to mongodb
$client = new MongoDB\Client($uri);
// select a collection of a database
$collection = $client->selectCollection('myDb', 'sampleCollection');
// Define a Filter
$filter = ['phone' => '9000012345'];
$update = ['$set' => [phone => '90000123451']];
$options = [];
// update the document
$updatedResult = $collection->updateMany($filter, $update, $options);
printf("Matched %d document(s).<br/>", $updatedResult->getMatchedCount());
printf("Modified %d document(s).", $updatedResult->getModifiedCount())
?>
Output
Access the index.php deployed on apache web server and verify the output.
Matched 2 document(s). Modified 2 document(s).
PHP & MongoDB - Deleting Documents
Steps to Delete a Document in a collection
First step to do any operation is to create a MongoDB Client instance.
$uri = "mongodb://localhost:27017"; // connect to mongodb $client = new MongoDB\Client($uri);
Second step is to prepare and execute a filter to select a document and delete document using deleteOne() command.
// select a collection of a database
$collection = $client->selectCollection('myDb', 'sampleCollection');
// Define a Filter
$filter = ['e_mail' => 'mahesh_parashar@gmail.com'];
// delete the document
$deletedResult = $collection->deleteOne($filter);
Example - Deleting a Document of a MongoDB Collection
Try the following example to delete a single document of a MongoDB collection −
index.php
<?php
require __DIR__ . '\vendor\autoload.php';
$uri = "mongodb://localhost:27017";
// connect to mongodb
$client = new MongoDB\Client($uri);
// select a collection of a database
$collection = $client->selectCollection('myDb', 'sampleCollection');
// Define a Filter
$filter = ['e_mail' => 'mahesh_parashar@gmail.com'];
// delete the document
$deletedResult = $collection->deleteOne($filter);
printf("Deleted %d document.", $deletedResult->getDeletedCount());
?>
Output
Access the index.php deployed on apache web server and verify the output.
Deleted 1 document.
Steps to Delete Multiple Documents from a collection
Prepare and execute a command to delete documents using deleteMany() command.
// select a collection of a database
$collection = $client->selectCollection('myDb', 'sampleCollection');
// Define a Filter
$filter = ['phone' => '90000123451'];
// delete the documents
$deletedResult = $collection->deleteMany($filter);
Example - Deleting Multiple Documents of a MongoDB Collection
Try the following example to delete multiple documents of a MongoDB collection −
index.php
<?php
require __DIR__ . '\vendor\autoload.php';
$uri = "mongodb://localhost:27017";
// connect to mongodb
$client = new MongoDB\Client($uri);
// select a collection of a database
$collection = $client->selectCollection('myDb', 'sampleCollection');
// Define a Filter
$filter = ['phone' => '90000123451'];
// delete the documents
$deletedResult = $collection->deleteMany($filter);
printf("Deleted %d document(s).", $deletedResult->getDeletedCount());
?>
Output
Access the index.php deployed on apache web server and verify the output.
Deleted 2 document(s).
Steps to Delete All Documents from a collection
Prepare and execute a command to delete all documents using deleteMany() command.
// select a collection of a database
$collection = $client->selectCollection('myDb', 'sampleCollection');
// Define an empty Filter to match all documents
$filter = [];
// delete all the documents
$deletedResult = $collection->deleteMany($filter);
Example - Deleting All Documents of a MongoDB Collection
Try the following example to delete all documents of a MongoDB collection −
index.php
<?php
require __DIR__ . '\vendor\autoload.php';
$uri = "mongodb://localhost:27017";
// connect to mongodb
$client = new MongoDB\Client($uri);
// select a collection of a database
$collection = $client->selectCollection('myDb', 'sampleCollection');
// Define a Filter
$filter = [];
// delete all the documents
$deletedResult = $collection->deleteMany($filter);
printf("Deleted %d document(s).", $deletedResult->getDeletedCount());
?>
Output
Access the index.php deployed on apache web server and verify the output.
Deleted 2 document(s).
PHP & MongoDB - Embedded Documents
Steps to Insert a Document with Embedded Document in a collection
First step to do any operation is to create a MongoDB Client instance.
$uri = "mongodb://localhost:27017"; // connect to mongodb $client = new MongoDB\Client($uri);
Second step is to prepare and execute a command to select a collection and insert document with embedded document using insertOne() command.
// select a collection of a database
$collection = $client->selectCollection('myDb', 'sampleCollection');
// Define a Document
$document = [
'title' => "MongoDB Overview",
'description' => 'MongoDB is no SQL database',
'by' => 'tutorials point',
'url' => 'http://www.tutorialspoint.com',
'comments' => [
['user' => "user1", 'message' => "My First Comment", 'dateCreated' => "20/2/2020", 'like' => 0],
['user' => "user2", 'message' => "My Second Comment", 'dateCreated' => "20/2/2020", 'like' => 0],
]];
// insert the document in the collection
$result = $collection->insertOne($document);
// Print result
printf("Inserted document ID: %s\n", $result->getInsertedId())
Example - Inserting a Document With Embedded Document in a MongoDB Collection
Try the following example to insert a document with embedded document in a MongoDB collection −
index.php
<?php
require __DIR__ . '\vendor\autoload.php';
$uri = "mongodb://localhost:27017";
// connect to mongodb
$client = new MongoDB\Client($uri);
// select a collection of a database
$collection = $client->selectCollection('myDb', 'sampleCollection');
// Define a Document
$document = [
'title' => "MongoDB Overview",
'description' => 'MongoDB is no SQL database',
'by' => 'tutorials point',
'url' => 'http://www.tutorialspoint.com',
'comments' => [
['user' => "user1", 'message' => "My First Comment", 'dateCreated' => "20/2/2020", 'like' => 0],
['user' => "user2", 'message' => "My Second Comment", 'dateCreated' => "20/2/2020", 'like' => 0],
]];
// insert the document in the collection
$result = $collection->insertOne($document);
// Print result
printf("Inserted document ID: %s\n", $result->getInsertedId())
?>
Output
Access the index.php deployed on apache web server and verify the output.
Inserted document ID: 696ce141fed319cd950058cf
PHP & MongoDB - Error Handling
Syntax
MongoDB driver operations throws exceptions in case of any database operations and can be captured easily using following syntax:
try {
} catch (MongoDB\Driver\Exception\Exception $e) {
echo "Exception:", $e->getMessage(), "<br/>";
echo "File:", $e->getFile(), "<br/>";
echo "Line:", $e->getLine(), "<br/>";
}
Example - Handling Database Error
Try the following example to check Database error while trying to connect to a MongoDB database using invalid port −
index.php
<?php
require __DIR__ . '\vendor\autoload.php';
$uri = "mongodb://localhost:27020";
try {
// connect to mongodb
$client = new MongoDB\Client($uri);
// select a database
$db = $client->myDb;
// execute a command
$cursor=$db->command(array('create' => 'sampleCollection'));
echo "Collection created.";
} catch (MongoDB\Driver\Exception\Exception $e) {
echo "Exception:", $e->getMessage(), "<br/>";
echo "File:", $e->getFile(), "<br/>";
echo "Line:", $e->getLine(), "<br/>";
}
?>
Output
Access the index.php deployed on apache web server and verify the output.
Exception:No suitable servers found (`serverSelectionTryOnce` set): [connection refused calling hello on 'localhost:27020']. Topology type: Single File:D:\Apache\Apache24\htdocs\php\vendor\mongodb\mongodb\src\functions.php Line:600
PHP & MongoDB - Limit Records
Steps to Limit Documents Selection in a collection
First step to do any operation is to create a MongoDB Client instance.
$uri = "mongodb://localhost:27017"; // connect to mongodb $client = new MongoDB\Client($uri);
Second step is to prepare and execute a filter to select a document and select document using find() command while passing an option to limit records to 2.
// select a collection of a database
$collection = $client->selectCollection('myDb', 'sampleCollection');
// Define a Filter to select all records
$filter = [];
// Define a option to limit Records
$options = ['limit' => 2];
// execute the query
$cursor = $collection->find($filter, $options);
// Iterate over the cursor to access each document
foreach ($cursor as $document) {
echo "<pre>";
echo json_encode($document, JSON_PRETTY_PRINT);
echo "</pre>";
}
Example - Limiting Documents Selection from a MongoDB Collection
Try the following example to limit documents from a MongoDB collection −
index.php
<?php
require __DIR__ . '\vendor\autoload.php';
$uri = "mongodb://localhost:27017";
// connect to mongodb
$client = new MongoDB\Client($uri);
// select a collection of a database
$collection = $client->selectCollection('myDb', 'sampleCollection');
// Define a Filter to select all records
$filter = [];
// Define a option to limit Records
$options = ['limit' => 2];
// execute the query
$cursor = $collection->find($filter, $options);
// Iterate over the cursor to access each document
foreach ($cursor as $document) {
echo "<pre>";
echo json_encode($document, JSON_PRETTY_PRINT);
echo "</pre>";
}
?>
Output
Access the index.php deployed on apache web server and verify the output.
{
"_id": {
"$oid": "696cf16bfed319cd950058d4"
},
"First_Name": "Mahesh",
"Last_Name": "Parashar",
"Date_Of_Birth": "1990-08-21",
"e_mail": "mahesh_parashar.123@gmail.com",
"phone": "9034343345"
}
{
"_id": {
"$oid": "696cf16bfed319cd950058d5"
},
"First_Name": "Radhika",
"Last_Name": "Sharma",
"Date_Of_Birth": "1995-09-26",
"e_mail": "radhika_sharma.123@gmail.com",
"phone": "9000012345"
}
PHP & MongoDB - Sorting Records
Steps to Sort Documents in a collection
First step to do any operation is to create a MongoDB Client instance.
$uri = "mongodb://localhost:27017"; // connect to mongodb $client = new MongoDB\Client($uri);
Second step is to prepare and execute a filter to sort documents and select document using find() command while passing an option to sort records in descending order by name.
// select a collection of a database
$collection = $client->selectCollection('myDb', 'sampleCollection');
// Define a Filter to select all records
$filter = [];
// Define a option to sort Records
$options = ['sort' => ['First_Name' => -1]];
// execute the query
$cursor = $collection->find($filter, $options);
// Iterate over the cursor to access each document
foreach ($cursor as $document) {
echo "<pre>";
echo json_encode($document, JSON_PRETTY_PRINT);
echo "</pre>";
}
Example - Sorting Documents of a MongoDB Collection in Descending Order
Try the following example to sort documents of a MongoDB collection in descending order−
index.php
<?php
require __DIR__ . '\vendor\autoload.php';
$uri = "mongodb://localhost:27017";
// connect to mongodb
$client = new MongoDB\Client($uri);
// select a collection of a database
$collection = $client->selectCollection('myDb', 'sampleCollection');
// Define a Filter to select all records
$filter = [];
// Define a option to sort Records
$options = ['sort' => ['First_Name' => -1]];
// execute the query
$cursor = $collection->find($filter, $options);
// Iterate over the cursor to access each document
foreach ($cursor as $document) {
echo "<pre>";
echo json_encode($document, JSON_PRETTY_PRINT);
echo "</pre>";
}
?>
Output
Access the index.php deployed on apache web server and verify the output.
{
"_id": {
"$oid": "696cf16bfed319cd950058d5"
},
"First_Name": "Radhika",
"Last_Name": "Sharma",
"Date_Of_Birth": "1995-09-26",
"e_mail": "radhika_sharma.123@gmail.com",
"phone": "9000012345"
}
{
"_id": {
"$oid": "696cf16bfed319cd950058d6"
},
"First_Name": "Rachel",
"Last_Name": "Christopher",
"Date_Of_Birth": "1990-02-16",
"e_mail": "rachel_christopher.123@gmail.com",
"phone": "9000054321"
}
{
"_id": {
"$oid": "696cf16bfed319cd950058d4"
},
"First_Name": "Mahesh",
"Last_Name": "Parashar",
"Date_Of_Birth": "1990-08-21",
"e_mail": "mahesh_parashar.123@gmail.com",
"phone": "9034343345"
}
{
"_id": {
"$oid": "696cf16bfed319cd950058d7"
},
"First_Name": "Fathima",
"Last_Name": "Sheik",
"Date_Of_Birth": "1990-02-16",
"e_mail": "fathima_sheik.123@gmail.com",
"phone": "9000012345"
}
Example - Sorting Documents of a MongoDB Collection in Ascending Order
Try the following example to sort documents of a MongoDB collection in ascending order −
index.php
<?php
require __DIR__ . '\vendor\autoload.php';
$uri = "mongodb://localhost:27017";
// connect to mongodb
$client = new MongoDB\Client($uri);
// select a collection of a database
$collection = $client->selectCollection('myDb', 'sampleCollection');
// Define a Filter to select all records
$filter = [];
// Define a option to sort Records
$options = ['sort' => ['First_Name' => 1]];
// execute the query
$cursor = $collection->find($filter, $options);
// Iterate over the cursor to access each document
foreach ($cursor as $document) {
echo "<pre>";
echo json_encode($document, JSON_PRETTY_PRINT);
echo "</pre>";
}
?>
Output
Access the index.php deployed on apache web server and verify the output.
{
"_id": {
"$oid": "696cf16bfed319cd950058d7"
},
"First_Name": "Fathima",
"Last_Name": "Sheik",
"Date_Of_Birth": "1990-02-16",
"e_mail": "fathima_sheik.123@gmail.com",
"phone": "9000012345"
}
{
"_id": {
"$oid": "696cf16bfed319cd950058d4"
},
"First_Name": "Mahesh",
"Last_Name": "Parashar",
"Date_Of_Birth": "1990-08-21",
"e_mail": "mahesh_parashar.123@gmail.com",
"phone": "9034343345"
}
{
"_id": {
"$oid": "696cf16bfed319cd950058d6"
},
"First_Name": "Rachel",
"Last_Name": "Christopher",
"Date_Of_Birth": "1990-02-16",
"e_mail": "rachel_christopher.123@gmail.com",
"phone": "9000054321"
}
{
"_id": {
"$oid": "696cf16bfed319cd950058d5"
},
"First_Name": "Radhika",
"Last_Name": "Sharma",
"Date_Of_Birth": "1995-09-26",
"e_mail": "radhika_sharma.123@gmail.com",
"phone": "9000012345"
}