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

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

问题描述

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

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.

我认为你不应该查询所有项目,而不是执行skip and take,因为当你有大数据时,你会在数据传输和处理方面遇到问题.

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.

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

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