Python存連線MongoDB
阿新 • • 發佈:2018-11-02
step1:安裝pymongo庫
pip install pymongo
step2:使用pymongo模組連線mongoDB資料庫
#coding=utf-8
from pymongo import MongoClient
#建立MongoDB資料庫連線
client = MongoClient('localhost',27017)
#連線所需資料庫,testdb為資料庫名(沒有則新建)
db=client.testdb
#連線所用集合,也就是我們通常所說的表,test為表名(沒有則新建)
collection=db.test
#接下里就可以用collection來完成對資料庫表的一些操作
#查詢集合中所有資料,返回列表
for item in collection.find():
print(item)
#查詢集合中單條資料
print collection.find_one()
#向集合中插入資料
collection.insert({name:'Tom',age:25,addr:'Cleveland'})
#更新集合中的資料,第一個大括號裡為更新條件,第二個大括號為更新之後的內容
collection.update({Name:'Tom'},{Name:'Tom',age:18})
#刪除name=panghu的全部記錄
my_set.remove( {'name': 'panghu'})
#刪除name=lisi的某個id的記錄(按照id刪除資料)
id = my_set.find_one({"name":"zhangsan"})["_id"]
my_set.remove(id)
#刪除集合collection中的所有資料
collection.remove()
#刪除集合collection
collection.drop()