从头开始,验证mongodb的索引的好处。(window7环境下)
- 下载mongodb服务器,并解压到d盘,并使用以下命令启动 mongod --dbpath D:\mongodb\data
- mongo客户端Robo 3T 去官网下载,安装
- 准备数据,条数为1亿
public static void main(String[] args) { try { /**** Connect to MongoDB ****/// Since 2.10.0, uses MongoClientMongoClient mongo = new MongoClient("localhost", 27017); /**** Get database ****/// if database doesn't exists, MongoDB will create it for youDB db = mongo.getDB("www"); /**** Get collection / table from 'testdb' ****/// if collection doesn't exists, MongoDB will create it for youDBCollection table = db.getCollection("person"); /**** Insert ****/// create a document to store key and valueBasicDBObject document=null; for(int i=0;i<100000000;i++) {document = new BasicDBObject();document.put("name", "mkyong"+i);document.put("age", 30);document.put("sex", "f");table.insert(document);} /**** Done ****/System.out.println("Done");} catch (UnknownHostException e) {e.printStackTrace();} catch (MongoException e) {e.printStackTrace();}}
复制代码
- 获取索引情况
- 根据姓名查询一条记录6.
- 根据姓名创建索引
创建索引的时间稍微有点长,请耐心等待
db.person.createIndex({name:1})
索引说明:
索引通常能够极大的提高查询的效率,如果没有索引,MongoDB在读取数据时必须扫描集合中的每个文件并选取那些符合查询条件的记录。
这种扫描全集合的查询效率是非常低的,特别在处理大量的数据时,查询可以要花费几十秒甚至几分钟,这对网站的性能是非常致命的。
索引是特殊的数据结构,索引存储在一个易于遍历读取的数据集合中,索引是对数据库表中一列或多列的值进行排序的一种结构。