Python MongoDB - 创建集合



MongoDB 中的集合保存了一组文档,它类似于关系数据库中的表。

你可以使用 createCollection() 方法创建一个集合。此方法接受一个代表要创建的集合名称的字符串值,以及一个选项(可选)参数。

使用此方法你可以指定以下内容 −

  • 集合的 大小

  • 受限集合中允许的文档的 最大 数量。

  • 我们创建的集合是否应该是受限集合(固定大小的集合)。

  • 我们创建的集合是否应该是自动编制的索引。

语法

以下是 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........
广告
© . All rights reserved.