我们可以进行查询以使我们能够在前N个文档中使用跳过和限制吗?
Ex:
假设在称为教师的集合中有近500个文档。
我想要一个查询,使我只能读取前300个文档。
如果我在该查询中使用skip(300),它应该显示为空。
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()
答案 0 :(得分:0)
我认为没有一种方法可以完全满足您的要求。如果您愿意使用aggregation framework,则可以轻松完成。
db.teachers.aggregate([{$limit: 5}, {$skip: 5}])
如果您愿意创建view,甚至可以创建强制执行限制的视图
db.createView('limitedTeachers', 'teachers', [{$limit: 5}])
然后您可以在视图上使用查找:
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)