How to use MongoDB with PHP

Last updated on May 30 2022
Satyen Sahu

Table of Contents

How to use MongoDB with PHP

MongoDB – PHP

To use MongoDB with PHP, you need to use MongoDB PHP driver. Download the driver from the url Download PHP Driver. Make sure to download the latest release of it. Now unzip the archive and put php_mongo.dll in your PHP extension directory (“ext” by default) and add the subsequent line to your php.ini file −
extension = php_mongo.dll

Make a Connection and Select a Database

To make a connection, you need to specify the database name, if the database doesn’t exist then MongoDB creates it automatically.
Subsequent is that the code snippet to connect to the database −
<?php
// connect to mongodb
$m = new MongoClient();

echo “Connection to database successfully”;
// select a database
$db = $m->mydb;

echo “Database mydb selected”;
?>
When the program is executed, it will produce the subsequent result −
Connection to database successfully
Database mydb selected

Create a Collection

Subsequent is that the code snippet to create a collection −
<?php
// connect to mongodb
$m = new MongoClient();
echo “Connection to database successfully”;

// select a database
$db = $m->mydb;
echo “Database mydb selected”;
$collection = $db->createCollection(“mycol”);
echo “Collection created succsessfully”;
?>
When the program is executed, it will produce the subsequent result −
Connection to database successfully
Database mydb selected
Collection created succsessfully

Insert a Document

To insert a document into MongoDB, insert() method is employed.
Subsequent is that the code snippet to insert a document −
<?php
// connect to mongodb
$m = new MongoClient();
echo “Connection to database successfully”;

// select a database
$db = $m->mydb;
echo “Database mydb selected”;
$collection = $db->mycol;
echo “Collection selected succsessfully”;

$document = array(
“title” => “MongoDB”,
“description” => “database”,
“likes” => 100,
“url” => “http://www.tecklearn.com/mongodb/”,
“by” => “tecklearn”
);

$collection->insert($document);
echo “Document inserted successfully”;
?>
When the program is executed, it will produce the subsequent result −
Connection to database successfully
Database mydb selected
Collection selected succsessfully
Document inserted successfully

Find All Documents

To select all documents from the collection, find() method is employed.
Subsequent is that the code snippet to select all documents −
<?php
// connect to mongodb
$m = new MongoClient();
echo “Connection to database successfully”;

// select a database
$db = $m->mydb;
echo “Database mydb selected”;
$collection = $db->mycol;
echo “Collection selected succsessfully”;

$cursor = $collection->find();
// iterate cursor to display title of documents

foreach ($cursor as $document) {
echo $document[“title”] . “\n”;
}
?>
When the program is executed, it will produce the subsequent result −
Connection to database successfully
Database mydb selected
Collection selected succsessfully {
“title”: “MongoDB”
}

Update a Document

To update a document, you need to use the update() method.
In the subsequent example, we will update the title of inserted document to MongoDB Tutorial. Subsequent is that the code snippet to update a document −
<?php
// connect to mongodb
$m = new MongoClient();
echo “Connection to database successfully”;

// select a database
$db = $m->mydb;
echo “Database mydb selected”;
$collection = $db->mycol;
echo “Collection selected succsessfully”;

// now update the document
$collection->update(array(“title”=>”MongoDB”),
array(‘$set’=>array(“title”=>”MongoDB Tutorial”)));
echo “Document updated successfully”;

// now display the updated document
$cursor = $collection->find();

// iterate cursor to display title of documents
echo “Updated document”;

foreach ($cursor as $document) {
echo $document[“title”] . “\n”;
}
?>
When the program is executed, it will produce the subsequent result −
Connection to database successfully
Database mydb selected
Collection selected succsessfully
Document updated successfully
Updated document {
“title”: “MongoDB Tutorial”
}

Delete a Document

To delete a document, you need to use remove() method.
In the subsequent example, we will remove the documents that has the title MongoDB Tutorial. Subsequent is that the code snippet to delete a document −
<?php
// connect to mongodb
$m = new MongoClient();
echo “Connection to database successfully”;

