猫鼬限制/偏移量和计数查询 [英] Mongoose limit/offset and count query

查看:82
本文介绍了猫鼬限制/偏移量和计数查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查询性能有点奇怪...我需要运行一个查询,该查询可以计算文档总数,并且还可以返回可以限制和偏移的结果集.

Bit of an odd one on query performance... I need to run a query which does a total count of documents, and can also return a result set that can be limited and offset.

因此,我总共有57个文档,而用户希望将10个文档偏移20.

So, I have 57 documents in total, and the user wants 10 documents offset by 20.

我可以想到两种方法,首先是查询所有57个文档(作为数组返回),然后使用array.slice返回所需的文档.第二种选择是运行2个查询,第一个查询使用mongo的本机"count"方法,然后使用mongo的本机$ limit和$ skip聚合器运行第二个查询.

I can think of 2 ways of doing this, first is query for all 57 documents (returned as an array), then using array.slice return the documents they want. The second option is to run 2 queries, the first one using mongo's native 'count' method, then run a second query using mongo's native $limit and $skip aggregators.

您认为哪种扩展性更好?在一个查询中完成所有操作,还是运行两个单独的查询?

Which do you think would scale better? Doing it all in one query, or running two separate ones?

// 1 query
var limit = 10;
var offset = 20;

Animals.find({}, function (err, animals) {
    if (err) {
        return next(err);
    }

    res.send({count: animals.length, animals: animals.slice(offset, limit + offset)});
});


// 2 queries
Animals.find({}, {limit:10, skip:20} function (err, animals) {            
    if (err) {
        return next(err);
    }

    Animals.count({}, function (err, count) {
        if (err) {
            return next(err);
        }

        res.send({count: count, animals: animals});
    });
});

推荐答案

我建议您使用2个查询:

I suggest you to use 2 queries:

  1. db.collection.count()将返回项目总数.此值存储在Mongo中的某个位置,并且不会计算.

  1. db.collection.count() will return total number of items. This value is stored somewhere in Mongo and it is not calculated.

db.collection.find().skip(20).limit(10)在这里,我假设您可以使用按某些字段排序,所以请不要忘记在该字段上添加索引.此查询也将很快.

db.collection.find().skip(20).limit(10) here I assume you could use a sort by some field, so do not forget to add an index on this field. This query will be fast too.

我认为您不应该查询所有项目,而应该执行跳过和获取,因为稍后当您拥有大数据时,您将在数据传输和处理方面遇到问题.

I think that you shouldn't query all items and than perform skip and take, cause later when you have big data you will have problems with data transferring and processing.

这篇关于猫鼬限制/偏移量和计数查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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