Reputation: 625
I'm a novice-intermediate PHP developer and am starting to work with MongoDB. I would like to create a Mongo query class that builds a query based on the arguments passed into the method. I hope this is possible and I am just missing some fundamental PHP technique.
I started with a static find function:
$dateRange = $this->collection->find(array(
'timeStamp' => array(
'$gt' => $startTime,
'$lt' => $endTime
),
'userAgent' => array(
'$ne' => 'ELB-HealthChecker/1.0'
)
));
I would like to be able to pass a time range, userAgent, urgency level, etc. into the method and then build the query based on whether those arguments exist. I tried something like this:
if($startTime && $endTime){
$filter = "
'timeStamp' => array(
'$gt' => $start,
'$lt' => $end
)";
}
if($userAgent){
$filter .= ",
'userAgent' => array(
'$ne' => 'ELB-HealthChecker/1.0'
)";
$dateRange = $this->collection->find(array($filter);
Didn't work. So, what am I doing wrong?
Upvotes: 0
Views: 848
Reputation: 46
Looks like you are trying to use a string, where you should just use an array.
$qry = array();
if(isset($startTime) && isset($endTime)) {
// Add the timestamp array
$qry['timestamp'] = array('$gt' => $startTime, '$lt' => $endTime);
}
if(isset($userAgent)) {
// add the userAgent
$qry['userAgent'] = array('$ne' => 'ELB-HealthChecker/1.0');
}
$dateRange = $this->collection->find($qry);
Upvotes: 3
Reputation: 640
Have you tried if(isset($startTime) && isset($endTime))
? It also seems that you might need a couple of else
statements in there too.
Upvotes: 0