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}); }); });
The limit() method in Mongoose is used to specify the number or a maximum number of documents to return from a query.
n = count( conn , collection ) returns the total number of documents in a collection by using the MongoDB® C++ interface connection. n = count( conn , collection ,Query= mongoquery ) returns the total number of documents in an executed MongoDB query on a collection.
In Mongoose, the skip() method is used to specify the number of documents to skip. When a query is made and the query result is returned, the skip() method will skip the first n documents specified and return the remaining.
The limit() function in MongoDB is used to specify the maximum number of results to be returned. Only one parameter is required for this function.to return the number of the desired result. Sometimes it is required to return a certain number of results after a certain number of documents. The skip() can do this job.
I suggest you to use 2 queries:
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With