.count()
é muito mais rápido. Você pode ver a implementação chamando // Note the missing parentheses at the end
db.collection.count
que retorna o comprimento do cursor. da consulta padrão (se
count()
é chamado sem documento de consulta), que por sua vez é implementado como retornando o comprimento do _id_
índice, iirc. Uma agregação, no entanto, lê cada documento e o processa. Isso só pode ser meio caminho na mesma ordem de magnitude com
.count()
ao fazê-lo em apenas cerca de 100k de documentos (dar e receber de acordo com sua memória RAM). A função abaixo foi aplicada a uma coleção com cerca de 12 milhões de entradas:
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
}
E retornou:
{ "_id" : "aggregation", "average" : 43828.8 }
{ "_id" : "count", "average" : 0.6 }
A unidade é milissegundos.
hth