MongoDB(4)數據庫 & 集合操作

MongoDB 入門專欄

http://blog.csdn.net/column/details/19681.html


數據庫操作

查看數據庫

 
# 查看當前mongo下的所有數據庫
> show databases  
> show dbs

創建數據庫 

 
# 連接,創建 testdb 數據庫
> use testdb
此時已經創建了 testdb 數據庫,但是如果使用 show dbs 指令並不能查詢到相關信息,這是由於 mongodb 是不顯示空數據庫的,如果向空數據庫 testdb 插入一些數據,便可以顯示該數據庫了;

刪除數據庫

 
# 刪除 testdb 數據庫
> use testdb
> db.dropDatabase()

複製數據庫

可以使用 db.copyDatabase(from_db,to_db [,from_host]) 來複制數據庫;
 
# 複製 testdb 庫爲 testdb_copy 庫
> use testdb
> db.copyDatabase("testdb", "testdb_copy")

重命名數據庫

mongodb 沒有提供重命名數據庫的指令,可以通過複製數據庫來實現數據庫的重命名;
 
# 重命名 testdb 爲 testdb233
> use testdb
> db.copyDatabase('testdb', 'testdb233')
> db.dropDatabase()
但是這種方式如果數據庫龐大時很佔用資源,可以使用遍歷重命名集合的方式來實現:
 
# 重命名 testdb 爲 testdb233
> use testdb 
> db.runCommand( { renameCollection:'testdb.orders', to: 'testdb233.orders' } )



集合操作

查看集合

 
# 顯示指定數據庫的所有集合
> use testdb
> show collections  # 或者 show tables

創建集合

db.createCollection(name,option) 用於創建集合,其中 option 可選參數如下:
  • autoIndexID:是否在 _id 字段自動創建索引,默認爲 false;
  • capped:是否創建固定集合,指定爲 true 時當集合容量到最大值時,會自動覆蓋最早的文檔,當指定 capped時,必須指定 size  參數;
  • size:指定固定集合的大小的上限,單位爲字節;
  • max:指定固定集合的文檔數量上限;
※在插入文檔時,mongodb 先檢查 size,再檢查 max;
 
> use testdb
> db.createCollection('articles')
> db.createCollection( 'site', { capped:true, autoIndexID:true, size:233300, max: 10000} )
實際上 mongodb 中並不需要創建集合,在插入文檔時候,mongodb 會自動創建集合;

刪除集合

 
# 刪除 testdb 的 site 集合
> use testdb
> db.site.drop()

重命名集合

 
# 重命名 testdb 庫的 site 集合爲 site233 
> use testdb
> db.site.renameCollection('site233')

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章