How to use MongoDB 'Regex' filter in PHP

-1

I have already made a few attempts following examples on the internet, I found some until there seems to be a mixture of the two versions of the driver

Currently, in the MongoDB database I have a structure similar to the following example:

{
   "@versao": "3.10",
   "Documento": {
      "@Id": "ABCD123456789"
   },
   "protDoc": {
      "@versao": "3.10",
      "infDoc": {
         "Amb": "1",
         "Chave": "545asd828322852",
         "dhRecbto": "2017-05-23T23:24:00-03:00",
         "nProt": "17894060",
         "digVal": "+zVS8UJBtNk2edU478TUya6vGXs=",
      }
   }
}

My attempts are to get the documents containing a certain part of the text from the '@Id' field, in Compass I can filter using the following filter

{'doc.Documento.@Id': {$regex : '123456789$'}} //Informo só parte do Id

In PHP, my last attempt was to follow the MongoDB documentation ( link ). The Code is like this.

<?php
$conn = new MongoClient("mongodb://192.168.123.1:27017");
$collection = $conn->DB->colecao;

$cursor = $collection->find([
        'doc.Documento.@Id' => new MongoDB\BSON\Regex('123456789$', 'i')
        ]);

var_dump($cursor) //Não há nada

I tried to use the filters differently but there was no success. Another setup I had previously done was that.

<?php
$manager = new MongoDB\Driver\Manager('mongodb://192.168.123.1:27017');

$filtro = ['doc.Documento.@Id' => ['$regex' => '123456789$']];
$opcoes = [];

$query = new MongoDB\Driver\Query($filtro, $opcoes);

$documentos = $manager->executeQuery('DB.colecao', $query);
var_dump($documentos);//Não há nada

What would be the correct way to bring documents by filtering part of the value of a field?

Note: I can bring several documents using find.

I've tried to follow these other examples:

- link

- link

- link

    
asked by anonymous 04.07.2018 / 15:07

1 answer

0

I was able to solve it as follows;

    $regex = new MongoDB\BSON\Regex(trim('123456789', '/'), 'i');

    $search = array('doc.Documento.@Id' => $regex);
    $options = [
    "skip" => 0,
    "limit" => 10,
    "projection" => []
    ];

    $query = new MongoDB\Driver\Query($search, $options);
    $cursor = $manager->executeQuery('DataBase.Colection', $query);

    foreach ($cursor as $doc) {
       $doc = json_decode(json_encode($doc), true);
       var_dump($doc);
       break;
    }

So I get all the documents in return.

    
06.07.2018 / 16:56