1、MongoDB索引
1.1、創(chuàng)建索引
db.books.ensureIndex{{number:1}}
創(chuàng)建索引同時(shí)指定索引的名字
db.books.ensureIndex({number:1},{name:"book_"})
1.2、索引使用需要注意的地方
1)創(chuàng)建索引的時(shí)候注意1是正序創(chuàng)建索引-1是倒序創(chuàng)建索引
2)索引的創(chuàng)建在提高查詢(xún)性能的同事會(huì)影響插入的性能 對(duì)于經(jīng)常查詢(xún)少插入的文檔可以考慮用索引
3)符合索引要注意索引的先后順序
4)每個(gè)鍵全建立索引不一定就能提高性能呢 索引不是萬(wàn)能的
5)在做排序工作的時(shí)候如果是超大數(shù)據(jù)量也可以考慮加上索引 用來(lái)提高排序的性能
1.3、唯一索引
解決文檔books不能插入重復(fù)的數(shù)值
1.4、剔除重復(fù)值
#則插入相同的name值會(huì)報(bào)錯(cuò)
db.books.ensureIndex({name:-1},{unique:true})
如果建議唯一索引之前已經(jīng)有重復(fù)數(shù)值如何處理
#剔除重復(fù)數(shù)值
db.books.ensureIndex({name:1},{name:"book_",unique:true,dropDups:true})
1.5、后臺(tái)執(zhí)行創(chuàng)建索引
為了解決創(chuàng)建索引鎖表的問(wèn)題,在不影響查詢(xún)功能,可以在后臺(tái)運(yùn)行
db.books.ensureIndex({name:1},{background:true})
1.6、強(qiáng)制查詢(xún)已經(jīng)建立好的索引
#后一個(gè)name為索引名,正序倒序依據(jù)建立索引的規(guī)則,否則會(huì)報(bào)錯(cuò)
db.books.find({name:"323book"}).hint({name:1})
1.7、在shell查看數(shù)據(jù)庫(kù)已經(jīng)建立的索引
db.system.indexes.find()
db.system.namespaces.find()
1.8、查詢(xún)索引信息和查詢(xún)狀態(tài)信息
db.books.find({name:"123book"}).explain()
1.9、批量和精確刪除索引
db.runCommand({dropIndexes : "books" , index:"name_-1"})
db.runCommand({dropIndexes : "books" , index:"*"})
2、二維索引
建立二維索引
#默認(rèn)會(huì)建一個(gè)[-108,108]的范圍
db.map.ensureIndex({gis:"2d"},{min:-1,max:201})
3、MongoDB數(shù)據(jù)轉(zhuǎn)存及恢復(fù)
3.1、導(dǎo)出數(shù)據(jù)(中斷其他操作)
使用mongoexport命令行
-d指明使用的庫(kù)
-c指明要導(dǎo)出的表
-o指明要導(dǎo)出的文件名
-csv指定導(dǎo)出的csv格式
-q過(guò)濾導(dǎo)出
--type< json|csv|tsv>
把數(shù)據(jù)好testdb中的persons導(dǎo)出
mongoexport -d testdb -c persons -o D:/persons.json
導(dǎo)出其他主機(jī)數(shù)據(jù)庫(kù)的文檔
mongoexport --host 192.168.0.16 --port 37017
3.2、導(dǎo)入數(shù)據(jù)(中斷其他操作)
mongoimport --db testdb --collections persons --file d:/persons.json
3.3、運(yùn)行時(shí)備份 mongodump.exe
API: http://docs.mongodb.org/manual/reference/mongodump
mongodump --host 127.0.0.1:27017 -d testdb -o d:/testdb
3.4、運(yùn)行時(shí)恢復(fù) mongorestore.exe
API:http://docs.mongodb.org/manual/reference/mongorestore
恢復(fù)數(shù)據(jù)庫(kù)
db.dropDatabase()
mongorestore --host 127.0.0.1:27017 -d testdb -directoryperdb d:/testdb/testdb
MongoDB是文件數(shù)據(jù)庫(kù)這其實(shí)就可以用拷貝文件的方式進(jìn)行備份
3.5、上鎖和解鎖
db.runCommand({fsync:1,lock:1}) #上鎖
db.currentOp() #解鎖
3.7、數(shù)據(jù)修復(fù)
當(dāng)停電等不可逆轉(zhuǎn)災(zāi)難來(lái)臨的時(shí)候,由于mongodb的存儲(chǔ)結(jié)構(gòu)導(dǎo)致,會(huì)產(chǎn)生垃圾數(shù)據(jù),在數(shù)據(jù)恢復(fù)以后這垃圾數(shù)據(jù)依然存在,這是數(shù)據(jù)庫(kù),可以提供一個(gè)自我修復(fù)的能力.使用起來(lái)很簡(jiǎn)單
db.repairDatabase()
關(guān)注『 Tom彈架構(gòu) 』回復(fù)“MongoDB”可獲取配套資料。
本文為“Tom彈架構(gòu)”原創(chuàng),轉(zhuǎn)載請(qǐng)注明出處。技術(shù)在于分享,我分享我快樂(lè)!如果您有任何建議也可留言評(píng)論或私信,您的支持是我堅(jiān)持創(chuàng)作的動(dòng)力。關(guān)注『 Tom彈架構(gòu) 』可獲取更多技術(shù)干貨!
原創(chuàng)不易,堅(jiān)持很酷,都看到這里了,小伙伴記得點(diǎn)贊、收藏、在看,一鍵三連加關(guān)注!如果你覺(jué)得內(nèi)容太干,可以分享轉(zhuǎn)發(fā)給朋友滋潤(rùn)滋潤(rùn)!