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?
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.