从头开始,验证mongodb的索引的好处。(window7环境下)
下载mongodb服务器,并解压到d盘,并使用以下命令启动
mongod --dbpath D:mongodbdata
-
mongo客户端Robo 3T 去官网下载,安装
-
准备数据,条数为1亿
public static void main(String[] args) { ? ? ? ?try { ? ? ? ? ? ?/**** Connect to MongoDB ****/
// Since 2.10.0,uses MongoClient
MongoClient mongo = new MongoClient("localhost",27017); ? ? ? ? ? ?/**** Get database ****/
// if database doesn't exists,MongoDB will create it for you
DB db = mongo.getDB("www"); ? ? ? ? ? ?/**** Get collection / table from 'testdb' ****/
// if collection doesn't exists,MongoDB will create it for you
DBCollection table = db.getCollection("person"); ? ? ? ? ? ?/**** Insert ****/
// create a document to store key and value
BasicDBObject 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();
? ? ? ?}
? ?}
-
获取索引情况

-
根据姓名查询一条记录

-
根据姓名创建索引
创建索引的时间稍微有点长,请耐心等待
db.person.createIndex({name:1})

-
索引情况

-
再一次查询

索引说明:
索引通常能够极大的提高查询的效率,如果没有索引,MongoDB在读取数据时必须扫描集合中的每个文件并选取那些符合查询条件的记录。
这种扫描全集合的查询效率是非常低的,特别在处理大量的数据时,查询可以要花费几十秒甚至几分钟,这对网站的性能是非常致命的。
索引是特殊的数据结构,索引存储在一个易于遍历读取的数据集合中,索引是对数据库表中一列或多列的值进行排序的一种结构。
http://www.runoob.com/mongodb/mongodb-indexing.html
createIndex() 方法
MongoDB使用 createIndex() 方法来创建索引。
注意在 3.0.0 版本前创建索引方法为 db.collection.ensureIndex(),之后的版本使用了 db.collection.createIndex() 方法,ensureIndex() 还能用,但只是 createIndex() 的别名。
语法
createIndex()方法基本语法格式如下所示:
语法中 Key 值为你要创建的索引字段,1 为指定按升序创建索引,如果你想按降序来创建索引指定为 -1 即可。
实例
createIndex() 方法中你也可以设置使用多个字段创建索引(关系型数据库中称作复合索引)。
createIndex() 接收可选参数,可选参数列表如下:
Parameter
|