Python MongoDB 创建集合

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 Numpy 教程
  • Python MySQL 教程
  • MongoDB 教程
  • SciPy 教程
  • Python 教程

Python MongoDB 创建集合

2019年6月10日

 意见反馈

MongoDB中的集合与SQL数据库中的表类似。

创建集合

要在MongoDB中创建集合,使用数据库对象,传入要创建的集合名称。

如果没有同名集合存在,MongoDB将创建它。

示例

创建一个名为“customers”的集合:

import pymongo

myclient = pymongo.MongoClient("mongodb://192.168.31.154:27017/")
mydb = myclient["mydatabase"]

mycol = mydb["customers"]

复制

重要提示: MongoDB中,在添加内容之前不会真正创建集合!

MongoDB会等到插入了文档之后,才真正创建集合。

检查集合是否存在

记住: MongoDB中,只有在添加内容时才会创建集合,如果这是集合第一次创建,应该先添加内容(下一章,创建文档),再检查集合是否存在!

检查数据库中是否存在某个集合,我们可以列出数据库中所有集合:

示例

返回数据库中所有集合:

print(mydb.list_collection_names())

复制

或者你可以检查某个集合是否存在:

示例

检查“customers”集合是否存在:

collist = mydb.list_collection_names()
if "customers" in collist:
  print("这个集合存在")

复制


Doc navigation

← Python MongoDB 创建数据库

你可能感兴趣的:(python,Python,教程)