user1400312
user1400312

Reputation:

Regex MongoDB PHP Query

I'm looking to perform a REGEX on a MongoDB find query that only finds anything with image in the string, what its searching is a filetype header so it would generally looked like image/png or text/html.

I am running this code for the regex:

array('fileType'=>array('$regex'=>'^image'))

And this code alltogether:

foreach ($this->grid->find(array('fileType'=>array('$regex'=>'^image'))) as $file) {
                        $id = (string) $file->file['_id'];
                        $filename = htmlspecialchars($file->file["filename"]);
                        $filetype = isset($file->file["filetype"]) ? $file->file["filetype"] : 'application/octet-stream';

                        if($filetype == 'image/'.$chosenfile.''){
                            $links[] = sprintf('<img src="lib/download.php?id=%s" height="200px" width="200px">', $id);
                        }elseif($chosenfile == ''){
                             $links[] = sprintf('<img src="lib/download.php?id=%s" height="200px" width="200px">', $id);
                        }
                    }

Upvotes: 4

Views: 13852

Answers (3)

Hakan
Hakan

Reputation: 597

as of MongoDB 8.0.4

//php
$filter = ['fileType' => ['$regex' => '^image', '$options' => 'i']];
$rr = $collection->find( $filter  );

Upvotes: 0

Ankur Rupapara
Ankur Rupapara

Reputation: 136

check below mongodb instance query using php it's works..

$pipeline = array(
                array('$match' => array(
                                    '$and' => array(array('data_UTC' => array('$gte' => new MongoDate(strtotime('2017-01-20T00:00:00-02:00')),
                                                                                '$lt' => new MongoDate(strtotime('2017-01-29T00:00:00-02:00'))
                                                                        ),
                                                            'carga' => array('regex' => new MongoRegex('/^soja/i'))
                                                        )
                                                )
                                )
                ),
                array('$group' => array('_id' => array('$dataToString' => array('format' => '%Y-%m-%d', 'date' => array('$subtract' => array('$data_UTC', 1000 * 60 * 60 * 2)))), 'qtd_acessos' => array('$sum' => 1 ))),
                array('$sort' => array('_id' => -1)),
                array('$limit' => 50)
            );
$results = $this->mongodb->aggregate($pipeline);

Upvotes: 0

Sammaye
Sammaye

Reputation: 43884

This is your problem:

array('$regex'=>'^image')

It should be using the MongoRegex object:

array('fileType' => new MongoRegex('/^image/i'))

The documentation is defined here: http://www.php.net/manual/en/class.mongoregex.php

Does it work now?

Upvotes: 11

Related Questions