MongoDB學習筆記(二:入門環境配置及與關係型數據庫區別總結)

1、下載及安裝MongoDB

MongoDB下載官網連接:http://www.mongodb.org/downloadsphp

具體安裝步驟教程:http://www.shouce.ren/api/view/a/6191PS:該連接中對MongoDB安裝講解比較詳細,通俗易懂。安裝教程連接是我從手冊網上找到的,下面的總結知識點也是本人從中學習後概括的一部分,有興趣的同窗不妨收藏一下~html

附百度雲下載連接:http://pan.baidu.com/s/1i5QpmiL 密碼:lnqjmysql

 

2、MongoDB可視化工具下載

我的比較習慣在圖形化界面進行相關命令操做,因此在安裝完MongoDB後,就順便找了一個MongoDB可視化工具安裝使用。MongoDB可視化工具比較多,經過查找網上相關博客和帖子,發現mongobooster這個可視化工具比較受歡迎。正則表達式

Mongobooster官網下載連接:http://mongobooster.com/downloads(記得當時從官網下載時,網速超慢,下面附一個本人當時下載下來的一個版本的百度雲連接)sql

Mongobooster百度雲連接:http://pan.baidu.com/s/1jIhnwVW 密碼:wgxwmongodb

Mongobooster安裝後具體界面(PS:和使用mysql相關可視化工具很像,用着很不錯):數據庫

 

 

3、MongoDB基本概念及與關係型數據區別

MongoDB數據庫基本概念:express

關係型數據庫api

MongoDB數組

database(數據庫)

database(數據庫)

table(表)

collection(集合)

row()

document(文檔)

column(列)

filed()

index(索引)

index(索引)

table joins(表關係)

primary key(主鍵)

自動將_id字段設置爲主鍵

 

MongoDB經常使用的數據類型:

數據類型

描述

String

字符串,存儲數據經常使用的數據類型,在MongoDB中,UTF-8編碼纔是合法的

Integer

整型數值,用於存儲數值,根據你所採用的服務器,可分爲32位或64

Boolen

布爾值,用於存儲布爾值(真/假)

Double

雙精度浮點值,用於存儲浮點值

Min/Max keys

將一個值與BSON(二進制的JSON)元素的最低值和最高值相對比

Arrays

用於將數組或列表或多個值存儲爲一個鍵

Timestamp

時間戳,記錄文檔修改或添加的具體時間

Object

用於內嵌文檔

Null

用於建立空值

Symbol

符號。該數據類型基本上等同於字符串類型,但不一樣的是,它通常用於採用特殊符號類型的語言

Date

日期時間,用unix時間格式來存儲當前日期或時間。你能夠指定本身的日期時間:建立Date對象,傳入年月日信息

Object ID

對象 ID,用於建立文檔的 ID

Binary Data

二進制數據,用於存儲二進制數據

Code

代碼類型,用於在文檔中存儲 JavaScript 代碼

Regular expression

正則表達式類型,用於存儲正則表達式

 

MogoDB經常使用操做命令:

一、建立數據庫:use db_name(例如:use library,建立一個數據庫名稱爲library的數據庫)

二、查看系統全部數據庫:show dbs

三、刪除數據庫:先使用具體數據庫,使用命令use db_name(PS:該命令在有db_name數據庫條件下不會建立數據庫,沒有則從新建立一個db_name數據庫),而後使用命令db.dropDatabase()命令

四、插入文檔:db.collection_name.insert(document)

五、查看文檔:db.collection_name.find()

六、更新文檔:db.collection_name.update(<query>,<update>,{upsert:<boolen>,multi:<boolen>,writeConcern:<boolen>})

七、刪除文檔:db.collection_name.remove(<query>,<justOne>)

 

MongoDB操做語句與關係型SQL語句比照對應表:

 

操做

格式

範例

RDBMS中的相似語句

等於

{<key>:<value>}

db.col.find({"by":"菜鳥教程"}).pretty()

where by = '菜鳥教程'

小於

{<key>:{$lt:<value>}}

db.col.find({"likes":{$lt:50}}).pretty()

where likes < 50

小於或等於

{<key>:{$lte:<value>}}

db.col.find({"likes":{$lte:50}}).pretty()

where likes <= 50

大於

{<key>:{$gt:<value>}}

