MongoDB 創建 Database 和 Collection


在開始使用MongoDB(Version:3.2.9)之前,必須首先在MongoDB中創建 Database 和 Collection。Database是相互獨立的,每個Database都有自己的Collections,不同的database中,可以存在名字相同的collection,但是Database不是物理存儲單位,MongoDB以Collection為物理存儲單位,每個collection都有自己的數據文件和index文件,這些文件以 .wt 結尾。

一,創建Collection

1,查看當前database中的collection列表

show collections

2,隱式創建Collection

在MongoDB中,Collection相當於關系型數據庫的Table,用戶不需要顯式定義Collection就能向Collection插入數據。在第一次向Collection插入數據時,MongoDB會自動創建Collection;如果Collection已經存在於Database中,那么MongoDB直接向Collection中插入數據。

db.foo.insert({_id:1,name:"test"})  

3,顯式創建Collection

使用 db.createCollection() 顯式創建Collection,通過指定Collection Option,創建特定用途的Collection。

Because MongoDB creates a collection implicitly when the collection is first referenced in a command, this method is used primarily for creating new collections that use specific options.

例如,創建固定集合(Capped Collection),普通集合能夠自動增長以容納更多的doc,但是固定集合有最大的size,容納的doc不能超過限制(max選項)。

db.createCollection("log", { capped : true, size : 5242880, max : 5000 } )

4,刪除collection,調用collection的drop方法刪除collection

db.collection_name.drop()

二,創建database

1,查看MongoDB的database列表

show dbs

查看當前連接所在的Database

db

2,使用use 命令創建database

use my_database_name

MongoDB返回以下信息,use 命令只是向MongoDB注冊database,並沒有實際的創建使用show dbs 查看,列表中沒有該database。

switched to db my_database_name

3,在當前database中創建collection,並向集合中插入數據

db.foo.insert({_id:1,name:"test"})  

此時,MongoDB真正創建database,查看存儲數據的folder,發現多了兩個.wt文件,一個用於存儲數據,一個用於存儲index。使用show dbs 查看,列表中存在該database。

三,刪除database

刪除database時,必須十分小心,除非用於測試環境,否則,不要輕易使用這個命令

1,使用use命令,切換到指定的database

use database_name

2,使用db命令,查看當前database,避免刪錯

db

3,刪除當前database

db.dropDatabase()

 

參考文檔:

db.createCollection()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM