Search code examples
phpmongodblimit

Mongodb query with PHP variable is not working with Limit


I have write a script for Mongodb with php and its working fine when limit is in static number while when we pass varible in script it throw error.

Script code is:

array(
                                "\$match" => array(
                                    "\$or" => array(
                                        array(
                                            'title' => new \MongoDB\BSON\Regex($queryString),
                                        ),
                                        array(
                                            'description' => new \MongoDB\BSON\Regex($queryString),
                                        ),
                                        array(
                                            'master.title' => new \MongoDB\BSON\Regex($queryString),
                                        ),
                                    ),

                                    "\$and" => array(
                                    array(
                                        'created_on' => new \MongoDB\BSON\Regex($filterDate)
                                        )
                                    )
                                )
                            ),

                            array(
                                '$sort' => array(
                                    'created_on' => -1
                                )
                            ),
                            array(
                                '$limit' => $filterLimit,
                            )

'$limit' => $filterLimit, is not working while when we pass static number its working fine.

if we replace

                              array(
                                    '$limit' => $filterLimit,
                                )

to

                             array(
                                    '$limit' => 10,
                                )

its working fine.Below is the error

Fatal error: Uncaught MongoDB\Driver\Exception\CommandException: the limit must be specified as a number in


Solution

  • $filterLimit may be a string, try to cast it as an integer :

    array(
        '$limit' => intval($filterLimit),
    )