Why Mongoose sort is slower than native javascript sort?

Why Mongoose sort is slower than native javascript sort?

I’m using Node.js 6.10.0 and Mongoose 4.8.5. Actually I’m trying to find the nearest coordinates from a coordinate and with a certain datetime. I have billions data into my MongoDB. I want to apply a sort to my query because I want to order by the datetime
(2017-03-02T03:00:00.000Z, 2017-03-02T03:01:00.000Z … 2017-03-02T03:23:00.000Z)
So here is my query with Mongoose sort:
var condition = {
$nearSphere: {
$geometry: {
type : “Point”,
coordinates : [2.2871244564, 47.930476456445]
}
}
};

var date_condition = {
$gte: new Date(‘2017-03-02’),
$lt: new Date(‘2017-03-03’)
};

var selected_fields = ‘-_id loc datetime’;

console.time(‘find’)
var query = Model.find({loc: condition, datetime: date_condition}, selected_fields)
.limit(24)
.sort({date: ‘asc’})
.exec();

query.then(function(docs){
var json = {};
json.data = docs;
console.timeEnd(‘find’)
res.json(json);
});

Here easy the same query with native sort :
console.time(‘find’)
var query = Model.find({loc: condition, datetime: date_condition}, selected_fields)
.limit(24)
.exec();

query.then(function(docs){
var json = {};
docs.sort(function(a, b) {
return new Date(a.datetime) – new Date(b.datetime);
});
json.data = docs;
console.timeEnd(‘find’)
res.json(json);
});

Then with the Mongoose sort the request takes 8000 – 10000 MS.
And with the native sort the request takes just 15 MS.
Could you tell me why the native sort is better than Mongoose sort ? Or maybe I did something wrong with my Mongoose query ?

Related:  Retrieving a Subset of Fields from MongoDB in Ruby

Solutions/Answers:

Solution 1:

As @JuanMendes said in the comment, the first one does sort and then apply limit, which means MongoDB sorts all billions of documents and returns you 24 documents. In the second one, you are getting only 24 documents from MongoDB and sorting them using javascript‘s sort. So the difference is not between native javascript sorting and MongoDB sorting. The difference is between sorting 24 documents and sorting billions of documents

The order of sort and limit does not matter. MongoDB always does sort before applying limit. See this

References