I think you could optimize the query by returning less documents from MongoDB.
Let’s imagine you have 100 docs in MDB. You are returning 100 docs and then you are slicing the results to only returns docs 50 to 60 (arg1 & 2).
I would add a .skip(arg1).limit(arg2-arg1) to avoid returning 10 times 100 docs and only return 10 each time.
Example:
exports = function(arg){
const collection = context.services.get("mongodb-atlas").db("test").collection("messages");
collection.find({}, {_id:1}).skip(5).limit(10).toArray().then((docs) => {
console.log(docs.length);
console.log(EJSON.stringify(docs));
});
};
Cheers,
Maxime.