Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pagination on array stored in a document field

Let's say I've got a collection People in mongo database:

[{
    id: 1,
    name: "Tom",
    animals: ["cat", "dog", "fish", "bear"]
},
{
    id: 2,
    name: "Rob",
    animals: ["shark", "snake", "fish", "bear", "panda"]
},
{
    id: 3,
    name: "Matt",
    animals: ["cat", "fish", "bear"]
}]

For the purpose of REST API I need to create a pagination system for viewing people's animals and return only 3 per request. So for example if you go to /people/2the API should return this array:

["shark", "snake", "fish"]

I'm trying to get this result using Mongo methods. Here's my attempt:

db.getCollection('people').find({id: 2}, {animals: 1, _id:0}, {limit: 3})

Unfortunatelly it doesn't work like that and returns the whole object. Can anybody tell me how to do it?

like image 927
zorza Avatar asked Aug 03 '15 16:08

zorza


1 Answers

For you problem you need the $slice projection operator instead of limit. The later limits the number of documents returned as a result of the query. Instead, the $slice operator is intended for exactly what you need.

Here is an example how to use it in your use case:

> db.getCollection('people').find({id: 2}, {_id: 0, animals: {$slice: [0, 3]}})
{
    "id" : 2,
    "name" : "Rob",
    "animals" : [
        "shark",
        "snake",
        "fish"
    ]
}
like image 77
bagrat Avatar answered Sep 21 '22 14:09

bagrat