Using the library

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

PHP Library (PHPLIB)

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. In your project directory (/var/www/html/my-first-project) type:

curl -sS https://getcomposer.org/installer -o installer.php
hhvm installer.php
rm installer.php

This downloads and installs Composer. Wherever it says "Use it: php composer.phar", it of course means hhvm composer.phar.

With Composer installed, we can now install the library:

hhvm composer.phar require mongodb/mongodb

It outputs something akin to:

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

Writing lock file
Generating autoload files

And it has created several files (composer.json, composer.lock) as well as the vendor directory that contains the library.

Using the Library

Composer manages your dependencies, and will provide you with a loader that you include with the following at the start of your script:

<?php
    
require 'vendor/autoload.php';

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

If you are familiar with the old driver, it should look too much out of place. The only big difference is that the » Database class is only used for Database specific operations. The » CRUD operations on the » Collection class are also 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 goodies

    
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
    
$collection = new MongoDB\Collection($manager"demo.beers");

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

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

Instead of the original document being modified to add the newly generated _id field, this is now part of the result that comes back from 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 a cursor that you can iterate over:

<?php
    
require 'vendor/autoload.php'// include Composer goodies

    
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
    
$collection = new MongoDB\Collection($manager"demo.beers");

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

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

You might have noticed that instead of accessing the _id and name fields is no longer done through an array access operator. Instead, they are now properties of a stdClass object. You can find more information on how serialisation and deserialisation between PHP variables and the BSON stored in MongoDB in the Persisting Data specification.

add a note add a note

User Contributed Notes 7 notes

up
17
surajtiwari020 at gmail dot com
6 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
13
crystale dot darck at gmail dot com
6 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
1
wpg
4 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
1
salos_12 at hotmail dot com
4 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
3
Dc Shiman
8 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
2
Basher
7 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
-11
myname
5 years ago
What folder we need to be in to run composer? I can't get it to work.
To Top