对于第一个问题,是的,您可以解释聚合。
db.collection.runCommand("aggregate", {pipeline: YOUR_PIPELINE, explain: true})
对于第二个,您为优化范围查询而创建的索引也将应用于聚合管道的 $match 阶段,如果它们发生在管道的开头。所以你专注于索引优化是对的。
见Pipeline Operators and Indexes。
更新 2
关于聚合和解释的更多信息:在 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