分页存储在文档字段中的数组上 [英] Pagination on array stored in a document field

查看:80
本文介绍了分页存储在文档字段中的数组上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在mongo数据库中收集了一个人:

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"]
}]

出于REST API的目的,我需要创建一个用于查看人畜的分页系统,并且每个请求仅返回3个.因此,例如,如果您转到/people/2,则API应该返回以下数组:

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"]

我正在尝试使用Mongo方法获得此结果.这是我的尝试:

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?

推荐答案

对于您的问题,您需要

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"
    ]
}

这篇关于分页存储在文档字段中的数组上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