Main Page
 The gatekeeper of reality is
 quantified imagination.

Stay notified when site changes by adding your email address:

Your Email:

Bookmark and Share
Email Notification
Project MongoDB
Purpose
The purpose of this tutorial is to show how to use a variety of MongoDB commands in PHP. This tutorial focuses on communicating with a MongoDB installation hosted with MongoLabs.

Basic Connection
The following code block is the basic connection information for connecting to a Mongo Database.

/* MongoDB Connection Information */
$mongoDB_url = "ds.mongolab.com:000001"; /* Unique URL assigned by MongoLab */
$mongoDB_username = "dbusername"; /* User defined in "Users" for the MongoDB Name */
$mongoDB_pass = "dbpassword"; /* Password for the defined user */
$mongoDB_db = "database-collection"; /* MongoDB Name where collections (aka "tables") reside */
$mongoDB_dbcollection_requests = "specific-table"; /* Name of specific collection (aka specific "table") */

/* Define MongoDB Connection Parameters */
$mongoDB_error = "";
$mongoDB_fullURL = "mongodb://" . $mongoDB_username . ":" . $mongoDB_pass . "@" . $mongoDB_url . "/" . $mongoDB_db;
try {
$mongoDB_connection = new Mongo($mongoDB_fullURL);
$mongoDB_database = $mongoDB_connection->selectDB($mongoDB_db);
$mongoDB_collection = $mongoDB_database->selectCollection($mongoDB_dbcollection_requests);
}
catch(MongoConnectionException $e) {
$mongoDB_error = "Failed to connect to database " . $e->getMessage();
}

/* Output */
print "<html>\n";
print "<body>\n";
/* Continue if we've got a connection */
if (strlen($mongoDB_error) == 0) {
$mongoDB_results = Array();

/* COMMANDS WOULD BE PLACED HERE */

/* Handle Response */
if (sizeof($mongoDB_results) > 0) {
/* Iterate through returned documents (aka "rows") */
while ($mongoDB_results->hasNext()) {
/* There is at least one document (aka "row") in the returned data */
$doc_content = $mongoDB_results->getNext();

/* The following are examples of special handling for data types. You will want to keep these commented out. */
/* A boolean value in MongoDB may not appear in results with a value of "true" or "false". Instead, if a boolean is set to true, it will be returned as 1; otherwise it may be 0 or a blank value. */
if (isset($doc_content["failed"])) {
$tmp_failed = $doc_content["failed"];
}
/* A timestamp in MongoDB as ISODate("2014-11-09T19:39:16.55Z") will appear in results as "0.55000000 1415561956". To convert to human-readable can use PHP's date function */
if (isset($doc_content["timestamp"])) {
$tmp_timestamp = date("Y-m-d h:i:s", $doc_content["timestamp"]->sec);
}
}
}
else {
print "ERROR: A connection was established but it seems your query did not have any results.<br />\n";
}
}
else {
print "ERROR: " . $mongoDB_error;
}
print "</body>\n";
print "</html>\n";


Example MongoDB Commands

Get the first 5 documents
$mongoDB_results = $mongoDB_collection->find()->limit(5);

Find documents that have boolean failed set to true
$mongoDB_searchdata = Array(
'failed'=>true
);
$mongoDB_results = $mongoDB_collection->find($mongoDB_searchdata)->limit(1);


Find documents that have an IP that BEGINS with the search text
$tmp_searchtxt = "1.2";
$mongoDB_searchdata = Array(
'ip'=>new MongoRegex("/^$tmp_searchtxt/i")
);
$mongoDB_results = $mongoDB_collection->find($mongoDB_searchdata)->limit(5);


Find documents that have an IP that's LIKE the search text
$tmp_searchtxt = "1.2";
$mongoDB_searchdata = Array(
'ip'=>new MongoRegex("/$tmp_searchtxt/i")
);
$mongoDB_results = $mongoDB_collection->find($mongoDB_searchdata)->limit(5);