db.col.find({"likes":{$gt:50}}).pretty()

where likes > 50

大於或等於

{<key>:{$gte:<value>}}

db.col.find({"likes":{$gte:50}}).pretty()

where likes >= 50

不等於

{<key>:{$ne:<value>}}

db.col.find({"likes":{$ne:50}}).pretty()

where likes != 50

      

附操做MongoDB數據庫常見命令(PS:原文連接):

  1 MongoDb 命令查詢全部數據庫列表  
  2   
  3 CODE:  
  4   
  5 > show dbs  
  6   
  7 若是想查看當前鏈接在哪一個數據庫下面,能夠直接輸入db  
  8 CODE:  
  9   
 10 > db  
 11 Admin  
 12 想切換到test數據庫下面  
 13 CODE:  
 14   
 15 > use test  
 16 switched to db test  
 17 > db  
 18 Test  
 19 想查看test下有哪些表或者叫collection,能夠輸入  
 20 CODE:  
 21 
 22 
 23 > show collections  
 24 system.indexes  
 25 user  
 26 想知道mongodb支持哪些命令,能夠直接輸入help  
 27 CODE:  
 28 > help  
 29 Dos代碼  收藏代碼  
 30   
 31     HELP    
 32           show dbs                     show database names    
 33           show collections             show collections in current database    
 34           show users                   show users in current database    
 35           show profile                 show most recent system.profile entries with time >= 1ms    
 36           use <db name>                set curent database to <db name>    
 37           db.help()                    help on DB methods    
 38           db.foo.help()                help on collection methods    
 39           db.foo.find()                list objects in collection foo    
 40           db.foo.find( { a : 1 } )     list objects in foo where a == 1    
 41           it                           result of the last line evaluated; use to further iterate    
 42   
 43 若是想知道當前數據庫支持哪些方法:  
 44 CODE:  
 45 
 46 
 47 
 48 > db.help();  
 49 Java代碼  收藏代碼  
 50   
 51     DB methods:    
 52           db.addUser(username, password) 添加數據庫受權用戶    
 53           db.auth(username, password)                訪問認證    
 54           db.cloneDatabase(fromhost) 克隆數據庫    
 55           db.commandHelp(name) returns the help for the command    
 56           db.copyDatabase(fromdb, todb, fromhost)  複製數據庫    
 57           db.createCollection(name, { size : ..., capped : ..., max : ... } ) 建立表    
 58           db.currentOp() displays the current operation in the db    
 59           db.dropDatabase()        刪除當前數據庫    
 60           db.eval_r(func, args) run code server-side    
 61           db.getCollection(cname) same as db['cname'] or db.cname    
 62           db.getCollectionNames()        獲取當前數據庫的表名    
 63           db.getLastError() - just returns the err msg string    
 64           db.getLastErrorObj() - return full status object    
 65           db.getMongo() get the server connection object    
 66           db.getMongo().setSlaveOk() allow this connection to read from the nonmaster member of a replica pair    
 67           db.getName()    
 68           db.getPrevError()    
 69           db.getProfilingLevel()    
 70           db.getReplicationInfo()    
 71           db.getSisterDB(name) get the db at the same server as this onew    
 72           db.killOp() kills the current operation in the db    
 73           db.printCollectionStats()   打印各表的狀態信息    
 74           db.printReplicationInfo()        打印主數據庫的複製狀態信息    
 75           db.printSlaveReplicationInfo()        打印從數據庫的複製狀態信息    
 76           db.printShardingStatus()                打印分片狀態信息    
 77           db.removeUser(username) 刪除數據庫用戶    
 78           db.repairDatabase() 修復數據庫    
 79           db.resetError()    
 80           db.runCommand(cmdObj) run a database command.  if cmdObj is a string, turns it into { cmdObj : 1 }    
 81           db.setProfilingLevel(level) 0=off 1=slow 2=all    
 82           db.shutdownServer()    
 83           db.version() current version of the server    
 84 
 85 若是想知道當前數據庫下的表或者表collection支持哪些方法,能夠使用一下命令如:  
 86 CODE:  
 87   
 88 > db.user.help();  user爲表名  
 89 Java代碼  收藏代碼  
 90   
 91     DBCollection help    
 92           db.foo.count()                統計表的行數    
 93           db.foo.dataSize()        統計表數據的大小    
 94           db.foo.distinct( key ) - eg. db.foo.distinct( 'x' )                按照給定的條件除重    
 95           db.foo.drop() drop the collection 刪除表    
 96           db.foo.dropIndex(name)  刪除指定索引    
 97           db.foo.dropIndexes() 刪除全部索引    
 98           db.foo.ensureIndex(keypattern,options) - options should be an object with these possible fields: name, unique, dropDups  增長索引    
 99           db.foo.find( [query] , [fields]) - first parameter is an optional query filter. second parameter is optional set of fields to return.     
