Question

After executing the query

$orders = Orders::connection()->connection->command(array(
  'aggregate' => 'orders',
  'pipeline' => array( 
    array( 
      '$group' => array( 
        '_id' => array('cust_id'=>'$cust_id','ord_date'=>'$ord_date'),
      'total' => array( '$sum' => '$price') ,
        ),
      ),
    )
));     

I get the output array of $orders as

Array
(
    [0] => Array
        (
            [_id] => Array
                (
                    [cust_id] => xyz123
                    [ord_date] => MongoDate Object
                        (
                            [sec] => 1351875851
                            [usec] => 102000
                        )

                )

            [total] => 75
        )

    [1] => Array
        (
            [_id] => Array
                (
                    [cust_id] => abc123
                    [ord_date] => MongoDate Object
                        (
                            [sec] => 1351875851
                            [usec] => 102000
                        )

                )

            [total] => 125
        )

)

I have tried the following with MongoDate object to print it correctly

foreach($orders['result'] as $o){
    $date = $o['ord_date'];
    echo date('Y-M-d',$date->sec);
}

Also tried

foreach($orders['result'] as $o){
    $date = new MongoDate ($o['ord_date']);
    echo date('Y-M-d',$date->sec);
}

Can some one show me the correct method to do so?

Was it helpful?

Solution

You're missing the _id level of your object. Try this instead:

foreach($orders['result'] as $o){
    $date = $o['_id']['ord_date'];
    echo date('Y-M-d',$date->sec);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top