3

I m trying to make a query in PHP with the MongoDB\Driver\Query class but with the doc in php.net I didn't really understand how to make it work. I would like to return a JSON object with all data of my collection.

This for a function PHP running with Php 7.1.2 and MongoDB 3.2.20

$m = new MongoDB\Driver\Manager("mongodb://login:password@127.0.0.1:27017/");

$filter = array('id' => 0);
$options = array(
    'projection' => ['name' => $parameters['baseName']]
);

$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $m->executeQuery(''db_name.my_collection', $query);

$myJson = json_decode(json_encode($cursor),true);

Harsh Patel
  • 6,334
  • 10
  • 40
  • 73
Vaaalaa
  • 41
  • 2
  • Are you getting any errors or results at all? What does your model look like? – Kyrre Jun 13 '19 at 13:49
  • It seems to be related with answer https://stackoverflow.com/a/14232565/612175, wich says to use json_encode(iterator_to_array($cursor)) to resolve it. – Damien Jun 13 '19 at 14:01

2 Answers2

0

You can use this as said here:

json_encode(iterator_to_array($cursor))
Damien
  • 352
  • 3
  • 11
0
try
    {
        $client = new MongoDB\Driver\Manager("mongodb://login:password@127.0.0.1:27017/");
    }
    catch (Exception $e)
    {
        echo "***DB Client not created*** " . $e->getMessage();
        saveEvent("DB Client not created" . $e->getMessage(), $owner);
        exit();
    }
    $filter = ['id'=> $lookForID];
    $query = new MongoDB\Driver\Query($filter);
    try
    {
        $rows = $client->executeQuery('dbName.collectionName', $query);
    }
catch (Exception $e)
    {
        echo "***search failed*** " . $e->getMessage();
        exit();
    }
    foreach($rows as $r){
       print_r($r);
    }
Arkady Karasin
  • 159
  • 6
  • 17