100   
101   
102 根據條件查找數據  
103 -----------------------  
104 經過條件查詢: db.foo.find( { x : 77 } , { name : 1 , x : 1 } )  
105 -----------------------------  
106 
107 若是想知道當前數據庫下的表或者表collection支持哪些方法,能夠使用一下命令如:  
108 CODE:  
109   
110 > db.user.help();  user爲表名  
111 Java代碼  收藏代碼  
112   
113     DBCollection help    
114           db.foo.count()                統計表的行數    
115           db.foo.dataSize()        統計表數據的大小    
116           db.foo.distinct( key ) - eg. db.foo.distinct( 'x' )                按照給定的條件除重    
117           db.foo.drop() drop the collection 刪除表    
118           db.foo.dropIndex(name)  刪除指定索引    
119           db.foo.dropIndexes() 刪除全部索引    
120           db.foo.ensureIndex(keypattern,options) - options should be an object with these possible fields: name, unique, dropDups  增長索引    
121           db.foo.find( [query] , [fields]) - first parameter is an optional query filter. second parameter is optional set of fields to return.     
122   
123   
124 根據條件查找數據  
125 -----------------------  
126 經過條件查詢: db.foo.find( { x : 77 } , { name : 1 , x : 1 } )  
127 -----------------------------  
128              instead of connecting to a mongod instance  
129 -v [ --verbose ]         be more verbose (include multiple times for more  
130                          verbosity e.g. -vvvvv)  
131 -o [ --out ] arg (=dump) output directory  
132 [falcon@www.fwphp.cn  ~/mongodb/bin]$ ./mongodump -d test -o test/  
133 connected to: 127.0.0.1  
134 DATABASE: test         to         test/test  
135       test.user to test/test/user.bson  
136                100000 objects  
137       test.system.indexes to test/test/system.indexes.bson  
138                1 objects  
139 [falcon@www.fwphp.cn  ~/mongodb/bin]$ ls  
140 2     mongo   mongodump    mongofiles   mongorestore  mongosniff  
141 dump  mongod  mongoexport  mongoimport  mongos     test  
142 MongoDB的數據恢復工具mongorestore  
143   
144 查看test庫中的表  
145 CODE:  
146   
147 > show collections  
148 system.indexes  
149 User  
150 刪除user表  
151 CODE:  
152   
153 > db.user.drop();  
154 True  
155 
156 > show collections  
157 System.indexes  
158 如今利用mongorestore表恢復剛纔利用mongodump備份的數據  
159 CODE:  
160   
161 [falcon@www.fwphp.cn  ~/mongodb/bin]$ ./mongorestore --help  
162 usage: ./mongorestore [options] [directory or filename to restore from]  
163 options:  
164 --help                  produce help message  
165 -h [ --host ] arg       mongo host to connect to  
166 -d [ --db ] arg         database to use  
167 -c [ --collection ] arg collection to use (some commands)  
168 -u [ --username ] arg   username  
169 -p [ --password ] arg   password  
170 --dbpath arg            directly access mongod data files in this path,  
171                         instead of connecting to a mongod instance  
172 -v [ --verbose ]        be more verbose (include multiple times for more  
173                         verbosity e.g. -vvvvv)  
174   
175 [falcon@www.fwphp.cn  ~/mongodb/bin]$ ./mongorestore -d test -c user test/test/user.bson  
176 connected to: 127.0.0.1  
177 test/test/user.bson  
178        going into namespace [test.user]  
179   
180        100000 objects  
181 User表中的10w條記錄已經恢復  
182 CODE:  
183   
184 > show collections  
185 system.indexes  
186 user  
187 > db.user.find();  
188 { "_id" : ObjectId("4b9c8db08ead0e3347000000"), "uid" : 1, "username" : "Falcon.C-1" }  
189 { "_id" : ObjectId("4b9c8db08ead0e3347010000"), "uid" : 2, "username" : "Falcon.C-2" }  
190 { "_id" : ObjectId("4b9c8db08ead0e3347020000"), "uid" : 3, "username" : "Falcon.C-3" }  
191 { "_id" : ObjectId("4b9c8db08ead0e3347030000"), "uid" : 4, "username" : "Falcon.C-4" }  
192 { "_id" : ObjectId("4b9c8db08ead0e3347040000"), "uid" : 5, "username" : "Falcon.C-5" }  
193 .................  
194 has more  
195   
196   
197   
198   
199   
200    1. 超級用戶相關:  
201   
202          #增長或修改用戶密碼  
203   
204          db.addUser('admin','pwd')  
205   
206          #查看用戶列表  
207   
208          db.system.users.find()  
209   
210          #用戶認證  
211   
212          db.auth('admin','pwd')  
213   
214          #刪除用戶  
215   
216          db.removeUser('mongodb')  
217 
218    #查看全部用戶  
219   
220          show users  
221   
222          #查看全部數據庫  
223   
224          show dbs  
225   
226          #查看全部的collection  
227   
228          show collections  
229   
230          #查看各collection的狀態  
231   
232          db.printCollectionStats()  
233   
234          #查看主從複製狀態  
235   
236          db.printReplicationInfo()  
237   
238          #修復數據庫  
239   
240          db.repairDatabase()  
241   
242          #設置記錄profiling,0=off 1=slow 2=all  
243   
244          db.setProfilingLevel(1)  
245   
246          #查看profiling  
247         show profile  
248   
249          #拷貝數據庫  
250   
251          db.copyDatabase('mail_addr','mail_addr_tmp')  
252   
253          #刪除collection  
254   
255          db.mail_addr.drop()  
256   
257          #刪除當前的數據庫  
258   
259          db.dropDatabase()  
260   
261    2. 客戶端鏈接  
262   
263           /usr/local/mongodb/bin/mongo user_addr -u user -p 'pwd'  
264   
265    3. 增刪改  
266   
267            #存儲嵌套的對象  
268   
269           db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})  
270   
271           #存儲數組對象  
272   
273           db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})  
274   
275           #根據query條件修改,若是不存在則插入,容許修改多條記錄  
276    db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)  
277   
278           #刪除yy=5的記錄  
279   
280           db.foo.remove({'yy':5})  
281   
282           #刪除全部的記錄  
283   
284          db.foo.remove()  
285   
286    4. 索引  
287   
288           增長索引:1(ascending),-1(descending)  
289   
290           db.things.ensureIndex({firstname: 1, lastname: 1}, {unique: true});  
291   
292           #索引子對象  
293   
294           db.user_addr.ensureIndex({'Al.Em': 1})  
295   
296           #查看索引信息  
297   
298           db.deliver_status.getIndexes()  
299   
300           db.deliver_status.getIndexKeys()  
301   
302           #根據索引名刪除索引  
303     db.user_addr.dropIndex('Al.Em_1')  
304   
305    5. 查詢  
306   
307           查找全部  
308   
309           db.foo.find()  
310   
311           #查找一條記錄  
312   
313           db.foo.findOne()  
314   
315           #根據條件檢索10條記錄  
316   
317           db.foo.find({'msg':'Hello 1'}).limit(10)  
318   
319           #sort排序  
320   
321           db.deliver_status.find({'From':'yushunzhi@sohu.com'}).sort({'Dt',-1})  
322   
323           db.deliver_status.find().sort({'Ct':-1}).limit(1)  
324   
325          #count操做  
326   
327          db.user_addr.count()  
328   
329          #distinct操做  
330   
331          db.foo.distinct('msg')  
332     #>操做  
333   
334          db.foo.find({"timestamp": {"$gte" : 2}})  
335   
336          #子對象的查找  
337   
338          db.foo.find({'address.city':'beijing'})  
339   
340    6. 管理  
341   
342           查看collection數據的大小  
343   
344           db.deliver_status.dataSize()  
345   
346           #查看colleciont狀態  
347   
348           db.deliver_status.stats()  
349   
350           #查詢全部索引的大小  
351   
352           db.deliver_status.totalIndexSize()   
相關文章
相關標籤/搜索