How to use Mongodb 'Regex' filter in PHP

Asked

Viewed 122 times

-1

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

Currently, in the Mongodb bank 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 that contain certain text part of 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(https://docs.mongodb.com/php-library/master/tutorial/crud/#regular-Expressions). 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 done before was this.

<?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 the documents filtering part of the value of a field?

Note: I can bring several documents using find.

I have tried to follow these other examples:

-https://stackoverflow.com/questions/34707657/set-filter-with-regex-in-query-with-phps-mongodb-driver-query-class

-https://stackoverflow.com/questions/45523046/mongodb-php-search-for-string-with-query

-http://php.net/manual/en/class.mongodb-driver-query.php

1 answer

0


I was able to solve it this way;

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.