Tim Gobb
Tim Gobb

Reputation: 33

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!

Upvotes: 3

Views: 2328

Answers (1)

BatScream
BatScream

Reputation: 19700

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);

Upvotes: 4

Related Questions