Find documents that have an IP that BEGINS with the search text 1 AND has page set to search text 2
$tmp_searchtxt1 = "1.2";
$tmp_searchtxt2 = "1";
$mongoDB_searchdata = Array(
'ip'=>new MongoRegex("/^$tmp_searchtxt1/i")
,'page'=>$tmp_searchtxt2
);
$mongoDB_results = $mongoDB_collection->find($mongoDB_searchdata)->limit(5);


Find documents that have an IP that BEGINS with the search text 1 OR has page set to search text 2
$tmp_searchtxt1 = "1.2";
$tmp_searchtxt2 = 1;
$mongoDB_searchdata = Array(
'$or'=>Array(
Array('ip'=>new MongoRegex("/^$tmp_searchtxt1/i"))
,Array('page'=>$tmp_searchtxt2)
)
);
$mongoDB_results = $mongoDB_collection->find($mongoDB_searchdata)->limit(5);


Date Searching
Important Note: It is not possible to search a field in MongoDB such as you can do with Php, MySQL and 'BETWEEN'.
That is, the following (as an example) ordinarily has 5 documents in the database for between '2014-12-04 00:00:00' and '2014-12-04 04:40:45' but MongoDB query returns nothing.
Example 1:
$tmp_startdate = new MongoDate(strtotime("2014-12-04 00:00:00")); //0.00000000 1417651200
$tmp_enddate = new MongoDate(strtotime("2014-12-04 04:40:45")); //0.00000000 1417668045
$mongoDB_searchdata = Array(
'timestamp'=>Array(
'$gte'=>$tmp_startdate
,'$lte'=>$tmp_enddate
)
);
$mongoDB_results = $mongoDB_collection->find($mongoDB_searchdata)->limit(5);


In the example below, if a search is more granular such as to a day, then results are returned.
Example 2:
$tmp_startdate = new MongoDate(strtotime("2014-12-04 00:00:00")); //0.00000000 1417651200
$tmp_enddate = new MongoDate(strtotime("2014-12-05 04:40:45")); //0.00000000 1417754445
$mongoDB_searchdata = Array(
'timestamp'=>Array(
'$gte'=>$tmp_startdate
,'$lte'=>$tmp_enddate
)
);
$mongoDB_results = $mongoDB_collection->find($mongoDB_searchdata)->limit(5);


Find and sort documents for a specific user by a specific date "2014-12-11" in ascending order
$tmp_searchtxt = "handy";
$tmp_startdate = new MongoDate(strtotime("2014-12-11")); //0.00000000 1417651200
$tmp_enddate = new MongoDate(strtotime("2014-12-12")); //0.00000000 1417737600
$mongoDB_searchdata = Array(
'client'=>$tmp_searchtxt
,'timestamp'=>Array(
'$gte'=>$tmp_startdate
,'$lt'=>$tmp_enddate
)
);
// NOTE: Sorting by the "timestamp" field where 1 is ascending and -1 is descending
$mongoDB_results = $mongoDB_collection->find($mongoDB_searchdata)->limit(25)->sort(Array("timestamp" => 1));


Count the number of documents for a specific user
$tmp_searchtxt = "handy";
$mongoDB_searchdata = Array(
'client'=>$tmp_searchtxt
);
$mongoDB_results = $mongoDB_collection->count($mongoDB_searchdata);
print "Number of documents = " . $mongoDB_results . "<br />";
unset($mongoDB_results);


Find distinct IP addresses for a specific user. Normally "$mongoDB_collection->distinct('ip')" would just return distinct values for that one column.
$tmp_searchtxt = "handy";
$mongoDB_searchdata = Array(
'client'=>$tmp_searchtxt
);
$mongoDB_results = $mongoDB_collection->distinct('ip', $mongoDB_searchdata);
if (sizeof($mongoDB_results) > 0) {
foreach ($mongoDB_results AS $arrindex => $arrvalue) {
print "array index = " . $arrindex . "<br />array index value = " . $arrvalue . "<br />";
}
}
unset($mongoDB_results);


About Joe