I am using PHP/Mongo to query a data set like the following:
{
description:
{
0:
{level: (some int 0-50)},
1:
{level: (some int 0-50)},
...
n:
{level: (some int 0-50)}
}
}
How do I write the function, in php, that will build a dynamic query that searches for a level 40 and above, using $or and based on the number of description keys (0 ... n)?
What I currently have for a manual query is not working (I have a feeling it's because in some entries description.1, 2, 3 do not exist):
find("$or":{"description.0.level":[40,41,42,43,44,45,46,47,48,49,50],"description.1.level":[40,41,42,43,44,45,46,47,48,49,50],"description.2.level":[40,41,42,43,44,45,46,47,48,49,50],"description.3.level":[40,41,42,43,44,45,46,47,48,49,50]}})
It gives me an error:
Fatal error: Uncaught exception 'MongoCursorException' with message '$and/$or/$nor must be a nonempty array'
So, I need a function that will build the query dynamically, and work :).
For those interested, here is my final code for this problem (works).
$y = 0;
$descriptionLevels = 10; // set to 'n' levels as needed ...
while($y < $descriptionLevels){
$filter['$or'][]['description.' . $y . '.level']['$in'] = range($startLevel, $endLevel);
$y++;
}
The $or
query's value itself should be an array. {$or : [...]}
Please see the standard example in the MongoDB documentation.
You will probably also want to use an operator such as $in
(or $lt
and $gt
in combination) to select which description level you are interested in, rather than enumerating each value.