If you’re used to MySQL then making the move to MongoDB may be daunting. Here’s a simple walkthrough with examples to get you started.

Setup

Firstly, connect to your server and select the database with which you wish to work.

$m = new MongoClient("server.co.uk");
$db = $m->selectDB("database");

Access the relevant collection (equivalent to a table in MySQL). In this example I will be using “cars”. If a collection doesn’t already exist, it will be created.
$collection = $db->cars;

Insert Data

Inserting data (called a document) into a collection is pretty straight forward.
Create an array containing the data you want to add:
$insert = array('brand'=>'Ferrari', 'model'=>F40')));

Then use the “insert” command:
$collection->insert($insert);

Simple. You can also store arrays within the document:
$insert = array('brand'=>'Ferrari', 'model'=>F40', 'wheels'=>array(['number'=>4, 'size'=>18]));

If the square brackets are confusing, it’s the same as this:
$insert = array('brand'=>'Ferrari', 'model'=>F40', 'wheels'=>array(array('number'=>4, 'size'=>18)));

Update Data

$criteria = array('brand'=>'Ferrari', 'model'=>'F40');
$new_data = array('$set'=>array('wheels'=>array('size'=>17)));
$collection->update($criteria, $new_data);

The above will find any Ferrari F40 and update the wheel size to 17.
Note: the dollar ($) doesn’t denote a variable, and must be enclosed in single quotes.

You can also add “fields” to collections in the same way. For example if I wanted to add “top speed” to just the Ferrari F40:
$criteria = array('brand'=>'Ferrari', 'model'=>'F40');
$new_data = array('$set'=>array('top speed'=>201));
$collection->update($criteria, $new_data);

Select Data

If you want to find all Ferraris:
$search = array('brand'=>'Ferrari');
$cars = $collection->find($search);

If you want to find all cars with 18″ wheels:
$search = array('wheels.size'=>18);
$cars = $collection->find($search);

If you want to find all Ferraris with 18″ wheels:
$search = array('brand'=>'Ferrari', 'wheels.size'=>18);
$cars = $collection->find($search);

Add a comment