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

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

问题描述

假设我在 mongo 数据库中有一个 People 集合:

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/2API 应返回此数组:

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?

推荐答案

对于你的问题,你需要 $slice 投影运算符而不是 limit.后者限制了作为查询结果返回的文档 的数量.相反,$slice 运算符旨在满足您的需求.

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天全站免登陆