Mongodb - 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 following line to your php.ini file −
extension = php_mongo.dll
<?php
// connect to mongodb
$m = new MongoClient();
Create a Collection
Following is 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";
?>
Explore our latest online courses and learn new skills at your own pace. Enroll and
become a certified expert to boost your career.
Insert a Document
To insert a document into MongoDB, insert() method is used.
<?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.tutorialspoint.com/mongodb/",
"by" => "tutorials point"
);
$collection->insert($document);
echo "Document inserted successfully";
?>
<?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
In the following example, we will update the title of inserted document to MongoDB
Tutorial. Following is 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";
In the following example, we will remove the documents that has the title MongoDB
Tutorial. Following is 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";
In the above example, the second parameter is boolean type and used for justOne field of
remove() method.
Remaining MongoDB methods findOne(), save(), limit(), skip(), sort() etc. works
same as explained above.