Link to home
Start Free TrialLog in
Avatar of Rick Pratt
Rick Pratt

asked on

PHP Mongodb aggregrate query error

Hi There,

I have a mongodb aggregate query in PHP that is throwing an error and I can't see what I've missed in the syntax.

Versions are
mongodb =  3.6
PHP  = 7.1
mongo PHP driver = 1.3.1-1


 The query in mongo shell works and looks like this:

db.products.aggregate(
	[
		{
			$match: {
			    download_Date : {'$gte' : 20180205 }
			}},
		{
			$sort: {
			download_Date: 1 }
		},
		{
			$group: {
			 _id: "$cw_product_id", batch: { $last : "$download_Date" }
	        }},
	]

Open in new window


My code in PHP fails and  looks like

$command = new MongoDB\Driver\Command([
    'aggregate' => 'products',
    'pipeline' => [    
        ['$match' =>  [ 'download_Date' => ['$gte' => $batch ]]],
        ['$sort'  => [  
            'download_Date' => 1
        ]],
    ['$group' => [ 
        '_id' => [ '$cw_product_id', 'batch' => ['$last' => '$download_Date'] ],
        ]],   
    ],
        'allowDiskUse' => true, 
        'cursor' => new stdClass, 
    ]);

Open in new window


The error I receive when running the php script is

           
PHP Fatal error:  Uncaught MongoDB\Driver\Exception\RuntimeException: Unrecognized expression '$last'

Open in new window

I've pulled it apart and put it back together so many times, a fresh pair of eyes is needed to spot the obvious.  

Thanks in advance,

Rick
Avatar of Eddie Shipman
Eddie Shipman
Flag of United States of America image

Try removing the quotes around $last.
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.