如何提高MongoDB查询的速度?

时间:2012-08-23 06:44:53

标签: performance mongodb mapreduce

MongoDB 2.0.7& PHP 5

我正在尝试计算每个数组的长度。每个文档都有一个数组。我想获得每个数组中的元素数量和文档的ID。除Id之外没有索引。

这是我的代码:

$map = new MongoCode("function() {
    emit(this._id,{
    '_id':this._id,'cd':this.cd,'msgCount':this.cs[0].msgs.length}
    );
}");

$reduce = new MongoCode("function(k, vals) {
    return vals[0];
}");

$cmmd = smongo::$db->command(array(
    "mapreduce" => "sessions",
    "map" => $map,
    "reduce" => $reduce,
    "out" => "result"));

这些是时间安排。如您所见,查询非常慢

Array
(
[result] => result
[timeMillis] => 29452
[counts] => Array
(
[input] => 106026
[emit] => 106026
[reduce] => 0
[output] => 106026
)
[ok] => 1
)

如何减少时间?

1 个答案:

答案 0 :(得分:4)

如果您经常需要数组的计数,更好的方法是在实际文档中包含count字段。否则,您将扫描所有文档以进行计数(根据您的Map / Reduce示例)。

您可以使用诸如Atomic Operation之类的$inc在更新阵列的同时递增/递减此计数。

相关问题