給MongoDB添加索引

來源:互聯網
上載者:User

標籤:索引   資訊   例子   find   exe   聯合   key   log   建立索引   

用過資料庫的都知道,資料庫索引與書籍的索引類似,都是用來協助快速尋找的。 MongoDB的索引跟關係型資料庫的索引幾乎一致。   1. 索引的建立 mongodb採用ensureIndex來建立索引,如: db.user.ensureIndex({"name":1}) 表示在user集合的name鍵建立一個索引,這裡的1表示索引建立的方向,可以取值為1和-1 在這裡面,我們沒有給索引取名字,mongodb會為我們取一個預設的名字,規則為keyname1_dir1_keyname2_dir2...keynameN_dirN keyname表示鍵名,dir表示索引的方向,例如,上面的例子我們建立的索引名字就是name_1   索引還可以建立在多個鍵上,也就是聯合索引,如: > db.user.ensureIndex({"name":1,"age":1}) 這樣就建立了name和age的聯合索引   除了讓mongodb預設索引的名字外,我們還可以去一個方便記的名字,方法就是為ensureIndex指定name的值,如: > db.user.ensureIndex({"name":1},{"name":"IX_name"}) 這樣,我們建立的索引的名字就叫IX_name了   2. 唯一索引 與RDB類似,我們也可以定義唯一索引,方法就是指定unique鍵位true: >db.user.ensureIndex({"name":1},{"unique":true})   3.查看我們建立的索引 索引的資訊存在每個資料庫的system.indexes集合裡面,對這個集合只能有ensureIndex和dropIndexes進行修改,不能手動插入或修改集合。 通過> db.system.indexes.find()可以找到資料庫中多有的索引: > db.system.indexes.find() { "v" : 1, "key" : { "_id" : 1 }, "ns" : "test.entities", "name" : "_id_" } { "v" : 1, "key" : { "_id" : 1 }, "ns" : "test.blog", "name" : "_id_" } { "v" : 1, "key" : { "_id" : 1 }, "ns" : "test.authors", "name" : "_id_" } { "v" : 1, "key" : { "_id" : 1 }, "ns" : "test.papers", "name" : "_id_" } { "v" : 1, "key" : { "_id" : 1 }, "ns" : "test.analytics", "name" : "_id_" } { "v" : 1, "key" : { "_id" : 1 }, "ns" : "test.user", "name" : "_id_" } { "v" : 1, "key" : { "_id" : 1 }, "ns" : "test.food", "name" : "_id_" } { "v" : 1, "key" : { "_id" : 1 }, "ns" : "test.user.info", "name" : "_id_" } { "v" : 1, "key" : { "_id" : 1 }, "ns" : "test.userinfo", "name" : "_id_" } { "v" : 1, "key" : { "name" : 1 }, "ns" : "test.user", "name" : "IX_name" }   4.刪除索引 如果索引沒有用了,可以使用dropIndexes將其刪掉: > db.runCommand({"dropIndexes":"user","index":"IX_name"}) { "nIndexesWas" : 2, "ok" : 1 } ok表示刪除成功

給MongoDB添加索引

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.