Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Mongo Aggregation $cond if / then syntax

I have a $project working as a normal MongoDB query, but am having a hard time figuring out how to write it for the PHP-Mongo driver. Here's what I've got:

db.collection.aggregate(
   {
      $project:
            {
            projectField: {
                $cond: {
                    if: { $eq: [ "$field", "-" ] }, 
                    then: "$otherfield", else: "Blah" }
                 }

            }
      }

)

My specific issue is how to deal w/ the "if" and "then" using PHP syntax. I've googled, but am new to MongoDB and the PHP driver and am not sure if I'm even googling for the right terms.

Thanks!

like image 415
Tim Gobb Avatar asked Jul 12 '26 03:07

Tim Gobb


1 Answers

You could use the simplified syntax for the $cond expression:

{ $cond: [ <boolean-expression>, <true-case>, <false-case> ] }

So the statements can be broken down and substituted as below:

$if => array('$eq' => array('$field','-'))

$cond => array($if,'$otherfield','Blah')

$projectField => array('$cond' => $cond)

$pipeline => array('$project' => array('projectField' => $projectField))

$out = $c->aggregate($pipeline);
like image 84
BatScream Avatar answered Jul 14 '26 18:07

BatScream



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!