1. 程式人生 > >mongodb(三)

mongodb(三)

需要 mon event find() esp 重復數 name command 代碼

索引詳講
索引管理
空間索引

for(var i = 0 ; i<200000 ;i++){
    db.books.insert({number:i,name:i+"book"})
}

1.創建簡單索引

數據準備index.js
1.1.先檢驗一下查詢性能
var start = new Date()
db.books.find({number:65871})
var end = new Date()
end - start
1.2.為number 創建索引
db.books.ensureIndex({number:1})

1.3.再執行第一部的代碼可以看出有數量級的性能提升


2.索引使用需要註意的地方
2.1.創建索引的時候註意1是正序創建索引-1是倒序創建索引
2.2.索引的創建在提高查詢性能的同事會影響插入的性能
對於經常查詢少插入的文檔可以考慮用索引
2.3.符合索引要註意索引的先後順序
2.4.每個鍵全建立索引不一定就能提高性能呢
索引不是萬能的
2.5.在做排序工作的時候如果是超大數據量也可以考慮加上索引
用來提高排序的性能

3.索引的名稱
3.1用VUE查看索引名稱

技術分享
3.2創建索引同時指定索引的名字
db.books.ensureIndex({name:-1},{name:”bookname”})

技術分享

4.唯一索引
4.1如何解決文檔books不能插入重復的數值
建立唯一索引
db.books.ensureIndex({name:-1},{unique:true})
試驗
db.books .insert({name:”1book”})

技術分享
5.踢出重復值
5.1如果建議唯一索引之前已經有重復數值如何處理


db.books.ensureIndex({name:-1},{unique:true,dropDups:true})
6.Hint
6.1如何強制查詢使用指定的索引呢?
db.books.find({name:"1book",number:1}).hint({name:-1})
指定索引必須是已經創建了的索引

技術分享

7.Expain
7.1如何詳細查看本次查詢使用那個索引和查詢數據的狀態信息
db.books.find({name:"1book"}).explain()

技術分享
“cursor” : “BtreeCursor name_-1“ 使用索引
“nscanned” : 1 查到幾個文檔
“millis” : 0 查詢時間0是很不錯的性能

1.system.indexes
1.1在shell查看數據庫已經建立的索引
db.system.indexes.find()
db.system.namespaces.find()
2.後臺執行
2.1執行創建索引的過程會暫時鎖表問題如何解決?
為了不影響查詢我們可以叫索引的創建過程在後臺
db.books.ensureIndex({name:-1},{background:true})
3.刪除索引
3.1批量和精確刪除索引
db.runCommand({dropIndexes : ”books” , index:”name_-1”})
db.runCommand({dropIndexes : ”books” , index:”*”})

1.mongoDB提供強大的空間索引可以查詢出一定範圍的地理坐標.看例子
準備數據map.json

技術分享
var map = [{
  "gis" : {
    "x" : 185,
    "y" : 150
  }
},{
  "gis" : {
    "x" : 70,
    "y" : 180
  }
},{
  "gis" : {
    "x" : 75,
    "y" : 180
  }
},{
  "gis" : {
    "x" : 185,
    "y" : 185
  }
},{
  "gis" : {
    "x" : 65,
    "y" : 185
  }
},{
  "gis" : {
    "x" : 50,
    "y" : 50
  }
},{
  "gis" : {
    "x" : 50,
    "y" : 50
  }
},{
  "gis" : {
    "x" : 60,
    "y" : 55
  }
},{
  "gis" : {
    "x" : 65,
    "y" : 80
  }
},{
  "gis" : {
    "x" : 55,
    "y" : 80
  }
},{
  "gis" : {
    "x" : 0,
    "y" : 0
  }
},{
  "gis" : {
    "x" : 0,
    "y" : 200
  }
},{
  "gis" : {
    "x" : 200,
    "y" : 0
  }
},{
  "gis" : {
    "x" : 200,
    "y" : 200
  }
}]
for(var i = 0;i<map.length;i++){
    db.map.insert(map[i])
}
View Code

技術分享

1.查詢出距離點(70,180)最近的3個點
添加2D索引
db.map.ensureIndex({"gis":"2d"},{min:-1,max:201})
默認會建立一個[-180,180]之間的2D索引
查詢點(70,180)最近的3個點
db.map.find({"gis":{$near:[70,180]}},{gis:1,_id:0}).limit(3)
2.查詢以點(50,50)和點(190,190)為對角線的正方形中的所有的點
db.map.find({gis:{"$within":{$box:[[50,50],[190,190]]}}},{_id:0,gis:1})
3.查詢出以圓心為(56,80)半徑為50規則下的圓心面積中的點
db.map.find({gis:{$within:{$center:[[56,80],50]}}},{_id:0,gis:1})

技術分享

mongodb(三)