PHP 5.6.0RC3 is available


Tabla de contenidos

Este es el controlador oficial de MongoDB para PHP.

Lo siguiente es una muestra de código que conecta, inserta documentos, consulta a documentos, itera sobre resultados de consultas, y desconecta de MongoDB. Hay más detalles de cada paso del tutorial más abajo.


// conectar
$m = new MongoClient();

// seleccionar una base de datos
$bd $m->comedy;

// seleccionar una colección (equivalente a una tabla en una base de datos relacional)
$colección $bd->cartoons;

// añadir un registro
$documento = array( "title" => "Calvin and Hobbes""author" => "Bill Watterson" );

// añadir un nuevo registro, con un distinto "perfil"
$documento = array( "title" => "XKCD""online" => true );

// encontrar todo lo que haya en la colección
$cursor $colección->find();

// recorrer el resultado
foreach ($cursor as $documento) {
$documento["title"] . "\n";


El resultado del ejemplo sería:

Calvin and Hobbes
add a note add a note

User Contributed Notes 3 notes

pgl at yoyo dot org
10 months ago
To use a collection with periods in its name, quote it with braces:

= new MongoClient();

$cursor = $m->test->{'test.test'}->find();

## equivalent to the following:
#$db = $m->test;
#$collection = $db->{'test.test'};
#$cursor = $collection->find();

foreach ($cursor as $doc) {
Josh Heidenreich
3 years ago
If you are getting "writing more" shown at random places on the screen, it's a MongoDB connector bug in 1.0.5.

Bug report:

Update to the latest connector driver and it should go away.
php at whoah dot net
4 years ago
Make sure array keys consecutive before inserting. As of 1.0.6 driver, the following will end up as an object of key:value pairs, instead of an array, because it's trying to maintain the 0 and 2 keys:

$array = array('a', 'b', 'c');

$document = array(
'embedded' => $array,

// assuming local
$mongo = new Mongo();

mongodb result:
{ "_id" : ObjectId(...), "embedded" : { "0" : "a", "2" : "c" } }

This is bad if you plan on indexing the embedded property as an array because objects and arrays are indexed differently.

Whether the behaviour will change or not, this is logged here:

If you know about it, it's not major, just use a sort() before inserting, or use array_* methods to remove elements instead of unset() -- anything that will re-adjust keys.
To Top