【Python语言基础】——Python MongoDB 创建集合

Python语言基础——Python MongoDB 创建集合

文章目录

  • Python语言基础——Python MongoDB 创建集合
  • 一、Python MongoDB 创建集合

一、Python MongoDB 创建集合

MongoDB 中的集合与 SQL 数据库中的表相同。
创建集合
要在 MongoDB 中创建集合,请使用数据库对象并指定要创建的集合的名称。
如果它不存在,MongoDB 会创建该集合。
实例
创建名为 “customers” 的集合:
import pymongo
myclient = pymongo.MongoClient(“mongodb://localhost: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(“The collection exists.”)

你可能感兴趣的:(#,python语言基础,mongodb,数据库)