加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MySql教程 > 正文

createIndex() 方法

发布时间:2020-12-11 23:56:39 所属栏目:MySql教程 来源:网络整理
导读:从头开始,验证mongodb的索引的好处。(window7环境下) 下载mongodb服务器,并解压到d盘,并使用以下命令启动 mongod --dbpath D:mongodbdata mongo客户端Robo 3T 去官网下载,安装 准备数据,条数为1亿 public static void main(String[] args) { ? ? ? ?t
。...实例

在后台创建索引:

通过在创建索引时加 background:true 的选项,让创建工作在后台执行

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

从头开始,验证mongodb的索引的好处。(window7环境下)

    下载mongodb服务器,并解压到d盘,并使用以下命令启动

    mongod --dbpath D:mongodbdata

  1. mongo客户端Robo 3T 去官网下载,安装

  2. 准备数据,条数为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();
    ? ? ? ?}

    ? ?}

  3. 获取索引情况

  4. 根据姓名查询一条记录

  5. 根据姓名创建索引

    创建索引的时间稍微有点长,请耐心等待

    db.person.createIndex({name:1})

  6. 索引情况

  7. 再一次查询

索引说明:

索引通常能够极大的提高查询的效率,如果没有索引,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
Type Description
    推荐文章
      热点阅读