PHP 8.3.21 Released!

Utilizar la biblioteca PHP para MongoDB (PHPLIB)

Después de la configuración inicial de la extensión, se continuará explicando cómo comenzar con la biblioteca de usuario correspondiente para escribir nuestro primer proyecto.

Instalar la biblioteca PHP con Composer

La última cosa que se debe instalar para comenzar la aplicación en sí es la biblioteca PHP.

La biblioteca debe ser instalada con » Composer, un gestor de paquetes para PHP. Las instrucciones para instalar Composer en diferentes plataformas pueden encontrarse en su sitio web.

Instalar la biblioteca ejecutando:

$ composer require mongodb/mongodb

Esto producirá una salida similar a:

./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing mongodb/mongodb (1.0.0)
    Downloading: 100%

Writing lock file
Generating autoload files

Composer creará varios ficheros: composer.json, composer.lock, y un directorio vendor que contendrá la biblioteca y todas las otras dependencias que su proyecto podría necesitar.

Utilizar la biblioteca PHP

Además de gestionar sus dependencias, Composer también le proporcionará un autocargador (para las clases de estas dependencias). Asegúrese de que esté incluido al inicio de su script o en el código de arranque de su aplicación:

<?php
// Esta ruta debe apuntar al autocargador de Composer
require 'vendor/autoload.php';

Con esto hecho, ahora puede utilizar cualquier funcionalidad como se describe en la » documentación de la biblioteca.

Si ha utilizado controladores MongoDB en otros lenguajes, la API de la biblioteca debería resultarle familiar. Contiene una clase » Client para conectarse a MongoDB, una clase » Database para las operaciones a nivel de la base de datos (por ejemplo, los comandos, la gestión de las colecciones), y una clase » Collection para las operaciones a nivel de la colección (por ejemplo, los métodos » CRUD, la gestión de los índices).

Como ejemplo, aquí se muestra cómo insertar un documento en la colección beers de la base de datos demo:

<?php
require 'vendor/autoload.php'; // incluir el autocargador de Composer

$client = new MongoDB\Client("mongodb://localhost:27017");
$collection = $client->demo->beers;

$result = $collection->insertOne( [ 'name' => 'Hinterland', 'brewery' => 'BrewDog' ] );

echo
"Inserted with Object ID '{$result->getInsertedId()}'";
?>

Dado que el documento insertado no contenía un campo _id, la extensión generará un MongoDB\BSON\ObjectId para que el servidor lo utilice como _id. Este valor también está disponible para el llamador a través del objeto de resultado devuelto por el método insertOne.

Después de la inserción, se pueden consultar los datos que acaba de insertar. Para ello, se utiliza el método find, que devuelve un cursor iterable:

<?php
require 'vendor/autoload.php'; // incluir el autocargador de Composer

$client = new MongoDB\Client("mongodb://localhost:27017");
$collection = $client->demo->beers;

$result = $collection->find( [ 'name' => 'Hinterland', 'brewery' => 'BrewDog' ] );

foreach (
$result as $entry) {
echo
$entry['_id'], ': ', $entry['name'], "\n";
}
?>

Aunque los ejemplos no lo muestran, los documentos BSON y los arrays son deserializados como clases especiales en la biblioteca por defecto. Estas clases extienden ArrayObject para facilidad de uso e implementan las interfaces MongoDB\BSON\Serializable y MongoDB\BSON\Unserializable de la extensión para garantizar que los valores conserven su tipo cuando se serializan nuevamente en BSON. Esto evita un inconveniente de la antigua extensión mongo donde los arrays podrían convertirse en documentos, y viceversa. Ver la especificación Persistir datos para más información sobre cómo se convierten los valores entre PHP y BSON.

add a note

User Contributed Notes 7 notes

up
22
surajtiwari020 at gmail dot com
7 years ago
Well most of the tutorials didn't explained well, So i hope this might help someone
Note: this is a part of my laravel project

//getting data from a collection
<?php

use MongoDB\Client as Mongo;

$user = "admin";
$pwd = 'password';

$mongo = new Mongo("mongodb://${user}:${pwd}@127.0.0.1:27017");
$collection = $mongo->db_name->collection;
$result = $collection->find()->toArray();

print_r($result);

?>
up
10
salos_12 at hotmail dot com
5 years ago
When your database name contains a "-" (e.g. database-name) you need to use a string instead.

<?php

$client
= new MongoDB\Client("mongodb://ip_address:port");
$collection = $client->{'database-name'}->collection;

?>
up
4
wpg
5 years ago
If you have a number of JSON documents with nested elements such as 'responseId' below and you want to know how many documents have a responseId:
{"result":{"responseId":"xyz"}}
{"result":NULL}
{"result":{"responseId":"abc"}}

I was not having luck with the following format
<?php
// trying to get the count of documents where responseId is not equal to NULL (did not work for me)
$intCount = $collection->count(['result' => ['responseId' => ['$ne' => NULL]]]);
?>

Instead I needed to use a period between the JSON elements:
<?php
// get the count of documents where responseId is not equal to NULL
$intCount = $collection->count(['result.responseId' => ['$ne' => NULL]]);
?>
up
9
crystale dot darck at gmail dot com
7 years ago
To test your connection string, you can do something like this:

<?php
$mongo
= new MongoDB\Client('mongodb://my_server_does_not_exist_here:27017');
try
{
$dbs = $mongo->listDatabases();
}
catch (
MongoDB\Driver\Exception\ConnectionTimeoutException $e)
{
// PHP cannot find a MongoDB server using the MongoDB connection string specified
// do something here
}
?>
up
6
Dc Shiman
9 years ago
Do a text search on the collection with projection

$search['$text'] = ['$search' => "foo"];
$options["projection"] = ['score' => ['$meta' => "textScore"]];
$options["sort"] = ["score" => ['$meta' => "textScore"]];

$cursor = $collection->find($search, $options);
up
4
Basher
8 years ago
Pecl MongoDB at time of writing can be installed (see phpinfo()) but composer will complain that it's not present.

$ composer require "mongodb/mongodb=^1.0.0"
...
Your requirements could not be resolved to an installable set of packages.

If you see this try

$ composer require "mongodb/mongodb=^1.0.0" --ignore-platform-reqs
up
0
drankinatty at NOSPAMgmail dot com
6 months ago
One question that was unanswered was how to handle insertion of a full JSON document provided as an argument (or in a string variable). The mongodb extension can handle this by simply using json_decode() to convert the JSON document to an object that can then be easily inserted, e.g. (with full document provided as the 2nd command-line argument)

<?php
/* include libmongo API */
require "vendor/autoload.php";

/* include connection string, db and collection values */
require __DIR__ . '/site/db-mongo-inc.php';

/* use MongoDBClient; */
use MongoDB\Client;

/* connection string */
$uri = "mongodb://$user:$pass@localhost";

/* attempt connection to database with $uri */
$client = new MongoDB\Client("$uri");
if (!isset(
$client)) {
echo
'error: connection failed';
}

/* define collection of documents */
$collection = $client->$db->$collection;

/* insert JSON document from string variable (here $argv[2]) */
if ($argc > 2) {
$jsobj = json_decode ($argv[2]);
if (
$jsobj) {
$iresult = $collection->insertOne ( $jsobj );
if (!
$iresult) {
printf ("error: insert of object failed.\n");
}
}
}
?>

The extension's block insert feature recursively resolves all field and data values contained in the object and inserts the entire document in the collection. It is helpful to remove the "_id:" field and have that auto-generated for you to avoid issues.
To Top