【问题标题】:Mongodb query use skip and limit function in first N documentsMongodb查询在前N个文档中使用skip和limit函数
【发布时间】:2019-10-11 18:38:22
【问题描述】:

我们能否进行查询,使我们能够在前 N 个文档中使用跳过和限制?

例如:

假设在一个名为教师的集合中有近 500 个文档。

我想要一个限制我只能阅读前 300 个文档的查询。

如果我在该查询中使用 skip(300),它应该显示 null。

db.teachers.find().pretty()

{
  id : 1,
  name : "teach001"
},
{
  id : 2,
  name : "teach002"
},
{
  id : 3,
  name : "teach003"
},
{
  id : 4,
  name : "teach004"
},
{
  id : 5,
  name : "teach005"
},
{
  id : 6,
  name : "teach006"
},
{
  id : 7,
  name : "teach007"
},
{
  id : 8,
  name : "teach008"
},
{
  id : 9,
  name : "teach009"
},
{
  id : 10,
  name : "teach0010"
}



 db.teachers.find({some query here to restrict access first 5 documents only }).skip(5).limit(5).pretty()

【问题讨论】:

  • 请通过一些示例数据和查询为您的问题添加更多详细信息。
  • 我认为您需要在代码中预处理查询的跳过和限制参数以强制执行您想要的任何规则。

标签: mongodb mongodb-query


【解决方案1】:

聚合

我认为没有办法完全按照您的要求进行操作。如果您愿意使用aggregation framework,则可以轻松完成。

db.teachers.aggregate([{$limit: 5}, {$skip: 5}])

查看

如果您愿意创建view,您甚至可以创建一个强制执行限制的视图

db.createView('limitedTeachers', 'teachers', [{$limit: 5}])

然后你可以在视图上使用find:

db.limitedTeachers.find({}).skip(5)

两个发现

如果您不能使用聚合,您可以选择在查询中使用 2 个查找。首先,找到 n 个对象 ID。然后,将您的第二个查询限制为仅这些对象 ID。

var ids = [];
db.teachers.find({}, {_id: 1}).limit(5).forEach(function(doc){
    ids.push(doc._id);
});

db.teachers.find({ _id: {$in: ids} }).skip(5)

或者作为相同类型的查询,但更接近您在问题中的格式

db.teachers.find({$or: db.teachers.find({}, {_id: 1}).limit(5).toArray()}).skip(5)

【讨论】:

    猜你喜欢
    • 2012-06-19
    • 2019-10-22
    • 2015-07-29
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    • 2014-09-06
    • 2018-08-18
    • 1970-01-01
    相关资源
    最近更新 更多