我有一个有700万条记录的集合。我需要在特定日期范围之间选择X个随机元素。
这是我的架构
mongoose.Schema({
transactionId: {type: String, required: [true, 'transactionId is required'], index: true},
createdAt: {type: Date, required: [true, 'date is required'], index: true},
userId: {type: String, required: [true, 'userId is required']}
});
这是我正在做的查询
TransactionModel.aggregate([
{
$match: {
createdAt: {$gte: startDate, $lt: endDate}
}
},
{
$sample: {
size: 100,
}
}
]
这些是我的结果:
Took 458ms to select 100 winners in date range: 1-5-2018 - 1-6-2018
Took 1524ms to select 100 winners in date range: 1-5-2018 - 1-9-2018
Took 2052ms to select 100 winners in date range: 1-4-2018 - 1-4-2019
Took 19249ms to select 100 winners in date range: 1-1-2018 - 1-1-2033
19秒似乎相对较长,当我从聚合函数中删除$ match时,从700万条记录中挑选100名获胜者仅需142ms。
有没有办法可以通过匹配条款提高速度?
正如Anthony Winzlet已经写过的那样,你需要在createdAt字段上有一个索引。这可以是单个字段索引,也可以是复合索引,其中createdAt是第一部分。
除此之外,如果不需要文档的所有字段,您应该考虑使用$ project阶段。
理想情况下,您有复合索引,它涵盖您的查询。
你可以使用explain()来看看发生了什么:
collection.find(
{createdAt: {$gte: startDate, $lt: endDate}},
{ created: 1, otherField: 1 }
).explain('executionStats')