Python 数据访问教程

Python 数据访问 - 主页

Python MySQL

Python MySQL - 简介 Python MySQL - 数据库连接 Python MySQL - 创建数据库 Python MySQL - 创建表 Python MySQL - 插入数据 Python MySQL - 选择数据 Python MySQL - Where 子句 Python MySQL - 排序 Python MySQL - 更新表 Python MySQL - 删除数据 Python MySQL - 删除表 Python MySQL - Limit 子句 Python MySQL - 连接 Python MySQL - 游标对象

Python PostgreSQL

Python PostgreSQL - 简介 Python PostgreSQL - 数据库连接 Python PostgreSQL - 创建数据库 Python PostgreSQL - 创建表 Python PostgreSQL - 插入数据 Python PostgreSQL - 选择数据 Python PostgreSQL - Where 子句 Python PostgreSQL - 排序 Python PostgreSQL - 更新表 Python PostgreSQL - 删除数据 Python PostgreSQL - 删除表 Python PostgreSQL - Limit 子句 Python PostgreSQL - 连接 Python PostgreSQL - 游标对象

Python SQLite

Python SQLite - 简介 Python SQLite - 建立连接 Python SQLite - 创建表 Python SQLite - 插入数据 Python SQLite - 选择数据 Python SQLite - Where 子句 Python SQLite - 排序 Python SQLite - 更新表 Python SQLite - 删除数据 Python SQLite - 删除表 Python SQLite - Limit 子句 Python SQLite - 连接 Python SQLite - 游标对象

Python MongoDB

Python MongoDB - 简介 Python MongoDB - 创建数据库 Python MongoDB - 创建集合 Python MongoDB - 插入文档 Python MongoDB - 查找 Python MongoDB - 查询 Python MongoDB - 排序 Python MongoDB - 删除文档 Python MongoDB - 删除集合 Python MongoDB - 更新 Python MongoDB - Limit 子句

Python 数据访问资源

Python 数据访问 - 快速指南 Python 数据访问 - 有用资源 Python 数据访问 - 讨论


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

#创建 pymongo 客户端
client = MongoClient('localhost', 27017)

#获取数据库实例
db = client['mydb']

#创建集合
collection = db['example']
print("Collection created........")
 

输出

Collection created........