Mongo Phpbnl12

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 42

Welcome!

PHP and mongoDB


PHP Benelux - Edegem, Belgium - Jan 28th, 2012
Derick Rethans - derick10gen!com - t"itter#
derickr
htt$#%%&oind!in%'()*
About Me
Derick Rethans

Dutchman li+ing in ,ondon

PHP mongoDB dri+er maintainer -or 10gen .the


com$an/ 0ehind mongoDB1

2uthor o- 3de0ug

2uthor o- the mcr/$t, in$ut4-ilter, d0us, translit


and date%time extensions
What is mongoDB?

mongoDB is a document storage and retrie+al


engine

5t re6uires almost no con-iguration to set-u$ a


high a+aila0le and high $er-ormant cluster o-
data0ase ser+ers

Each document is stored into a collection, "hich is


stored into a data0ase, "hich is stored in a
data0ase ser+er!
Getting started with mongoDB
5nstallation 0/ do"nloading -rom #
wge hp://fasd1.mongodb.org/1inux/mongodb-1inux-x86_64-2.0.2.gz
ar xvzf mongodb-1inux-x86_64-2.0.2.gz
cd mongodb-1inux-x86_64-2.0.2/bin
m'dir ../../daa
./mongod --dbpah ../../daa --1ogpah /mp/mongod.1og --for'
ai1 -f /mp/mongod.1og
5nstallation through a$t-get#
$ sudo ap-'ey adv --'eyserver 'eyserver.ubunu.com --recv 7E0CEB10
$ sudo echo "deb hp://down1oads-disro.mongodb.org/repo/debian-sysvini dis 10gen" >> /ec/ap/sources.1is
# sudo ap-ge updae
$ sudo ap-ge insa11 mongodb-10gen
7"eak con-ig in %etc%mongod0!con- i- /ou must!
mongo .the shell1 is a use-ul a$$lication to tr/ out
things "ith!
The mongoDB PHP extension

8aintained and su$$orted 0/ 10gen ."ell, 9ristina


and me reall/1

:an 0e installed "ith $ecl# $ecl install mongo

2dd extension;mongo!so to $h$!ini


Terminology

J<=> Document# the data .ro"1

:ollection# contains documents .ta0le, +ie"1

5ndex

Em0edded Document .?&oin1


onnecting to mongoDB
>o ta0les or collections ha+e to do 0e ex$licitl/
created
<?php
$m = new Mongo(),
$daabase = $m->demo,
$co11ecion = $daabase->esCo11ecion,
?>
Di--erent connection strings#

@m ; ne" 8ongo.Amongod0#%%localhostA1B

@m ; ne" 8ongo.Alocalhost#2(01(A1B

@m ; ne" 8ongo.Amongod0#%%localhost#2C000A1B

@m ; ne"
8ongo.Amongod0#%%mongo!exam$le!comA1B

@m ; ne"
8ongo.Amongod0#%%md01!exam$le!com,md02!exa
m$le!comA1B
Documents

<tored as B<=> .Binar/ J<=>1

:an ha+e em0edded documents

Ha+e a uni6ue 5D .the 4id -ield1


