Mongodb and php example

Connecting to MongoDB

If you do not specify a $uri value, the driver connects to a standalone mongod on 127.0.0.1 via port 27017 . To connect to a different server, pass the corresponding connection string as the first parameter when creating the Client instance:

 $client = new MongoDB\Client('mongodb://mongodb-deployment:27017'); 

Connecting to a Replica Set

The following example demonstrates how to connect to a replica set with a custom read preference:

 $client = new MongoDB\Client( 'mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet', [ 'readPreference' => 'secondaryPreferred', ] ); 

Connecting with SSL and Authentication

The following example demonstrates how to connect to a MongoDB replica set with SSL and authentication, as is used for MongoDB Atlas:

 $client = new MongoDB\Client( 'mongodb://myUsername:myPassword@rs1.example.com,rs2.example.com/?ssl=true&replicaSet=myReplicaSet&authSource=admin' ); 

Alternatively, the authentication credentials and URI parameters may be specified in the constructor’s $uriOptions parameter:

 $client = new MongoDB\Client( 'mongodb://rs1.example.com,rs2.example.com/' [ 'username' => 'myUsername', 'password' => 'myPassword', 'ssl' => true, 'replicaSet' => 'myReplicaSet', 'authSource' => 'admin', ], ); 

The driver supports additional SSL options, which may be specified in the constructor’s $driverOptions parameter. Those options are covered in the MongoDB\Driver\Manager::__construct() documentation.

Specifying connection options

Connection options can be passed via the $uri parameter, or through the $options and $driverOptions parameters. The available options are documented in the MongoDB\Client::__construct() reference.

© MongoDB, Inc 2008-present. MongoDB, Mongo, and the leaf logo are registered trademarks of MongoDB, Inc.

Источник

Creating, Reading, Updating, and Deleting MongoDB Documents with PHP

PHP badge

Welcome to Part 2 of this quick start guide for MongoDB and PHP. In the previous article , I walked through the process of installing, configuring, and setting up PHP, Apache, and the MongoDB Driver and Extension so that you can effectively begin building an application leveraging the PHP, MongoDB stack.

I highly recommend visiting the first article in this series to get set up properly if you have not previously installed PHP and Apache.

I’ve created each section with code samples. And I’m sure I’m much like you in that I love it when a tutorial includes examples that are standalone. They can be copy/pasted and tested out quickly. Therefore, I tried to make sure that each example is created in a ready-to-run fashion.

These samples are available in this repository , and each code sample is a standalone program that you can run by itself. In order to run the samples, you will need to have installed PHP, version 8, and you will need to be able to install additional PHP libraries using Compose . These steps are all covered in the first article in this series.

Additionally, while I cover it in this article, it bears mentioning upfront that you will need to create and use a .env file with your credentials and the server name from your MongoDB Atlas cluster.

This guide is organized into a few sections over a few articles. This first article addresses the installation and configuration of your development environment. PHP is an integrated web development language. There are several components you typically use in conjunction with the PHP programming language.

Connecting to a MongoDB Database Instance

Just a note about language. Throughout this article, we use the term create and insert interchangeably. These two terms are synonymous. Historically, the act of adding data to a database was referred to as CREATING . Hence, the acronym CRUD stands for Create, Read, Update, and Delete. Just know that when we use create or insert, we mean the same thing.

Protecting Sensitive Authentication Information with DotEnv (.env)

When we connect to MongoDB, we need to specify our credentials as part of the connection string. You can hard-code these values into your programs, but when you commit your code to a source code repository, you’re exposing your credentials to whomever you give access to that repository. If you’re working on open source, that means the world has access to your credentials. This is not a good idea. Therefore, in order to protect your credentials, we store them in a file that does not get checked into your source code repository. Common practice dictates that we store this information only in the environment. A common method of providing these values to your program’s running environment is to put credentials and other sensitive data into a .env file.

To create your own environment file, create a file called .env in the root of your program directory. You can simply copy the example environment file I’ve provided and rename it to .env . Be sure to replace the values in the file yourusername , yourpassword , and mycluster.zbcul.mongodb.net with your own.

Once the environment file is in place, you can use Composer to install the DotEnv library, which will enable us to read these variables into our program’s environment. See the first article in this series for additional setup instructions.

Once installed, you can incorporate this library into your code to pull in the values from your .env file.

Источник

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:

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:

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:

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.

Источник

Читайте также:  Что такое навигация html
Оцените статью