In the process of learning to use Mongo and PHP, and got stuck with this.
I have a collection in Mongo with the following structure:
array(3){
["timehack"]=>int(..),
["_id"]=>object..,
["series"]=>
array(3){
[0]=>int(..),
[1]=>int(..),
[2]=>int(..)
}
}
I am trying to query the collection so i get all of the samples with first item in “series”, something like:
$cursor = $collection->find();
$cursor->fields(array=>("timehack"=>true, "_id"=>false, "series.0"=>true));
$arr = $cursor->getNext();
var_dump($arr);
The resulting series array is empty. How can I get just the desired index? (I realize that I can get all samples in the series then filter with code, but I would like to know how to accomplish this with a query). Thanks.
In the comments above you have already confirmed that this works with the $slice operator in the shell. So, to give you an example of how $slice works in PHP, I refer you to none other than the PHP tests in the driver itself.
Take a look at line 33 in the tests/MongoCollectionTest2.php file on github:
https://github.com/mongodb/mongo-php-driver/blob/master/tests/MongoCollectionTest2.php
The code goes like this:
It looks a little convoluted compared to the shell with a lot of casting as an object going on (if I am reading that right), but hopefully enough to get you started 🙂