4

私は mongo で集計を頻繁に使用してきました。グループ化されたカウントなどでパフォーマンスが向上することはわかっています。

collection.aggregate([
  {
    $match: {}
  },{
    $group: {
      _id: null, 
      count: {$sum: 1}
    }
}]);

collection.find({}).count()

更新: 2 番目のケース: 次のサンプル データがあるとします。

{_id: 1, type: 'one', value: true}
{_id: 2, type: 'two', value: false}
{_id: 4, type: 'five', value: false}

aggregate():

var _ids = ['id1', 'id2', 'id3'];
var counted = Collections.mail.aggregate([
  {
    '$match': {
      _id: {
        '$in': _ids
      },
      value: false
    }
  }, {
    '$group': {
      _id: "$type",
      count: {
        '$sum': 1
      }
    }
  }
]);

count():

var counted = {};
var type = 'two';
for (i = 0, len = _ids.length; i < len; i++) {
  counted[_ids[i]] = Collections.mail.find({
    _id: _ids[i], value: false, type: type
  }).count();
}
4

1 に答える 1

10

.count()はるかに高速です。呼び出すことで実装を確認できます

// Note the missing parentheses at the end
db.collection.count

カーソルの長さを返します。デフォルト クエリの (count()クエリ ドキュメントなしで呼び出された場合)。これは、インデックスの長さ_id_iirc を返すように実装されています。

ただし、集約はすべてのドキュメントを読み取り、処理します。.count()これは、約 100k のドキュメント (RAM に応じてギブ アンド テイク) に対してのみ実行する場合と同じ大きさの半分にすぎません。

以下の関数は、12M のエントリを持つコレクションに適用されました。

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
}

そして返されました:

{ "_id" : "aggregation", "average" : 43828.8 }
{ "_id" : "count", "average" : 0.6 }

単位はミリ秒です。

h番目

于 2015-10-17T13:03:55.010 に答える