mongo connection using php

22:46
if we want to establish connection between mongo and php then we need to install php mongo driver in your server. after download and install in your server. please follow steps to establish the connection between php and mongo. create config.php file in your application.
<?php 
$dbhost = 'localhost';
$m = new Mongo("mongodb://$dbhost:27017");  
$db = $manager->selectDB("mydba");  
?>

Insert Documents

whenever doing mongo related operations please include above config.php file in your files.
<?php
//connection db
include("config.php");
$my_collection = $db->test;

//insert document
$doc = array(
  'name'=>'Rahul',
  'age'=>'25',
  'state'=>'TN',
  'country'=>'USA'
 );

$my_collection->insert($doc);

Find All Documents

<?php 
$users = $my_collection->find();

echo 'Find All Documents';

echo '<pre>';

foreach($users as $user)
{
 print_r($user);
}

echo '</pre>';
?>


Update Documents

<?php 
echo 'Update Documents';
$my_collection->update(array('name'=>'Rahul'),array('$set'=>array('name'=>'Rahul Sharma')));

$users = $my_collection->find(array('name'=>'Rahul Sharma'));

echo '<pre>';

foreach($users as $user)
{
 print_r($user);
}

echo '</pre>';
?>
Output:
Array
(
    [_id] => MongoId Object
        (
            [$id] => 5b20f42d6f8cd7e82700002b
        )

    [user_id] => 3
    [name] => Rahul Sharma
    [age] => 25
    [state] => TN
    [country] => USA
)

No comments:

Powered by Blogger.