Take inner array of mongo document using with limit and skip in php.
$db->users->findOne(array('_id' => new MongoId('5045fa0213cfcdfc06000008')));
Above query will give me below mongo array
[_id] => MongoId Object (
[$id] => 5045fa0213cfcdfc06000008
)
[items] => Array (
[0] => 13
[1] => 4
[2] => 3
[3] => 7
[4] => 10
[5] => 11
[6] => 28
[7] => 54
[8] => 31
[9] => 33
[10] => 37
[11] => 12
)
Is it possible to make use of limit with skip with above mongo doc, something like below
$db->users->
findOne(array('_id' => new MongoId('5045fa0213cfcdfc06000008')))->
limit(5)->skip(5);
Which will output as
[_id] => MongoId Object (
[$id] => 5045fa0213cfcdfc06000008
)
[items] => Array (
[5] => 11
[6] => 28
[7] => 54
[8] => 31
[9] => 33
)
And how to take total count of items array using mongo?
The
limit()andskip()methods only apply at the document level, not the array level.You can use the
$sliceoperator to fetch a subset of an array:There currently (as at MongoDB 2.2.0) isn’t a straightforward way to determine the size of the array without fetching it. You could do some manipulation using the new Aggregation Framework but that’s perhaps overkill.
A common usage pattern is to use
$incto adjust a counter in a document in the same update when items are added or removed from an array.Here is a quick example using the Aggregation Framework in the
mongoshell: