---
title: "mongoDB ruby driver性能测试与优化建议"
author: "pingfeng"
date: "2011-04-07T15:05:43Z"
tags: []
categories: ["编程语言"]
slug: "mongodb-ruby-driver"
draft: false
lastmod: "2011-04-07T15:07:01Z"
id: 990628
url: "https://pingfeng.iteye.com/blog/990628"
---

用mongo的ruby driver进行测试。

测试脚本见附件

 

测试基本结果：

 

                                                |   MONGO |  
\-----------------------------------------------------------  
find\_one,find\_first                       x1000 |   0.223 |  
find by id                                x1000 |   0.304 |  
find by index(composite index)            x1000 |   0.539 |  
find use index and other field            x1000 |   0.871 |  
find use a field in index field             x10 |  10.479 |  
find not use index(1 field)                 x10 |   6.690 |  
find not use index(2 field)                 x10 |   5.405 |  
insert 1000 doc                              x1 |   0.337 |  
update                                    x1000 |   0.079 |  
remove 1000 doc                              x1 |   0.074 |

 

结果分析：

 

1. 索引查找：复合索引比单列索引查找要慢，本次测试是三个字段复合索引。0.304 vs 0.539

 

2. 无索引查找：查找的字段越多，越慢。5.405(一个字段） vs 6.690（二个字段） vs 10（四个字段）

 

3. 用复合索引的一个字段等于没有用索引。find use a field in index field             x10 |  10.479 |

 

4. 对子文档字段查找比一般字段要慢。5.405 vs 10.479

 

优化建议：

 

1. 设计好索引很关键！避免对子文档的字段零散操作，可以专门做一个数组字段（mongo强大之处）作为索引。

 

2. 尽量避免多字段，子文档无索引查找 。当文档数超过一百万时，查找时间将达到秒级

 

3. 复合索引是个整体 ，如果要对其中一个字段做查找，要专门再建一个索引。

 

基本上mongo性能非常好（包括复合索引），在索引上要小心，很多地方可以大胆使用！