Using the PHP Library for MongoDB (PHPLIB)

After the initial driver set-up, we will continue explaining how to get started with the MongoDB driver and corresponding userland library to write our first project.

Installing the PHP Library with Composer

The last thing we still need to install to get started on the application itself, is the PHP library.

The library needs to be installed with » Composer, a package manager for PHP. Instructions for installing Composer on various platforms may be found on its website.

Install the library by running:

$ composer require mongodb/mongodb

It will output something akin to:

./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 will create several files: composer.json, composer.lock, and a vendor directory that will contain the library and any other dependencies your project might require.

Using the PHP Library

In addition to managing your dependencies, Composer will also provide you with an autoloader (for those dependencies' classes). Ensure that it is included at the start of your script or in your application's bootstrap code:

<?php
// This path should point to Composer's autoloader
require 'vendor/autoload.php';

With this done, you can now use any of the functionality as described in the » library documentation.

If you have previously used the old driver (i.e. mongo extension), the library's API should look familiar. It contains a » Client class for connecting to MongoDB, and » Database class for database-level operations (e.g. commands, collection management) and a » Collection class for collection-level operations (e.g. » CRUD methods, index management). Various Collection methods have been renamed for clarity, and to be in accordance with a new language-agnostic » specification.

As an example, this is how you insert a document into the beers collection of the demo database:

<?php
require 'vendor/autoload.php'// include Composer's autoloader

$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()}'";
?>

Instead of injecting the generated _id field into the input document (as was done in the old driver), it is now made available through the result object returned by the insertOne method.

After insertion, you can of course also query the data that you have just inserted. For that, you use the find method, which returns an iterable cursor:

<?php
require 'vendor/autoload.php'// include Composer's autoloader

$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";
}
?>

While it may not be apparent in the examples, BSON documents and arrays are unserialized as type classes in the library by default. These classes ensure that values preserve their type when being serialized back into BSON, which avoids a caveat in the old driver where arrays might turn into documents, and vice versa. Additionally, the classes extend ArrayObject for enhanced usability. You can find more information on how serialization and deserialization between PHP variables and BSON is handled by the driver and library by reading the Persisting Data specification.

Hier Kannst Du einen Kommentar verfassen


Bitte gib mindestens 10 Zeichen ein.
Wird geladen... Bitte warte.
* Pflichtangabe
Es sind noch keine Kommentare vorhanden.

PHP cURL-Tutorial: Verwendung von cURL zum Durchführen von HTTP-Anfragen

cURL ist eine leistungsstarke PHP-Erweiterung, die es Ihnen ermöglicht, mit verschiedenen Servern über verschiedene Protokolle wie HTTP, HTTPS, FTP und mehr zu kommunizieren. ...

TheMax

Autor : TheMax
Kategorie: PHP-Tutorials

Midjourney Tutorial - Anleitung für Anfänger

Über Midjourney, dem Tool zur Erstellung digitaler Bilder mithilfe von künstlicher Intelligenz, gibt es ein informatives Video mit dem Titel "Midjourney Tutorial auf Deutsch - Anleitung für Anfänger" ...

Mike94

Autor : Mike94
Kategorie: KI Tutorials

Grundlagen von Views in MySQL

Views in einer MySQL-Datenbank bieten die Möglichkeit, eine virtuelle Tabelle basierend auf dem Ergebnis einer SQL-Abfrage zu erstellen. ...

admin

Autor : admin
Kategorie: mySQL-Tutorials

Tutorial veröffentlichen

Tutorial veröffentlichen

Teile Dein Wissen mit anderen Entwicklern weltweit

Du bist Profi in deinem Bereich und möchtest dein Wissen teilen, dann melde dich jetzt an und teile es mit unserer PHP-Community

mehr erfahren

Tutorial veröffentlichen

Daten einer Abfrage mit Hilfe von Thumbnails nebeneinander ausgeben

Warum soll ich float meiden? Siehe https://www.linkedin.com/pulse/css-float-vs-grid-flexbox-sachin-tiwari Falls es mit Englisch nicht so klappt: ...

Geschrieben von scatello am 18.05.2024 05:57:56
Forum: PHP Developer Forum
Daten einer Abfrage mit Hilfe von Thumbnails nebeneinander ausgeben

Also den Fehler habe ich gefunden und abgestellt. Warum soll ich float meiden?

Geschrieben von Malchor am 17.05.2024 20:54:01
Forum: PHP Developer Forum
Daten einer Abfrage mit Hilfe von Thumbnails nebeneinander ausgeben

Dein HTML-Code ist definitiv kaputt und float solltest du auch vergessen. Beschäftige dich mit Flex-Box oder Grid

Geschrieben von scatello am 17.05.2024 20:43:50
Forum: PHP Developer Forum
Daten einer Abfrage mit Hilfe von Thumbnails nebeneinander ausgeben

Da ich viele unterschiedliche Tabellen benötige mache ich das so umständlich. Aber ist das der Grund warum das Floaten nicht funktioniert?

Geschrieben von Malchor am 17.05.2024 17:15:03
Forum: PHP Developer Forum