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=^1.0.0"

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 and its » API.

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 goodies

$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 goodies

$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.

Коментарии

Автор:
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);
2016-02-23 17:53:54
http://php5.kiev.ua/manual/ru/mongodb.tutorial.library.html
Автор:
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
2016-08-12 07:10:38
http://php5.kiev.ua/manual/ru/mongodb.tutorial.library.html
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
}
?>
2017-05-15 19:03:50
http://php5.kiev.ua/manual/ru/mongodb.tutorial.library.html
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);

?>
2018-03-16 19:03:35
http://php5.kiev.ua/manual/ru/mongodb.tutorial.library.html
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;

?>
2019-08-16 22:16:38
http://php5.kiev.ua/manual/ru/mongodb.tutorial.library.html
Автор:
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]]);
?>
2019-10-23 20:40:01
http://php5.kiev.ua/manual/ru/mongodb.tutorial.library.html
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.
2024-11-07 11:21:18
http://php5.kiev.ua/manual/ru/mongodb.tutorial.library.html

    Поддержать сайт на родительском проекте КГБ