downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | conferences | my php.net

search for in the

Estableciendo una Conexión> <Manual
[edit] Last updated: Fri, 07 Jun 2013

view this page in

Tutorial

Tabla de contenidos

Este es el controlador de PHP admitido de 10gen para MongoDB.

He aquí un código de ejemplo que contecta, 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.

<?php

// conectar
$m = new MongoClient();

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

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

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

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

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

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

?>

El resultado del ejemplo sería:

Calvin and Hobbes
XKCD


add a note add a note User Contributed Notes Tutorial - [2 notes]
up
0
Josh Heidenreich
2 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: http://jira.mongodb.org/browse/PHP-91

Update to the latest connector driver and it should go away.
up
0
php at whoah dot net
3 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');
unset($array[1]);

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

// assuming local
$mongo = new Mongo();
$mongo->test->test->insert($document);

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: http://jira.mongodb.org/browse/PHP-104

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.

 
show source | credits | sitemap | contact | advertising | mirror sites