【发布时间】:2017-07-23 11:45:21
【问题描述】:
我正在使用 Node.js 6.10.0 和 Mongoose 4.8.5。实际上,我正在尝试从坐标和特定日期时间中找到最近的坐标。我的 MongoDB 中有数十亿数据。我想对查询应用排序,因为我想按日期时间排序
(2017-03-02T03:00:00.000Z, 2017-03-02T03:01:00.000Z ... 2017 -03-02T03:23:00.000Z)
这是我对 Mongoose 排序的查询:
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);
});
这里很容易使用原生排序进行相同的查询:
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);
});
然后对于 Mongoose 排序,请求需要 8000 - 10000 MS。 而使用本机排序,请求只需 15 MS。
你能告诉我为什么原生排序比猫鼬排序更好吗?或者我的 Mongoose 查询做错了什么?
【问题讨论】:
-
基于时间上的巨大差异,一定是先排序再过滤,而你的查询是对较小的过滤数据集进行排序,只是猜测
-
你可以做一个测试,切换排序的顺序和限制(先排序,然后限制)如果持续时间保持不变,你知道它在排序之前限制。
标签: javascript node.js mongodb sorting mongoose