.count()
je daleko rychlejší. Implementaci můžete vidět zavoláním
// Note the missing parentheses at the end
db.collection.count
který vrátí délku kurzoru. výchozího dotazu (pokud count()
je voláno bez dokumentu dotazu), který je zase implementován jako vracení délky _id_
index, iirc.
Agregace však čte každý dokument a zpracovává jej. To může být pouze poloviční ve stejném řádu s .count()
když to děláte přes jen nějakých 100k dokumentů (dávejte a berte podle vaší RAM).
Níže uvedená funkce byla použita na kolekci s přibližně 12 miliony záznamů:
function checkSpeed(col,iterations){
// Get the collection
var collectionUnderTest = db[col];
// The collection we are writing our stats to
var stats = db[col+'STATS']
// remove old stats
stats.remove({})
// Prevent allocation in loop
var start = new Date().getTime()
var duration = new Date().getTime()
print("Counting with count()")
for (var i = 1; i <= iterations; i++){
start = new Date().getTime();
var result = collectionUnderTest.count()
duration = new Date().getTime() - start
stats.insert({"type":"count","pass":i,"duration":duration,"count":result})
}
print("Counting with aggregation")
for(var j = 1; j <= iterations; j++){
start = new Date().getTime()
var doc = collectionUnderTest.aggregate([{ $group:{_id: null, count:{ $sum: 1 } } }])
duration = new Date().getTime() - start
stats.insert({"type":"aggregation", "pass":j, "duration": duration,"count":doc.count})
}
var averages = stats.aggregate([
{$group:{_id:"$type","average":{"$avg":"$duration"}}}
])
return averages
}
A vrátil se:
{ "_id" : "aggregation", "average" : 43828.8 }
{ "_id" : "count", "average" : 0.6 }
Jednotkou jsou milisekundy.
hth