Python 教程
/ 創(chuàng)建集合
創(chuàng)建集合
創(chuàng)建集合
要在 MongoDB 中創(chuàng)建集合,請(qǐng)使用數(shù)據(jù)庫(kù)對(duì)象并指定要?jiǎng)?chuàng)建的集合的名稱。
如果它不存在,MongoDB 會(huì)創(chuàng)建該集合。
實(shí)例
創(chuàng)建名為 "customers" 的集合:
import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] mycol = mydb["customers"]
運(yùn)行實(shí)例
重要提示:在 MongoDB 中,集合在獲得內(nèi)容之前不會(huì)被創(chuàng)建!
在實(shí)際創(chuàng)建集合之前,MongoDB 會(huì)等待直到您已插入文檔。
檢查集合是否存在
請(qǐng)記?。涸?MongoDB 中,集合在獲取內(nèi)容之前不會(huì)創(chuàng)建,因此如果這是您第一次創(chuàng)建集合,則應(yīng)在檢查集合是否存在之前完成下一章(創(chuàng)建文檔)!
您可以通過(guò)列出所有集合來(lái)檢查數(shù)據(jù)庫(kù)中是否存在集合:
實(shí)例
返回?cái)?shù)據(jù)庫(kù)中所有集合的列表:
print(mydb.list_collection_names())
運(yùn)行實(shí)例
或者您可以按名稱檢查特定集合:
實(shí)例
檢查 "customers" 集合是否存在:
collist = mydb.list_collection_names() if "customers" in collist: print("The collection exists.")
運(yùn)行實(shí)例