MongoDB では、興味深いパフォーマンス情報とともに、クエリがどのように実行されたかについての説明を得ることができます。
> db.people.find({ 'items' : { '$gte' : 1 } }).explain()
「カウント」(クエリではなくコマンド)でも同じことはできますか?
> db.people.count({ 'items' : { '$gte' : 1 } })
MongoDB では、興味深いパフォーマンス情報とともに、クエリがどのように実行されたかについての説明を得ることができます。
> db.people.find({ 'items' : { '$gte' : 1 } }).explain()
「カウント」(クエリではなくコマンド)でも同じことはできますか?
> db.people.count({ 'items' : { '$gte' : 1 } })
https://jira.mongodb.org/browse/SERVER-14098に基づいて、新しい将来のバージョンは次の形式でこれをサポートします。
db.runCommand({
explain: {
count: 'collectionName',
query: {
foo: 'bar'
}
}
})
count(query)はfind(query).count()の略であると確信しています。つまり、explainはまったく同じです。完全なコレクションカウントを除いて、特定のカウントの最適化は行われません。たとえば、ある範囲のインデックス付けされていないフィールドでカウントを実行すると、同じ範囲でfind.explainを実行するのとまったく同じ時間がかかります。
count関数の時間の平均を取り、比較のためにexplain出力を表示するtimeCountという関数を作成しました。
function timeCount(coll, query) {
var n = 5;
var total = 0;
for(var i = 0; i < n; i++) {
var start = new Date();
db[coll].find(query).count();
var end = new Date();
total += (end - start);
print("time[" + i + "]: " + (end - start) + "ms");
}
print("average time: " + (total / n));
var explain = db[coll].find(query).explain();
print("explain (from find): ");
for(e in explain) {
if(typeof explain[e] == "string" || typeof explain[e] == "number") {
print(e + ": " + explain[e]);
}
}
}
出力は次のようになります。
> timeCount('test',{x:{$gt:5000}});
time[0]: 1339ms
time[1]: 1280ms
time[2]: 1347ms
time[3]: 1322ms
time[4]: 1299ms
average time: 1317.4
explain (from find):
cursor: BtreeCursor x_1_y_1
nscanned: 995062
nscannedObjects: 995062
n: 995062
millis: 1390
nYields: 0
nChunkSkips: 0