我正在练习如何使用MongoDB聚合,但它们似乎要花费很长时间(运行时间)。
问题似乎在我使用$group
时发生。其他所有查询都可以正常运行。
我有一些1.3
个虚拟文档,需要执行两个基本操作:获取IP地址的count和unique IP地址。
我的模式看起来像这样:
{
"_id":"5da51af103eb566faee6b8b4",
"ip_address":"...",
"country":"CL",
"browser":{
"user_agent":...",
}
}
运行基本的$group
查询平均需要大约12
秒,这太慢了。
我做了一些研究,有人建议在ip_addresses
上创建一个index。这似乎已经减慢了速度,因为查询现在需要13-15
秒。
我使用MongoDB,而我正在运行的query看起来像这样:
visitorsModel.aggregate([
{
'$group': {
'_id': '$ip_address',
'count': {
'$sum': 1
}
}
}
]).allowDiskUse(true)
.exec(function (err, docs) {
if (err) throw err;
return res.send({
uniqueCount: docs.length
})
})
感谢您的任何帮助。
Edit:我忘了提,有人建议这可能是硬件问题?如果有帮助,我正在核心i5、8GB RAM笔记本电脑上运行查询。
Edit 2:查询计划:
{
"stages" : [
{
"$cursor" : {
"query" : {
},
"fields" : {
"ip_address" : 1,
"_id" : 0
},
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "metrics.visitors",
"indexFilterSet" : false,
"parsedQuery" : {
},
"winningPlan" : {
"stage" : "COLLSCAN",
"direction" : "forward"
},
"rejectedPlans" : [ ]
},
"executionStats" : {
"executionSuccess" : true,
"nReturned" : 1387324,
"executionTimeMillis" : 7671,
"totalKeysExamined" : 0,
"totalDocsExamined" : 1387324,
"executionStages" : {
"stage" : "COLLSCAN",
"nReturned" : 1387324,
"executionTimeMillisEstimate" : 9,
"works" : 1387326,
"advanced" : 1387324,
"needTime" : 1,
"needYield" : 0,
"saveState" : 10930,
"restoreState" : 10930,
"isEOF" : 1,
"invalidates" : 0,
"direction" : "forward",
"docsExamined" : 1387324
}
}
}
},
{
"$group" : {
"_id" : "$ip_address",
"count" : {
"$sum" : {
"$const" : 1
}
}
}
}
],
"ok" : 1
}
您可以创建索引
db.collectionname.createIndex( { ip_address: "text" } )
尝试一下,它更快。我认为它将为您提供帮助。