Python MongoDB - 建立集合



MongoDB 中的集合儲存一組文件,類似於關係資料庫中的表。

您可以使用createCollection()方法建立集合。此方法接受一個表示要建立的集合名稱的字串值和一個可選引數 options。

使用它,您可以指定以下內容:

  • 集合的大小。
  • 受限集合中允許的最大文件數。
  • 我們建立的集合是否應該是受限集合(固定大小的集合)。
  • 我們建立的集合是否應該是自動索引的。

語法

以下是建立 MongoDB 集合的語法。

db.createCollection("CollectionName")

示例

以下方法建立一個名為 ExampleCollection 的集合。

> use mydb
switched to db mydb
> db.createCollection("ExampleCollection")
{ "ok" : 1 }
>

類似地,以下是一個使用 createCollection() 方法的選項建立集合的查詢。

>db.createCollection("mycol", { capped : true, autoIndexId : true, size :
6142800, max : 10000 } )
{ "ok" : 1 }
>

使用 python 建立集合

以下 python 示例連線到 MongoDB 中的資料庫 (mydb),並在其中建立一個集合。

示例

from pymongo import MongoClient

#Creating a pymongo client
client = MongoClient('localhost', 27017)

#Getting the database instance
db = client['mydb']

#Creating a collection
collection = db['example']
print("Collection created........")

輸出

Collection created........
廣告