Reputation: 1013
I have an api with one optional parameter called limit, which takes an integer and limits the number of documents returned from the api in a get request.
Implementing this limit is fine in my PHP application when it is a required parameter, but when its not specified as part of my get request, what is the best way to handle it?
is there for example, a way to define $limit and set it to all documents? (in pseudo code, $limit = none)
$list = $collection->aggregate( array( array('$match' => array( ... )),
'$project' => array ( ... )), '$limit' => intval($this->limit) ));
$this->limit //this is the optional input parameter
As you can see above, when the limit parameter is required it functions as required. Now when its ommitted, how can I keep the above code but specify no limit?
Upvotes: 4
Views: 1674
Reputation: 14941
You could manually generate your where clause.
// Declare a where clause with your fixed conditions
$whereClause = array(array('$match' => array(...)), array('$project' => array(...)));
// Check if there's a limit
if($this->limit != 0)
array_push($whereClause, array('$limit' => $this->limit));
// Finally, call with the where clause we've generated above
$list = $collection->aggregate($whereClause);
Upvotes: 2
Reputation: 61243
Short answer No!
But, you can use an if/else condition like this:
<?php
if(intval($this->limit) != 0 ) {
$list = $collection->aggregate( array(
array('$match' => array( ... )),
array('$project' => array ( ... ))
array('$limit' => intval($this->limit))
);
));
} else {
$list = $collection->aggregate( array(
array('$match' => array( ... )),
array('$project' => array ( ... )),
);
}
?>
Upvotes: 1