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.
So, I have 57 documents in total, and the user wants 10 documents offset by 20.
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?
Edit:
// 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});
});
});
count()
function in PHP does not takelimit
orskip
into account unless told to so just running one query of limit and skip and then getting the count should give the most performant solution here probably. However how will you kow there are 57 documents if you don't do two queries to count what is currently there? Do you have a static number that never changes? If not then you will need to do both the skip and limit then the count. – Sammayedb.collection.find(<query>).count();
– leepowellcount()
function of MongoDB. Thecount()
function in MongoDB is relatively slow but it is still pretty much as fast as most client side variations on larger sets and it could be faster than client side counting here possibly. But that part is subjective to your own testing. Mind you I have counted 10k length arrays easily before so it might be faster client side, it is very hard to say at 10k elements. – Sammaye