我在Mongo 2.4.4中有一个match-unwind-group-sort
聚合管道,需要加快聚合速度。
匹配操作涉及对16个字段的范围查询。我已经使用.explain()
方法优化了范围查询 (即创建复合索引)。是否有类似于优化聚合的功能?我正在寻找像这样的东西:
db.col.aggregate([]).explain()
另外,我是否应该专注于索引优化?
我在Mongo 2.4.4中有一个match-unwind-group-sort
聚合管道,需要加快聚合速度。
匹配操作涉及对16个字段的范围查询。我已经使用.explain()
方法优化了范围查询 (即创建复合索引)。是否有类似于优化聚合的功能?我正在寻找像这样的东西:
db.col.aggregate([]).explain()
另外,我是否应该专注于索引优化?
关于第一个问题,是的,你可以解释聚合。
db.collection.runCommand("aggregate", {pipeline: YOUR_PIPELINE, explain: true})
对于第二个问题,你创建的用于优化范围查询的索引也会应用于聚合管道的$match阶段,如果它们出现在管道的开头。因此,你确实需要专注于索引优化。
请参见Pipeline Operators and Indexes。
更新2
更多关于aggregate和explain的信息:在版本2.4上不可靠;在2.6+上它不提供查询执行数据。https://groups.google.com/forum/#!topic/mongodb-user/2LzAkyaNqe0
更新1
MongoDB 2.4.5上聚合解释的记录。
$ mongo so
MongoDB shell version: 2.4.5
connecting to: so
> db.q19329239.runCommand("aggregate", {pipeline: [{$group: {_id: '$user.id', hits: {$sum: 1}}}, {$match: {hits: {$gt: 10}}}], explain: true})
{
"serverPipeline" : [
{
"query" : {
},
"projection" : {
"user.id" : 1,
"_id" : 0
},
"cursor" : {
"cursor" : "BasicCursor",
"isMultiKey" : false,
"n" : 1031,
"nscannedObjects" : 1031,
"nscanned" : 1031,
"nscannedObjectsAllPlans" : 1031,
"nscannedAllPlans" : 1031,
"scanAndOrder" : false,
"indexOnly" : false,
"nYields" : 0,
"nChunkSkips" : 0,
"millis" : 0,
"indexBounds" : {
},
"allPlans" : [
{
"cursor" : "BasicCursor",
"n" : 1031,
"nscannedObjects" : 1031,
"nscanned" : 1031,
"indexBounds" : {
}
}
],
"server" : "ficrm-rafa.local:27017"
}
},
{
"$group" : {
"_id" : "$user.id",
"hits" : {
"$sum" : {
"$const" : 1
}
}
}
},
{
"$match" : {
"hits" : {
"$gt" : 10
}
}
}
],
"ok" : 1
}
服务器版本。
$ mongo so
MongoDB shell version: 2.4.5
connecting to: so
> db.version()
2.4.5