<im$le document#
{
"_id" : Ob_ecId("4cb4ab6d7addf98506010001"),
"id" : NumberLong(1),
"desc" : "ONE"
}
Document "ith em0edded documents#
{
"_id" : "deric'r",
"name" : "eric' Rehans",
"aric1es" : [
{
"i1e" : "Rrofi1ing RHR App1icaions",
"ur1" : "hp://deric'rehans.n1/a1's/profi1ing-phpour1i11e11.pdf",
},
{
"i1e" : "Xdebug",
"ur1" : "hp://deric'rehans.n1/a1's/xdebug-phpbcn11.pdf",
}
|
}
!nserting a document
<?php
$documen = array(
"_id" => "deric'r",
"name" => "eric' Rehans",
"aric1es" => array(
array(
"i1e" => "Rrofi1ing RHR App1icaions",
"ur1" => "hp://deric'rehans.n1/a1's/profi1ing-phpour1i11e11.pdf",
),
array(
"i1e" => "Xdebug",
"ur1" => "hp://deric'rehans.n1/a1's/xdebug-phpbcn11.pdf",
)
)
),
$m = new Mongo(),
var_dump( $m->demo->aric1es->inser( $documen ) ),
?>
mongoDB su""orts many ty"es

null

0oolean

integer .0oth D2-0it and *'-0it, 8ongo5ntD2,


8ongo5nt*'1

dou0le

string .E7F-81

arra/

associati+e arra/

8ongoRegex

8ongo5d

8ongoDate

8ongo:ode

8ongoBinData
!Ds

E+er/ document needs an 5D

5Ds need to 0e uni6ue

Gou can set /our o"n, or let them 0e auto


generated
<?php
$m = new Mongo(),
$c = $m->demo->aric1es,
$d = array( 'name' => 'eric'', '_id' => 'deric'r' ),
$c->inser( $d ),
var_dump( $d ),
$d = array( 'name' => 'eric'' ),
$c->inser( $d ),
var_dump( $d ),
?>
hec#ing $or errors
<o -ar, "e ha+e not checked -or "hether inserts
"orked!
<?php
$m = new Mongo,
$c = $m->demo->aric1es,
$c->inser( array( '_id' => 'deric'r' ) ),
$c->inser( array( '_id' => 'deric'r' ) ),
?>
A<a-eA inserts#
<?php
$m = new Mongo,
$c = $m->demo->aric1es,
ry {
$c->inser(
array( '_id' => 'deric'r' ), // documen
array( 'safe' => rue ) // opions
),
} cach ( Excepion $e ) {
var_dump( $e->geMessage() ),
}
?>
hec#ing $or errors %&'
<a-eness le+els#

:on-irm change recorded in memor/# arra/. Hsa-eH


;I true 1B

:on-irm inclusion in &ournal# arra/. H&H ;I true 1B

:on-irm committed to disk# arra/. H-s/ncH ;I


true 1B
<?php
$m = new Mongo(),
$c = $m->demo->aric1es,
$c->inser(
array( '_id' => 'deric'r' ), // documen
array( '_' => rue ) // opions
),
$c->inser(
array( '_id' => 'mongodb' ), // documen
array( 'fsync' => rue ) // opions
),
?>
(uerying
<?php
$m = new Mongo(),
$record = $m->demo->aric1es->findOne(),
$record = $m->demo->aric1es->findOne( array( '_id' => 'deric'r' ) ),
$record = $m->demo->aric1es->findOne( array( 'aric1es.i1e' => 'Xdebug' ) ),
$record = $m->demo->aric1es->findOne(
array( 'aric1es.i1e' => 'Xdebug' ),
array( 'name' => rue, 'aric1es.ur1' => rue )
),
var_dump( $record ),
?>
(uerying and loo"ing
Finding multi$le documents is done "ith the -ind.1,
and returns an iterator in the -orm o- a
8ongo:ursor o0&ect!
<?php
$m = new Mongo(),
$c = $m->demo->aric1es,
$cursor = $c->find(),
var_dump( $cursor ),
foreach ( $cursor as $r )
{
var_dump( $r ),
}
?>
)orting
<?php
$m = new Mongo(),
$c = $m->demo->aric1es,
$cursor = $c->find()->sor( array( '_id' => -1 ) ),
foreach ( $cursor as $r )
{
var_dump( $r ),
}
?>
*imit and s#i"
<?php
$m = new Mongo(),
$c = $m->demo->aric1es,
$cursor = $c->find(),
$cursor->sor( array( '_id' => 1 ) )
->1imi( 3 )
->s'ip( 3 ),
foreach ( $cursor as $r )
{
var_dump( $r ),
}
?>
Ad+anced ,uerying o"erators
Besides testing -or exact matches, mongoDB also
has o$erators! =$erators start "ith a H@H, so make
sure to use single 6uotesJ
:om$are#

@lt, @lte, @gt, @gte .K, K;, I, I;1

@ne .not e6ual1

@exists .-ield exists1

@mod .modulo1
,ogical#

@or .one needs to match1

@and .all need to match1

@nor .not or1

@not
Ad+anced ,uerying o"erators
2rra/#

@in .+alue needs to 0e one o- the elements o- the gi+en


arra/1

@nin .not in1

@all .+alue needs to match all elements o- the gi+en arra/1

@siLe .exact siLe o- arra/1

@elem8atch .element in an arra/ matches the s$eci-ied


match ex$ression1
=thers#

@t/$e .check -or t/$e num0er, see 1


(uerying- .gte
<?php
$m = new Mongo,
$c = $m->demo->circus,
$c->inser( array(
'_id' => 'circ1',
'name' => 'iaspora',
'performers' => 43,
'e1ephpans' => array (
array ( 'name' => 'Annabe11e', 'co1our' => 'pin'', 'year' => 1964 ),
array ( 'name' => 'Chunee', 'co1our' => 'b1ue', 'year' => 1826 )
)
) ),
$c->inser( array(
'_id' => 'circ2',
'name' => 'Sensib1e',
'performers' => 27,
'e1ephpans' => array (
array ( 'name' => 'Kandu1a', 'co1our' => 'pin'', 'year' => 2001 ),
array ( 'name' => 'Ko1a'o11i', 'co1our' => 'b1ue', 'year' => 2006 )
)
) ),
?>
Find circuses "ith '0 or more $er-ormers!
<?php
$m = new Mongo,
$c = $m->demo->circus,
$r = $c->findOne(
array( 'performers' => array( '$ge' => 40 ) ),
array( 'name' => rue, 'performers' => rue )
),
var_dump( $r ),
?>
(uerying- matching array elements
Find circuses "hich ha+e 0lue ele$h$ants a-ter
1C00!
<?php ini_se( 'xdebug.var_disp1ay_max_deph', 4 ),
$m = new Mongo,
$c = $m->demo->circus,
$r = $c->find(
array( 'e1ephpans.co1our' => 'b1ue', 'e1ephpans.year' => array( '$g' => 1900 ) )
),
foreach( $r as $c ) {
echo $c['name'|, ': ',
foreach( $c['e1ephpans'| as $e1ephpan ) {
echo "\n- ", _oin( ", ", $e1ephpan ),
}
echo "\n\n",
}
?>
(uerying- matching array elements %.elemMatch'
<?php
$m = new Mongo,
$c = $m->demo->circus,
$r = $c->find(
array (
'e1ephpans' =>
array( '$e1emMach' => array ( 'co1our' => 'b1ue', 'year' => array( '$g' => 1900 ) )
)
) ),
foreach( $r as $c ) {
echo $c['name'|, ': ',
foreach( $c['e1ephpans'| as $e1ephpan ) {
echo "\n- ", _oin( ", ", $e1ephpan ),
}
echo "\n\n",
}
?>
/"dating documents
<?php
$m = new Mongo,
$c = $m->demo->e1ephpans,
$c->remove(),
$c->inser( array( '_id' => 'e42', 'name' => 'Kamubpo' ) ),
var_dump( $c->findOne( array( '_id' => 'e42' ) ) ),
$c->updae( array( '_id' => 'e42' ), array( 'name' => 'Bo Ta' ) ),
var_dump( $c->findOne( array( '_id' => 'e42' ) ) ),
$c->updae( array( 'name' => 'Bo Ta' ), array( 'age' => '17' ) ),
var_dump( $c->findOne( array( '_id' => 'e42' ) ) ),
?>
u$date.1 re$laces the document matching criteria
entirel/ "ith a ne" o0&ect!
Modi$ying documents
<?php
$m = new Mongo,
$c = $m->demo->e1ephpans,
$c->remove(),
$c->inser( array( '_id' => 'e43', 'name' => 'umbo' ) ),
var_dump( $c->findOne( array( '_id' => 'e43' ) ) ),
$c->updae( array(
'name' => 'umbo' ), // crieria
array(
'$se' => array ( 'age' => '17' )
)
),
var_dump( $c->findOne( array( '_id' => 'e43' ) ) ),
?>
/"dating documents
E$date onl/ u$dates the -irst document it -inds 0/
de-ault!
<?php
$m = new Mongo,
$c = $m->demo->e1ephpans,
$c->drop(),
$c->inser( array( '_id' => 'e42', 'name' => 'Kamubpo', 'age' => 17 ) ),
$c->inser( array( '_id' => 'e43', 'name' => 'ena1i', 'age' => 17 ) ),
$c->updae( array( 'age' => 17 ), array( '$inc' => array( 'age' => 1 ) ) ),
var_dump( ieraor_o_array( $c->find() ) ),
?>
/"dating documents
Gou can set an o$tion to get all matching documents
to 0e u$dated
<?php
$m = new Mongo,
$c = $m->demo->e1ephpans,
$c->drop(),
$c->inser( array( '_id' => 'e42', 'name' => 'Kamubpo', 'age' => 17 ) ),
$c->inser( array( '_id' => 'e43', 'name' => 'ena1i', 'age' => 17 ) ),
$c->updae(
array( 'age' => 17 ), // crieria
array( '$inc' => array( 'age' => 1 ) ), // updae spec
array( 'mu1ip1e' => rue ) // opions
),
var_dump( ieraor_o_array( $c->find() ) ),
?>
/"serting documents
u$sert# i- the record.s1 do not exist, insert one!
<?php
$m = new Mongo,
$c = $m->demo->e1ephpans,
$c->drop(),
funcion birhay( $c, $name )
{
$c->updae(
array( 'name' => $name ), // crieria
array( '$inc' => array( 'age' => 1 ) ), // updae spec
array( 'upser' => rue ) // opions
),
var_dump( $c->findOne( array( 'name' => 'Sanon' ) ) ),
}
birhay( $c, 'Sanon' ),
birhay( $c, 'Sanon' ),
?>
Document u"date modi$iers- )ingle +alue mani"ulation

@set .sets a -ield to a ne" +alue1

@unset .remo+es a -ield1

@inc .increments the +alue in a -ield1


<?php
$m = new Mongo,
$c = $m->demo->circus,
$c->remove(),
$c->inser( array( '_id' => 'circ3', 'name' => 'Humbero', 'performers' => 12 ) ),
$c->updae( array( 'name' => 'Humbero' ), array( '$inc' => array( 'performers' => 4 ) ) ),
var_dump( $c->findOne( array( 'name' => 'Humbero' ) ) ),
?>
Document u"date modi$iers- Array mani"ulation

@$ush%@$ush2ll .adds elements to an arra/1

@add7o<et .like @$ush, 0ut "ithout du$licates in


the arra/1

@$o$ .remo+es the -irst or last element o- an


arra/1

@$ull%@$ull2ll .remo+es elements -rom an arra/1


<?php
$m = new Mongo,
$c = $m->demo->circus, $c->remove(),
$c->inser( array( '_id' => 'circ5', 'name' => 'Eunny Led' ) ),
$c->updae(
array( '_id' => 'circ5' ),
array( '$push' => array(
'e1ephpans' => array( 'name' => 'Bobo', 'year' => 2012 ) )
)
),
var_dump( $c->findOne( array( 'name' => 'Eunny Led' ), array( 'e1ephpans' => rue ) ) ),
?>
Document u"date modi$iers- Misc

@rename .renames -ields1

@0it .0it"ise u$dates o- -ield1


<?php
$m = new Mongo,
$c = $m->demo->bis,
$c->remove(),
$c->inser( array( 'bimas'' => 0b1001 ) ),
echo decbin( $c->findOne()['bimas''| ), "\n",
$c->updae( array(), array( '$bi' => array( 'bimas'' => array( 'and' => 0b0101 ) ) ) ),
echo decbin( $c->findOne()['bimas''| ), "\n",
$c->updae( array(), array( '$bi' => array( 'bimas'' => array( 'or' => 0b10100 ) ) ) ),
echo decbin( $c->findOne()['bimas''| ), "\n",
// his is no in ye ,-)
$c->updae( array(), array( '$bi' => array( 'bimas'' => array( 'xor' => 0b01110 ) ) ) ),
echo decbin( $c->findOne()['bimas''| ), "\n",
?>
!ndexes

Just like a relational data0ase, mongoDB also


0ene-its -rom indexes!

E+er/ collection has .automaticall/1 an index on


4id!

5ndexes can 0e on single or multi$le -ields!

8ongo:ursor-Iex$lain.1!
<?php ini_se('xdebug.var_disp1ay_max_deph', 1),
$m = new Mongo,
$c = $m->demo->e1ephpans,
$c->drop(),
$c->inser( array( '_id' => 'e1e1', 'name' => 'Jumbo' ) ),
$c->inser( array( '_id' => 'e1e2', 'name' => 'Tanor' ) ),
var_dump( $c->find( [ '_id' => 'e1e1' | )->exp1ain() ),
?>
!ndexes
<?php ini_se('xdebug.var_disp1ay_max_deph', 1),
$m = new Mongo,
$c = $m->demo->e1ephpans,
$c->drop(),
$c->inser( [ '_id' => 'e1e1', 'name' => 'Jumbo' | ),
$c->inser( [ '_id' => 'e1e2', 'name' => 'Tanor' | ),
$c->inser( [ '_id' => 'e1e3', 'name' => 'Sampy' | ),
var_dump( $c->find( [ 'name' => 'Jumbo' | )->exp1ain() ),
?>
!ndexes
<?php ini_se('xdebug.var_disp1ay_max_deph', 1),
$m = new Mongo,
$c = $m->demo->e1ephpans,
$c->drop(),
$c->ensureIndex( [ 'name' => 1 | ),
$c->inser( [ '_id' => 'e1e1', 'name' => 'Jumbo' | ),
$c->inser( [ '_id' => 'e1e2', 'name' => 'Tanor' | ),
$c->inser( [ '_id' => 'e1e3', 'name' => 'Sampy' | ),
var_dump( $c->find( [ 'name' => 'Jumbo' | )->exp1ain() ),
?>
Geos"atial !ndexes
Hel$s /ou "ith -inding locations .$u0sJ1 in a 2D
s$ace
<?php
$m = new Mongo, $c = $m->demo->pubs, $c->drop(),
$c->ensureIndex( array( '1ocaion' => '2d' ) ),
$c->inser( [ '_id' => 'pub1', 'name' => 'Mrs Besy Smih', '1ocaion' => [ -0.1933, 51.5375 | | ),
$c->inser( [ '_id' => 'pub2', 'name' => 'Norh London Tavern', '1ocaion' => [ -0.2025, 51.5455 | | ),
$c1oses = $m->demo->command( [
'geoNear' => 'pubs',
'near' => [ -0.198, 51.538 |,
'spherica1' => rue,
| ),
//var_dump( $c1oses['sas'| ),
foreach ( $c1oses['resu1s'| as $res ) {
prinf( "%s: %.2f 'm\n", $res['ob_'|['name'|, $res['dis'| * 6378 ),,
}
?>
ommands

2re run on the data0ase

Do not return a cursor

Return one document

<ome commands ha+e hel$ers in the dri+ers and


shell
Distinct
<?php
$m = new Mongo, $c = $m->demo->pubs, $c->drop(),
$c->inser( [ '_id' => 'pub1', 'name' => 'Mrs Besy Smih', 'ciy' => 'London' | ),
$c->inser( [ '_id' => 'pub2', 'name' => 'Norh London Tavern', 'ciy' => 'London' | ),
$c->inser( [ '_id' => 'pub3', 'name' => 'Lammars', 'ciy' => 'Mancheser' | ),
$c->inser( [ '_id' => 'pub4', 'name' => 'Weaherspoons', 'ciy' => 'Covenry' | ),
$r = $m->demo->command( [
'disinc' => 'pubs',
''ey' => 'ciy',
'query' => [ 'name' => [ '$ne' => 'Weaherspoons' | |
| ),
var_dump( $r['va1ues'| ),
?>
Aggregation 0ramewor#
1ew in &2&
Po"er-ull -rame"ork -or running multi$le o$erations
in a $i$eline
=$erations are#

@match# -or matching documents, M la -ind.1!

@$ro&ect# -or Are"ritingA documents, 0ut more


$o"er-ul "ith com$uted ex$ressions# adding -ields
.@add1, conditions .@i->ull1, string -unctions
.@to,o"er1, etc

@un"ind# hands out arra/ elements each at a time

@grou$# aggregates items into 0uckets de-ined 0/


ke/

@sort

@limit % @ski$
Aggregation 3xam"le
<?php
$m = new Mongo, $d = $m->demo, $c = $d->aric1es, $c->drop(),
$c->inser( [
"i1e" => "Rrofi1ing RHR App1icaions",
"ur1" => "hp://deric'rehans.n1/a1's/profi1ing-phpour1i11e11.pdf",
"ags" => [ "php", "profi1ing" |
| ),
$c->inser( [
"i1e" => "Xdebug",
"ur1" => "hp://deric'rehans.n1/a1's/xdebug-phpbcn11.pdf",
"ags" => [ "php", "xdebug" |
| ),
$m = $d->command( [
'aggregae' => 'aric1es',
'pipe1ine' => [
[ '$mach' => [ 'ags' => 'php' | |,
[ '$unwind' => '$ags' |,
[ '$pro_ec' => [
'i1e' => [ '$add' => [ '$i1e', ': ', '$ur1' | |,
'ag' => '$ags'
| |
|
| ),
foreach( $m['resu1'| as $res ) { echo $res['i1e'|, ' (', $res['ag'|, ")\n", }
?>
Tools and monitoring

Nhengis# single -ile mongoDB management a$$ .a


la $h$8/2dmin1

Rock8ongo# mongoDB management a$$ .a la


$h$8/2dmin1

88<# hosted a$$lication -or instrumentation


Ghengis
MM)
4esources

Do"nload mongoDB#
htt$#%%"""!mongod0!org%do"nloads

B<=> <$ec# htt$#%%0sons$ec!org%

7hese slides# htt$#%%derickrethans!nl%talks!html

:ontact me# Derick Rethans# derickr,


derick10gen!com

Feed0ack# htt$#%%&oind!in%'()*

You might also like