MongoDB $subtract in $redact throwing 'object is already an operator expression' Error

101 views
Skip to first unread message

BlackMage

unread,
May 5, 2016, 9:22:14 AM5/5/16
to mongodb-user

I am having a weird error when I try run an aggreate query with subtract.  Then language is PHP.


With the query below:

$ops = array(

        array(
            '$redact' => array(
                '$cond' => array(
                    'if' => array( 
                        '$gte' => array('$subtract' => array(20 ,10), 10)
                    ),
                    'then' => '$$KEEP',
                    'else' => '$$PRUNE'
                )
            )
        )
    );
$results = $collection ->aggregate($ops);



Logically, this should subtract 20 - 10, and the compare if the result is greater or equal to 10. The problem is it throws this error:

MongoResultException: localhost:27017: this object is already an operator expression, and can't be used as a document expression (at '0')

Now when I remove the $subtract and I run this:


$ops = array(
                array(
                    '$redact' => array(
                        '$cond' => array(
                            'if' => array( 
                                '$gte' => array(10,10)
                            ),
                            'then' => '$$KEEP',
                            'else' => '$$PRUNE'
                        )
                    )
                )
            );


This  compares if 10 is greater than 10, which works without the error. So why is the $subtract causing the above error message?

Wan Bachtiar

unread,
May 10, 2016, 12:29:51 AM5/10/16
to mongodb-user

MongoResultException: localhost:27017: this object is already an operator expression, and can’t be used as a document expression (at ‘0’)

Hi,

The error message is due to a missing extra array wrap before $subtract. This is because $subtract itself is document. For example via the mongo shell:

"$gte":[ { '$subtract':[20,10] }, 10]},

Or, as your example PHP code, it should be :

$query = array(
           
array('$redact' =>
             array('$cond' => 
               array("if" => 
                 array('$gte' => 
                   array
(
                     array('$subtract' => 
                       array(20, 10)),
                       10

                     )
                   ),
                 "then" => '$$KEEP',
                 "else" => '$$PRUNE'
               )
             )
           )
         );

$results = $collection->aggregate($query);

Best regards,

Wan.

Reply all
Reply to author
Forward
0 new messages