MongoDB PHP



MongoDB PHP

1 1


mongophp-presentation

MongoDB und PHP

On Github cmuench / mongophp-presentation

MongoDB PHP

netz98 new media GmbH

by Christian Münch

Was ist MongoDB?

  • Dokumentenorientert NoSQL Datenbank
  • Kein formales Schema
  • Keine Transaktionen (nur auf Dokumentenbene)
  • Dokumente werden in BSON (Binary JSON) abgelegt
  • humongous => gigantisch

Features

  • Index Support
  • Hochverfügbarkeit / Replikation
  • Auto-Sharding
  • GridFS
  • Map/Reduce - Aggregation Framework

BSON

http://bsonspec.org/#/specification
element	::= "\x01" e_name double	Floating point
          | "\x02" e_name string	UTF-8 string
          | "\x03" e_name document	Embedded document
          | "\x04" e_name document	Array
          | "\x05" e_name binary	Binary data
          | "\x06" e_name	Undefined — Deprecated
          | "\x07" e_name (byte*12)	ObjectId
          | "\x08" e_name "\x00"	Boolean "false"
          | "\x08" e_name "\x01"	Boolean "true"
          | "\x09" e_name int64	UTC datetime
          | "\x0A" e_name	Null value
          | "\x0B" e_name cstring cstring	Regular expression
          | "\x0C" e_name string (byte*12)	DBPointer — Deprecated
          | "\x0D" e_name string	JavaScript code
          | "\x0E" e_name string	Symbol — Deprecated
          | "\x0F" e_name code_w_s	JavaScript code w/ scope
          | "\x10" e_name int32	32-bit Integer
          | "\x11" e_name int64	Timestamp
          | "\x12" e_name int64	64-bit integer
          | "\xFF" e_name	Min key
          | "\x7F" e_name	Max key
                    

Begriffe für SQL Entwickler

  • Connection = Connection
  • Database = Database
  • Table = Collection
  • Row = Document
  • Column = Field
  • Joins = Embedded Document Linking
  • Primary Key = Primary Key
  • Foreign Key = null
  • Aggregation (Group, Sum, ...) = Aggregation Pipeline
  • Store Procedures = Embedded JavaScript Engine (V8)
  • Index = Index
  • Trigger = null

CRUD SQL

  • C - INSERT INTO
  • R - SELECT FROM
  • U - UPDATE SET
  • D - DELETE FROM

CRUD MongoDB

  • C - collection.insert()
  • R - collection.find()
  • U - collection.update()
  • D - collection.remove()

PHP Modul Installation

                        $> pecl install mongo
...
Build process completed successfully
Installing '/usr/lib/php5/20121212/mongo.so'
install ok: channel://pecl.php.net/mongo-1.4.5
configuration option "php_ini" is not set to php.ini location
You should add "extension=mongo.so" to php.ini
                    

Prüfen ob alles läuft

CLI

                        
php -m | grep mongo
                        
                    

Prüfen ob alles läuft

Webserver

Programmierer brauchen eine API

http://api.mongodb.org

http://php.net/mongo

Erster Kontakt

$client = new \MongoClient();
/* @var $client \MongoClient */

$client = new \MongoClient('mongodb://localhost:27017');

$client = new \MongoClient(
    'mongodb://localhost:27017,localhost:27018,localhost:27019'
);

Datenbank selektieren

$db = $client->selectDB('phpugrhh');
/* @var $db \MongoDB */

$db = $client->phpugrhh;

$db = $client->{'foo-bar'};

Collection selektieren

$collection = $db->selectCollection('worker');
/* @var $collection \MongoCollection */

$collection = $db->worker;

Dokumente lesen

$cursor = $collection->find()
/* @var $cursor \MongoCursor */

foreach ($cursor as $doc) {
    var_dump($doc);
}

Ausgabe:

array(3) {
    '_id' => int(2)
    'name' => string(5) "Klaus"
}

Query

Einfach

$cursor = $collection->find(
    array(
        'name' => 'Klaus'
    )
);

Komplexer

$cursor = $collection->find(
    array(
        'age => array(
            '$gt' => 20
        ),
        'name' => array(
            '$regex' => 'aus'
        )
    )
);

Ich kann nicht so lange warten

$collection->ensureIndex(
    array(
        'name' => 1
    )
);

$collection->ensureIndex(
    array(
        'name'        => 1,
        'create_date' => -1
    )
);

Pagination

$pageNum = 2;
$resultsPerPage = 10;

$cursor = $collection->find()
    ->sort(array('_id' => -1))
    ->skip($pageNum * $resultsPerPage)
    ->limit($resultsPerPage);

Feed einlesen

$client = new \MongoClient();
$db = $client->phpugrhh;

$feed = $db->feed;
$feed->remove();

$feedData = \file_get_contents('http://www.php.net/releases/feed.php');

$xml = simplexml_load_string($feedData);
foreach ($xml->entry as $entry) {
    $feed->insert($entry); // Automatic Marshalling
}

Objekte speichern

class User
{
    /* @var string */
    public $name;

    /* @var int */
    public $age;
}

$client = new \MongoClient();
$db = $client->phpugrhh;
$storage = $db->object_storage;

$user = new User();
$user->_id = 'cmuench';
$user->name = 'Christian Münch';
$user->age = rand(30, 40);

$storage->save($user);

$js = <<<'JS'
    user = db.object_storage.findOne({_id: 'cmuench'});
    user['company'] = 'netz98 new media GmbH';
    user['ts'] = new Date();
    db.object_storage.save(user);
JS;

$db->execute(new \MongoCode($js));

$user = $storage->findOne(array('_id' => 'cmuench'));
var_dump($user);

Binärdaten

$profile = array(
    "username"     => "cmuench",
    "create_date"  => new \MongoDate(),
    "profilePhoto" => new \MongoBinData(file_get_contents("my_photo.jpg"))
);

$users->save($profile);

Manchmal braucht man etwas mehr Platz

$client = new \MongoClient();
$db = $client->phpugrhh;

$grid = $db->getGridFS();
$grid->storeFile(
    'php-logo.png',
    array('metadata' => array('date' => new MongoDate()))
);

$doc = $grid->findOne(array('filename' => 'php-logo.png'));
/* @var $doc \MongoGridFSFile */
echo $doc->getResource();
echo $doc->getBytes();

Einschränkungen

  • 16MB Limit für Dokumente
  • Für Blogs gilt das gleiche Limit. -> siehe GridFS
  • Update mit Refrenz auf sich selbst funktioniert nicht
  • Maximal 64 Indizes pro Collection
  • Maximal 31 Felder in einem Index

Praxis Beispiele

  • Embedded Document References
  • Failover
  • Replikation

Tools und Quellen

Noch Fragen?

sonst geht's zum Restaurant "Zum güldenen M"