问题描述
假设我在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/2
the 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"
]
}
这篇关于分页存储在文档字段中的数组上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!