This is my first question here, so please give me hints on bettering my question formulation, etc. I have already tried searching everywhere online, and I think the answer is out there, but my biggest problem is, I have no idea what words to use to search for this issue.
Now to the problem: I am currently using: https://github.com/sokil/php-mongo To create a searcher that is supposed to be searching through a list of key/values in a mongodb database collection.
My current code looks like this (Yes, way to many arguments, etc. I know, but I am creating a drop in replacement of a legacy function that is just too slow):
public function searchTasks(
int $start = 1,
int $end = 25,
string $type = null,
string $taskID = null,
string $siteID = null,
string $subject = null,
....... //Many more arguments following, but unused so far.
): \sokil\mongo\Cursor
{
return $this->collection
->find()
->where('siteID', $siteID)
->where('subject', $subject)
->whereGreaterOrEqual('status', 0);
}
The problem is, I would like to only add "where" clauses, whenever an argument is not null, so something like:
public function searchTasks(
int $start = 1,
int $end = 25,
string $type = null,
string $taskID = null,
string $siteID = null,
string $subject = null,
....... //Many more arguments following, but unused so far.
): \sokil\mongo\Cursor
{
$arguments = []
if($type != null) {
array_push($arguments, ["type" => $type]);
}
return $this->collection
->find()
->where($arguments)
->whereGreaterOrEqual('status', 0);
}
But according to the documentation, this is not possible, and I have found no way to simply add wildcards like this:
public function searchTasks(
int $start = 1,
int $end = 25,
string $type = "*",
string $taskID = "*",
string $siteID = "*",
string $subject = "*",
....... //Many more arguments following, but unused so far.
): \sokil\mongo\Cursor
{
return $this->collection
->find()
->where('siteID', $siteID)
->where('subject', $subject)
->whereGreaterOrEqual('status', 0);
}
If you have any way of helping me out with searchwords for what this is called, etc. I will appreciate it a lot. All the best Toby
Your code doesn't seem to fetch (execute) the query you are building. You can add the where
clauses before executing. Try this:
$query = $this->collection->find();
if ($siteID !== null) {
$query->where('siteID', $siteID);
}
return $query;
You then later call findAll()
outside of your function.