Introduction to MongoDB

MongoDB has databases, collections, and documents. Download an example file.

Collections correlate to tables within the relational database paradigm.Like tables, indexes
are applied to collections. A collection is a collection of documents and indexes.

In MongoDB, the primary object is called a document. MongoDB document is a JSON array with a set of keys that map to values.

Installing MongoDB

Connecting to a Database
The default host is localhost, and the default port is 27017.
Connecting to MongoDB database server at localhost port 27017:
$connection = new Mongo();
Connecting to a remote host with optional custom port:
$connection = new Mongo( “” );

Selecting a Database
MongoDB will create a new database if you try to select a database that doesn’t. Open connection to MongoDB server:
$db = $connection->selectDB(‘workout’);
$db = $connection->workout;

CRUD Operations
Create a collection or access to collection:
$user_collection = $db->user;
$user_collection= $connection->workout->user;

Creating a Document
$user = array(‘group_access_id’ =>1, ‘first_name’ => ‘Ruslan’, ‘last_name’ => ‘Verbelchuk’,‘phone’ => ”, “e-mail”=>’’, “membership”=>”);

Asynchronous update does not return a value after insert a record.

Synchronously update hold execution until it has finished inserting. The application must wait for the database.
$user_collection->insert($user, array(‘safe’ => true));
To access the primary key:
$user_id = $user[‘_id’];

Save a Document
An _id value is specified and exists.

Primary Keys and ObjectIds

MongoDB will automatically create a primary key (ObjectIds) for each document.

Reading a Document
Access the document by the primary key:
$user_data=$user_collection->findone( array(‘_id’=>$user_id) );
echo ‘<br>First Name: ‘ . $user_data[‘first_name’] . ‘<br/>’;
echo ‘Last Name: ‘ . $user_data[‘last_name’] . ‘<br/>’;
echo ‘E-mail: ‘ . $user_data[‘e-mail’] . ‘<br/>’;
echo ‘<br/>’;

A second parameter that is an array of the fields to return:
$user_data=$user_collection->findone( array(‘_id’=>$user_id), array(‘phone’) );
echo “<p>”.print_r($user_data).”</p>”;

Get all documents:
echo $user_data->count() . ‘ document(s) found. <br/>’;
foreach ($user_data as $obj) {
echo ‘<br>First Name: ‘ . $obj[‘first_name’] . ‘<br/>’;
echo ‘Last Name: ‘ . $obj[‘last_name’] . ‘<br/>’;
echo ‘E-mail: ‘ . $obj[‘e-mail’] . ‘<br/>’;
echo ‘<br/>’;

Updating a Document
Using $set to update a few fields:
array(‘_id’ =>$user_id),
array(‘$set’=>array(‘e-mail’=>’’,’phone’=>’4164440505′) )

Use update to add a value:
) )
Append values atomically to an array:
) )

Deleting a Document
justOne limit the deletion to a single document.
$criteria = array(‘last_name’=> ‘Verbelchuk’);
$user_collection->remove($criteria, array(“justOne” => true) );

This entry was posted in MongoDB and tagged . Bookmark the permalink.