一篇文章帶你搞懂非關(guān)系型數(shù)據(jù)庫MongoDB
但愿人長久,千里共嬋娟。
大家好,我是黃偉。今天給大家介紹芒果數(shù)據(jù)庫,一起來看看吧。
前言
Mongodb,分布式文檔存儲數(shù)據(jù)庫,由C++語言編寫,旨在為WEB應(yīng)用提供可擴(kuò)展的高性能數(shù)據(jù)存儲解決方案。MongoDB是一個高性能,開源,無模式的文檔型數(shù)據(jù)庫,是當(dāng)前NoSql數(shù)據(jù)庫中比較熱門的一種。它在許多場景下可用于替代傳統(tǒng)的關(guān)系型數(shù)據(jù)庫或鍵/值存儲方式。下面我們來說說它的具體用法吧。
一、安裝配置
1.下載
下載地址如下:
- https://590m.com/file/7715018-442253530
然后點擊msi安裝文件進(jìn)行安裝,由于比較大,建議不要安裝在C盤,選擇下圖中的選項哦。
在這里我選擇的是E:\mongodb,按著步驟來,整體來說比較簡單,唯一需要注意的是,有一個選項不能勾選,如下圖:
2.配置文件
創(chuàng)建E:\mongodb\data\log目錄,用來存放日志文件;
在E:\mongodb\data\log目錄里新建mongodb.log,用來存放日志信息;
創(chuàng)建E:\mongodb\data\db目錄,用來存放數(shù)據(jù)庫數(shù)據(jù);
并在E:\mongodb目錄下創(chuàng)建mongo.config,在文件內(nèi)部復(fù)制如下文本:
- #數(shù)據(jù)文件 此處=后對應(yīng)到數(shù)據(jù)所存放的目錄
- dbpath=E:\mongodb\data\db
- #日志文件 此處=后對應(yīng)到日志文件所在路徑
- logpath=E:\mongodb\data\log\mongodb.log
- #錯誤日志采用追加模式,配置這個選項后mongodb的日志會追加到現(xiàn)有的日志文件,而不是從新創(chuàng)建一個新文件
- logappend=true
- #啟用日志文件,默認(rèn)啟用
- journal=true
- #過濾掉一些無用的日志信息,若需要調(diào)試使用請設(shè)置為false
- quiet=true
- #端口號 默認(rèn)為27017
- port=27017
3.配置環(huán)境變量
4.創(chuàng)建數(shù)據(jù)庫文件存放位置
進(jìn)入命令提示符,鍵入如下命令:
- mongod.exe --dbpath E:\mongodb\data\db
--dbpath 是創(chuàng)建數(shù)據(jù)庫文件的存放位置,mongo需要確認(rèn)該目錄位置
5.驗證可否正常訪問
我們在瀏覽器中輸入以下的網(wǎng)站:
- http://localhost:27017/
如圖:
瀏覽器返回這樣一串英文即表示mongodb數(shù)據(jù)庫成功啟動。
但是每次這樣才能啟動太麻煩,我們可以將它添加到系統(tǒng)任務(wù)中,讓它開機(jī)自啟動啊。
6.安裝日志文件和服務(wù)名
- C:\Users\Administrator>mongod.exe --dbpath E:\mongodb\data\db -logpath E:\mongo
- db\data\log\mongodb.log -install -serviceName "MongoDB"
如果它顯示已存在,如圖:
那么,先刪除服務(wù):
- sc delete MongoDB
再次輸入上個命令就好了。
7.啟動mongodb
然后我們將它啟動起來:
- net start MongoDB
可以看到啟動成功了,不容易啊。
關(guān)閉mongodb服務(wù):
- net stop MongoDB
二、mongodb的數(shù)據(jù)庫增刪改查
眾所周知,mongodb沒有表這個概念,存儲都是靠集合來完成,因此我們需要創(chuàng)建的是集合。
我們先看看mongodb最常見的數(shù)據(jù)庫操作,首先 打開命令提示符,輸入如下命令進(jìn)入環(huán)境:
- // 創(chuàng)建數(shù)據(jù)庫
- use data
- //顯示所有數(shù)據(jù)庫
- show dbs
- show databases
- //查看當(dāng)前數(shù)據(jù)庫
- db
- db.getName()
- // 刪除當(dāng)前數(shù)據(jù)庫
- db.dropDatabase()
- //修復(fù)當(dāng)前數(shù)據(jù)庫
- db.repairDatabase()
- //從指定的機(jī)器上復(fù)制指定數(shù)據(jù)庫數(shù)據(jù)到某個數(shù)據(jù)庫
- db.copyDatabase("my_db", "you_db", "127.0.0.1")
- //從指定主機(jī)上克隆數(shù)據(jù)庫
- db.cloneDatabase(“127.0.0.1”)
- //創(chuàng)建集合 固定集合大小為100 最大數(shù)值1000
- db.createCollection('student',{capped:true,size:100,max:1000})
- //顯示所有集合
- show collections
- //得到當(dāng)前db的所有聚集集合
- db.getCollectionNames()
- //顯示當(dāng)前db所有聚集索引的狀態(tài)
- db.printCollectionStats()
- //刪除集合
- db.hw.drop()
- //得到指定名稱的聚集集合
- db.getCollection("hw")
- //插入集合 _id存在就報錯
- db.hw.insert({_id:0001,'name':'hw','age':10})
- //顯示集合內(nèi)容
- db.hw.find()
- //顯示一條集合內(nèi)容
- db.hw.findOne()
- //格式化顯示集合內(nèi)容
- db.hw.find().pretty()
- //保存集合_id存在就更新
- db.hw.save({_id:0001,'name':'hw','age':10})
- //更新集合
- $set 指定鍵并更新 不存在則創(chuàng)建 $unset 刪除
- db.hw.update({'name':'hw'},{'name':'xz'}) //更新一條數(shù)據(jù)替換
- db.hw.update({'name':'hw'},{$set{'name':'xz'}}) //更新一條數(shù)據(jù)更新
- db.hw.update({'name':'hw'},{'name':'xz'},{multi:true}) //更新全部數(shù)據(jù)
- //刪除集合數(shù)據(jù)
- db.hw.remove({'name':'hw'},{justOne:true}) //刪除一條數(shù)據(jù)
- db.hw.remove({'name':'hw'},{justOne:false}) //刪除全部數(shù)據(jù)
- //集合重命名
- db.user.renameCollection("hw"); 將user重命名為hw
- //查詢數(shù)據(jù)
- $lt--小于 $lte--小于等于
- $gt--大于 $gte--大于等于
- $ne--不等于 $in $nin--是否處在該范圍
- $and $or 查詢條件與或
- $type
- /^abc/ $regex:'abc$' 正則表達(dá)式
- limit(num) 顯示指定數(shù)量的結(jié)果
- skip(num) 跳過指定數(shù)量的結(jié)果
- $where 查詢函數(shù)
- _id默認(rèn)顯示,不顯示則把值設(shè)為0
- sort() 排序,參數(shù)為1升序 -1 降序
- count() 統(tǒng)計查詢結(jié)果數(shù)量 也可把查詢參數(shù)放進(jìn)count中
- distinct() 消除重復(fù)數(shù)據(jù)
- db.hw.find({age:{$gte:18}})
- db.hw.find({age:{$in:[12,32,21]}})
- db.hw.find({$and:{age:{$in:[12,32,21]},{age:{$gte:18}}}})
- db.hw.find({age:{$gte:18}}).skip(3).limit(2)
- db.hw.find({age:/^abc/,name:{$regex:'123$'}})
- db.hw.find($where:function(){return this.age<=19})
- db.hw.find({age:{$gte:18}}).sort({age:1})
- db.hw.distinct({age:{$gte:18}})
三、索引
- //建立唯一值的索引
- db.hw.ensureIndex({name:1},{'unique':true}) //1升序 -1降序
- db.hw.find({name:'he'}).explain('executionStats') //獲取時間
- //查看集合中所有索引
- db.hw.getIndexes()
- //刪除索引
- db.hw.dropIndex('name')
- //重建索引
- db.hw.reIndex()
四、數(shù)據(jù)聚合
- //數(shù)據(jù)聚合
- $group分組 $match過濾數(shù)據(jù) $project修改文檔結(jié)構(gòu)
- $sort排序 $limit指定數(shù)量 $skip 跳過
- $unwind 拆分?jǐn)?shù)組類型的字段 $pushAll
- $sum 和 $avg 平均值 $push 添加值至數(shù)組
- $pop $addToSet $pull $rename $bit
- $first開頭 $last結(jié)尾 $min $max
- db.hw.aggregate({$group:{_id:'$name',count:{$sum:1},avg_age:{$avg:'$age'}}}
- ,{$project:{name:'$_id',count:'$count',avg_age:'$avg_age'}},
- {$match:{age:{$gt:20}}},{$unwind:{'$age',preserveNullAndEmptyArrays:true}} //true保留缺失值
- )
五、數(shù)據(jù)備份與恢復(fù)
- //備份數(shù)據(jù)
- mongodump -h dbhost -d dbname -o dbdirectory
- -h 服務(wù)器地址
- -d 需要備份的數(shù)據(jù)庫名稱
- -o 備份數(shù)據(jù)庫存放位置
- //數(shù)據(jù)恢復(fù)
- mongorestore -h dbhost -d dbname --dir dbdirectory
- -h 服務(wù)器地址
- -d 需要恢復(fù)的數(shù)據(jù)庫實例
- --dir 備份數(shù)據(jù)所在位置
六、數(shù)據(jù)監(jiān)控
- //監(jiān)控
- Mongostat 檢測數(shù)據(jù)庫狀態(tài)
- Mongotop sleeptime - -locks 跟蹤一個MongoDB的實例
七、高級查詢
- <,>,>=,<=
- 這四個就不用解釋了,最常用的,也是最簡單的。
- db.collection.find({ "field" : { $gt: value } } ) // 大于 : field > value
- db.collection.find({ "field" : { $lt: value } } ) // 小于 : field < value
- db.collection.find({ "field" : { $gte: value } } ) // 大于等于 : field >= value
- db.collection.find({ "field" : { $lte: value } } ) // 小于等于 : field <= value
- 如果要同時滿足多個條件,記得要這樣用:
- db.collection.find({ "field" : { $gt: value1, $lt: value2 } } ) // value1 < field < value
- $ne 不等于
- db.things.find( { x : { $ne : 3 } } )
- 條件相當(dāng)于x<>3,即x不等于3。
- $mod 取模運(yùn)算
- db.things.find( { a : { $mod : [ 10 , 1 ] } } )
- 條件相當(dāng)于a % 10 == 1 即a除以10余數(shù)為1的。
- $nin 不屬于
- db.things.find({j:{$nin: [2,4,6]}})
- 條件相當(dāng)于 j 不等于 [2,4,6] 中的任何一個。
- $in 屬于
- db.things.find({j:{$in: [2,4,6]}})
- 條件相當(dāng)于j等于[2,4,6]中的任何一個。
- $all 全部屬于
- db.things.find( { a: { $all: [ 2, 3 ] } } )
- 與$in類似,但必須是[]的值全部都存在。
- $size 數(shù)量,尺寸
- db.things.find( { a : { $size: 1 } } )
- 條件相當(dāng)于a的值的數(shù)量是1(a必須是數(shù)組,一個值的情況不能算是數(shù)量為1的數(shù)組)。
- $exists 字段存在
- db.things.find( { a : { $exists : true } } )
- db.things.find( { a : { $exists : false } } )
- true返回存在字段a的數(shù)據(jù),false返回不存在字段a的數(shù)據(jù)。
- $type 字段類型
- db.things.find( { a : { $type : 2 } } )
- 條件是a類型符合的話返回數(shù)據(jù)。
- 參數(shù)類型如下圖:
- Type Name Type Number
- Double 1
- String 2
- Object 3
- Array 4
- Binary data 5
- Object id 7
- Boolean 8
- Date 9
- Null 10
- Regular expression 11
- JavaScript code 13
- Symbol 14
- JavaScript code with scope 15
- 32-bit integer 16
- Timestamp 17
- 64-bit integer 18
- Min key 255
- Max key 127
- Regular Expressions 正則表達(dá)式
- db.customers.find( { name : /acme.*corp/i } )
- 類似sql中的like方法。
- 行開始 /^ 行結(jié)束 $/
- 這里要特別特別特別地注意一點,關(guān)乎查詢效率:
- While /^a/, /^a./, and /^a.$/ are equivalent and will all use an index in the same way, the later two require scanning the whole string so they will be slower. The first format can stop scanning after the prefix is matched.
- 意思大概就是指在查詢以a開頭字符串時,可以有三種形式, /^a/, /^a./,和/^a.$/ 。后面兩種形式會掃描整個字符串,查詢速度會變慢。第一種形式會在查到符合的開頭后停止掃描后面的字符。
- 所以要特別注意。
- 幾個附加參數(shù):
- i的意思是忽略大小寫。(這個很重要,很常用)
- m的意思是支持多行。(不過ME沒有嘗試過)
- x的意思是擴(kuò)展。(也沒用過)
- $or 或 (注意:MongoDB 1.5.3后版本可用)
- db.foo.find( { $or : [ { a : 1 } , { b : 2 } ] } )
- 符合條件a=1的或者符合條件b=2的數(shù)據(jù)都會查詢出來。
- 與其它字段一起查詢:
- db.foo.find( { name : "bob" , $or : [ { a : 1 } , { b : 2 } ] } )
- 符合條件name等于bob,同時符合其它兩個條件中任意一個的數(shù)據(jù)。
- Value in an Array 數(shù)組中的值
- 例如數(shù)據(jù)庫中存在這樣的數(shù)據(jù):
- { "_id" : ObjectId("4c503405645fa23b31e11631"), "colors" : [ "red", "black" ] }
- 查詢
- db.things.find( { colors : "red" } );
- 即可查到上面那條數(shù)據(jù)。
- $elemMatch 要素符合
- t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } )
- 結(jié)果:
- { "_id" : ObjectId("4b5783300334000000000aa9"),
- "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]
- }
- x其中一個要素符合那個檢索條件就可以被檢索出來。(不過一般誰用像x這樣的結(jié)構(gòu)去保存數(shù)據(jù)呢?)
- Value in an Embedded Object 內(nèi)嵌對象中的值
- 例如數(shù)據(jù)庫中存在這樣的數(shù)據(jù):
- { "_id" : ObjectId("4c503773645fa23b31e11632"), "author" : { "name" : "Dan Brown", "age" : 38 }, "book" : "The Lost Symbol" }
- 查詢:
- db.postings.find( { "author.name" : "Dan Brown" } );
- 即可查到上面那條數(shù)據(jù)。
- 查詢內(nèi)嵌對象的屬性,記得要加上“”,字段是“author.name”,而不是author.name。
- $not 不是
- db.customers.find( { name : { $not : /acme.*corp/i } } );
- 這是一個與其它查詢條件組合使用的操作符,不會單獨使用。
- 只要你理解了前面的查詢操作即可,只是再加上了$not,結(jié)果就是得到了沒有$not的相反結(jié)果集。
- sort() 排序
- 這個非常實用。即sql語言中的OrderBy。
- db.myCollection.find().sort( { ts : -1 } )
- 也可以多個字段排序
- db.myCollection.find().sort( { ts : -1 ,ds : 1 } )
- 這里的1代表升序,-1代表降序。
- 經(jīng)過ME的實驗,小于0的數(shù)字就是降序,0以上(包括0)就是升序。
- limit() skip()
- 這兩個ME想連起來講,它們就是你實現(xiàn)數(shù)據(jù)庫分頁的好幫手。
- limit()控制返回結(jié)果數(shù)量,如果參數(shù)是0,則當(dāng)作沒有約束,limit()將不起作用。
- skip()控制返回結(jié)果跳過多少數(shù)量,如果參數(shù)是0,則當(dāng)作沒有約束,skip()將不起作用,或者說跳過了0條。
- 例如:
- db.test.find().skip(5).limit(5)
- 結(jié)果就是取第6條到第10條數(shù)據(jù)。
- snapshot() (沒有嘗試)
- count() 條數(shù)
- 返回結(jié)果集的條數(shù)。
- db.test.count()
- 在加入skip()和limit()這兩個操作時,要獲得實際返回的結(jié)果數(shù),需要一個參數(shù)true,否則返回的是符合查詢條件的結(jié)果總數(shù)。
- 例子如下:
- > db.test.find().skip(5).limit(5).count()
- 9
- > db.test.find().skip(5).limit(5).count(true)
- 4
八、用戶操作
- //添加一個用戶
- db.addUser("hw")
- db.addUser("hw", "123321", true) #添加用戶、設(shè)置密碼、是否只讀
- //數(shù)據(jù)庫認(rèn)證、安全模式
- db.auth("hw", "123123")
- //顯示當(dāng)前所有用戶
- show users
- //刪除用戶
- db.removeUser("hw")
九、其它命令
- //查詢指定數(shù)據(jù)庫的集合的可用的存儲空間
- db.hw.storageSize()
- //查詢集合已分配的存儲空間
- db.hw.totalSize()
- //查看數(shù)據(jù)庫服務(wù)器的狀態(tài)
- db.serverStatus()
- //查詢指定數(shù)據(jù)庫的統(tǒng)計信息
- db.stats()
- //當(dāng)前db版本
- db.version()
- //查看當(dāng)前db的鏈接機(jī)器地址
- db.getMongo()
十、可視化工具提高交互
為了讓我們的操作更加人性化,更加直觀的顯示操作數(shù)據(jù),我們可以使用一款可視化工具,今天我給大家?guī)淼木褪荖avicat-mongo 這款工具,它是Navicat家族中一款只針對mongo數(shù)據(jù)庫進(jìn)行操作的數(shù)據(jù)庫可視化工具。下載地址:
- https://590m.com/file/7715018-442253555
軟件理由破解程序,只需進(jìn)行簡單操作即可進(jìn)行破解。
下載好后按照提示進(jìn)行安裝即可,
這樣基本就能完成數(shù)據(jù)庫的操作了,接下來就是大家伙照著命令去敲了。
總結(jié)
本文從Mongodb的安裝、配置、數(shù)據(jù)增刪改查、索引操作、數(shù)據(jù)聚合、數(shù)據(jù)備份與恢復(fù)、監(jiān)控、高級查詢、用戶操作等十個方面進(jìn)行介紹Mongodb,一篇文章帶你搞懂Mongodb數(shù)據(jù)庫。