How to work with mongodb and php

Once you are ready with php properly configuration with mongodb . There after you can write php codes to take CURD with mongodb database.

PHP version 5.3+ comes great to work with mongodb.

Refer our other article to configure your php with mongodb.

How to connect to mongodb Database from php

CASE-1

1
2
3
4
5
/*
 * Connect to local server
 * Generally its your localhost system i.e 127.0.0.1
 */
$server = new Mongo();

CASE-2

/*
 * Connect to local server
 * Generally its your localhost system i.e 127.0.0.1 without ports
 */
$server = new Mongo("mongodb://127.0.0.1");

CASE-3

/*
 * Connect to local server
 * Generally its your localhost system i.e 127.0.0.1 with some port
 */
$server = new Mongo("mongodb://127.0.0.1:65432");

CASE-4

/*
 * Connect to Remote server
 */
$server = new Mongo("mongodb://way2code.com:65432");

How to select database and tables of mongoDb database using php

1
2
3
4
5
6
7
8
9
/*
 * select a database
 */
$db = $server->test;
 
/*
 *  select a collection (Generally its database's table)
 */
$collection = $db->users;

How to Save record in mongodb Database from php

1
2
3
4
5
/*
 * mongoDb Insert function always accepts array
 */
$dataToSave= array( "sitename" => "way2code", "author" => "bikash" );
$collection->insert($dataToSave);

How to Update data in mongoDb database using php

1
2
3
$dataToUpdate   = array('$set'=> array('sitename' => 'waytocode'));
$condition      = array('auther' => 'bikash');
$collection->update($condition,$dataToUpdate);

How to retrieve data from mongoDb database using php

1
2
3
4
5
6
7
8
/*
 * find function helps in retrieving data from database
 */
 $cursor = $collection->find();
 foreach ($cursor as $document) {
    echo $document["sitename"] . "<br />";
    echo $document["auther"] . "<br />";
 }

How to retrieve data from mongdb database based on condition using php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/*
 * Retrive records where auther is bikash
 */
$condition = array('auther' => 'bikash');
$cursor = $collection->find($condition);
foreach ($cursor as $document) {
    echo $document["sitename"];
}
 
/*
 * Retrive data using while loop
 */
while($cursor->hasNext()){
   echo $document["sitename"];
}

How to count number of records in mongodb database using php

1
$totalRecord = $collection->count();

How to select specific columns of mongoDb database using php

1
$cursor = $collection->find($conditionArray , $columnListArray);