python和mongodb簡單交互
阿新 • • 發佈:2018-12-19
mage exce func word key exceptio client 一個 con
1.安裝pymongo:
pip3 install pymongo
2.pymongo的簡單用法:
# /usr/bin/env python3
import pymongo
class Mymongo(object):
def __init__(self, host, port=27017):
try:
self.conn = pymongo.MongoClient(host=host, port=port)
except Exception as e:
print("連接失敗", e)
else:
print(‘連接成功‘)
def add(self, p_dict):
res = self.conn.testdb.testcol.insert(p_dict) # insert需要傳入字典
if res:
print(‘插入成功‘)
def show(self):
res = self.conn.testdb.testcol.find() # find()返回一個可叠代對象
for i in res:
print(i)
def mod(self, before, after): # 需要傳入字典
res = self.conn.testdb.testcol.update(before, after)
if res:
print("修改成功", res)
def rem(self, p_dict):
res = self.conn.testdb.testcol.delete_one(p_dict)
if res:
print(‘刪除成功‘)
if __name__ == "__main__":
mymongo = Mymongo(‘192.168.26.135‘)
mymongo.add({"name": ‘Tom‘})
mymongo.show()
mymongo.mod({"name": ‘Tom‘}, {"name": ‘Jerry‘})
mymongo.show()
mymongo.rem({"name": ‘Jerry‘})
mymongo.show()
python和mongodb簡單交互