mongodb新手入門,mongodb命令學習

下面來總結一下mongodb新手入門的經常使用命令吧。要是您是mongodb新手,能夠看下。mongodb

1,show dbs 查詢mongodb裏面的數據庫列表

enter image description here

若是想查看當前鏈接在哪一個數據庫下面,能夠直接輸入db數據庫

enter image description here

想切換到test數據庫下面 use test數組

enter image description here

二、db.getCollectionNames() 或者show collections 有哪些數據庫表名字

enter image description here

效果差很少,而後能夠對數據庫表進行操做服務器

三、查詢條數 db.foo.count()

enter image description here

四、數據庫的增刪改

存儲嵌套的對象

db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})

enter image description here

查看存儲的對象:

enter image description here

存儲數組對象

db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
 #根據query條件修改,若是不存在則插入,容許修改多條記錄  db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true) #刪除yy=5的記錄  db.foo.remove({'yy':5}) #刪除全部的記錄  db.foo.remove()

五、索引

增長索引:1(ascending),-1(descending)post

db.things.ensureIndex({firstname: 1, lastname: 1}, {unique: true});

索引子對象

 db.user_addr.ensureIndex({'Al.Em': 1})

查看索引信息

db.deliver_status.getIndexes() db.deliver_status.getIndexKeys()

根據索引名刪除索引

 db.user_addr.dropIndex('Al.Em_1')

六、查詢

 # 查找全部  >db.foo.find() #查找一條記錄  >db.foo.findOne() #根據條件檢索10條記錄  >db.foo.find({'msg':'Hello 1'}).limit(10) #sort排序  > db.deliver_status.find({'From':'yushunzhi@sohu.com'}).sort({'Dt',-1}) >db.deliver_status.find().sort({'Ct':-1}).limit(1) #count操做  > db.user_addr.count() >#distinct操做 >db.foo.distinct('msg') #操做  >db.foo.find({"timestamp": {"$gte" : 2}}) #子對象的查找  > db.foo.find({'address.city':'beijing'})

七、 管理

 查看collection數據的大小 >db.deliver_status.dataSize() #查看colleciont狀態  >db.deliver_status.stats() #查詢全部索引的大小  > db.deliver_status.totalIndexSize()

八、備份與恢復

先介紹下命令語法:spa

mongodump -h dbhost -d dbname -o dbdirectoryrest

-h:MongDB所在服務器地址,例如:127.0.0.1,固然也能夠指定端口號:127.0.0.1:27017code

-d:須要備份的數據庫實例,例如:test對象

-o:備份的數據存放位置,例如:c:\data\dump,固然該目錄須要提早創建,在備份完成後,系統自動在dump目錄下創建一個test目錄,這個目錄裏面存放該數據庫實例的備份數據。排序

mongorestore -h dbhost -d dbname --directoryperdb dbdirectory

-h:MongoDB所在服務器地址

-d:須要恢復的數據庫實例,例如:test,固然這個名稱也能夠和備份時候的不同,好比test2

--directoryperdb:備份數據所在位置,例如:c:\data\dump\test,這裏爲何要多加一個test,而不是備份時候的dump,讀者本身查看提示吧!

--drop:恢復的時候,先刪除當前數據,而後恢復備份的數據。就是說,恢復後,備份後添加修改的數據都會被刪除,慎用哦!

實際操做:

//cd 到bin目錄下 cd c:\data\db\bin //備份 mongodump -h 127.0.0.1:27017 -d test -o c:\data\dump //恢復 mongorestore -h 127.0.0.1:27017 -d test --directoryerdb c:\data\dump\test
相關文章
相關標籤/搜索