// select a database
$db = $m->mydb;
echo “Database mydb selected”;
$collection = $db->mycol;
echo “Collection selected succsessfully”;

// now remove the document
$collection->remove(array(“title”=>”MongoDB Tutorial”),false);
echo “Documents deleted successfully”;

// now display the available documents
$cursor = $collection->find();

// iterate cursor to display title of documents
echo “Updated document”;

foreach ($cursor as $document) {
echo $document[“title”] . “\n”;
}
?>
When the program is executed, it will produce the subsequent result −
Connection to database successfully
Database mydb selected
Collection selected succsessfully
Documents deleted successfully
In the above example, the second parameter is boolean type and employed for justOne field of remove() method.
Remaining MongoDB methods findOne(), save(), limit(), skip(), sort() etc. works same as explained above.
So, this brings us to the end of blog. This Tecklearn ‘How to use MongoDB with PHP’ helps you with commonly asked questions if you are looking out for a job in MongoDB and No-SQL Database Domain.
If you wish to learn and build a career in MongoDB or No-SQL Database domain, then check out our interactive, MongoDB Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

MongoDB Training

MongoDB Training

About the Course

Tecklearn’s MongoDB Training helps you to master the NoSQL database. The course makes you job-ready by letting you comprehend schema design, data modelling, replication, and query with MongoDB through real-time examples. Along with this, you’ll also gain hands-on expertise in installing, configuring, and maintaining the MongoDB environment, including monitoring and operational strategies from this online MongoDB training. Upon completion of this online training, you will hold a solid understanding and hands-on experience with MongoDB.

Why Should you take MongoDB Training?

• MongoDB – a $36 billion to a $40 billion market growing at 8% to 9% annually – Forbes.com
• Average salary of a Mongo DB certified professional is $134k – Indeed.com
• MongoDB has more than 900 customers, including 27 Fortune 100 companies like Cisco, eBay, eHarmony, MetLife & Salesforce.com

What you will Learn in this Course?

Introduction to MongoDB and Importance of NoSQL
• Understanding the basic concepts of RDBMS
• What is NoSQL Database and its significance?
• Challenges of RDBMS and How NoSQL suits Big Data needs
• Types of NoSQL Database and NoSQL vs. SQL Comparison
• CAP Theorem and Implementing NoSQL
• Introduction to MongoDB and its advantages
• Design Goals for MongoDB Server and Database, MongoDB tools
• Collection, Documents and Key Value Pair
• Introduction to JSON and BSON documents
• MongoDB installation
MongoDB Installation
• MongoDB Installation
• Basic MongoDB commands and operations,
• Mongo Chef (MongoGUI) Installation
Schema Design and Data Modelling
• Why Data Modelling?
• Data Modelling Approach
• Data Modelling Concepts
• Difference between MongoDB and RDBMS modelling
• Challenges for Data Modelling
• Model Relationships between Documents
• Data Model Examples and Patterns
• Model Tree Structures
CRUD Operations
• MongoDB Architecture
• CRUD Introduction and MongoDB CRUD Concepts
• MongoDB CRUD Concerns (Read and Write Operations)
• Cursor Query Optimizations and Query Behaviour in MongoDB
• Distributed Read and Write Queries
• MongoDB Datatypes
Indexing and Aggregation Framework
• Concepts of Data aggregation and types and data indexing concepts
• Introduction to Aggregation
• Approach to Aggregation
• Types of Aggregation: Pipeline, MapReduce and Single Purpose
• Performance Tuning
MongoDB Administration
• Administration concepts in MongoDB
• MongoDB Administration activities: Health check, recovery, backup, database sharing and profiling, performance tuning etc.
• Backup and Recovery Methods for MongoDB
• Export and Import of Data from MongoDB
• Run time configuration of MongoDB
MongoDB Security
• Security Introduction
• MongoDB security Concepts and security approach
• MongoDB integration with Java and Robomongo
Got a question for us? Please mention it in the comments section and we will get back to you.

0 responses on "How to use MongoDB with PHP"

Leave a Message

Your email address will not be published. Required fields are marked *