Using the PHP Library for MongoDB (PHPLIB)After the initial extension set-up, we will continue explaining how to get started with the corresponding userland library to write our first project. Installing the PHP Library with ComposerThe 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: Using the PHP LibraryIn 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:
With this done, you can now use any of the functionality as described in the » library documentation. If you have used MongoDB drivers in other languages, the library's API should look familiar. It contains a » Client class for connecting to MongoDB, a » 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). As an example, this is how you insert a document into the beers collection of the demo database:
Since the inserted document did not contain an
After insertion, you can query for the data that you have just inserted.
For that, you use the
While it may not be apparent in the examples, BSON documents and arrays are
unserialized as special classes in the library by default. These classes
extend ArrayObject for usability and implement the
extension's MongoDB\BSON\Serializable and
MongoDB\BSON\Unserializable interfaces to
ensure that values preserve their type when serialized back into BSON. This
avoids a caveat in the legacy |