python 連線mongodb實現增刪改查例項

Tlimited發表於2018-05-30

參考學習路徑:https://www.yiibai.com/mongodb/mongodb_python.html
下面是小案例:

# -*- coding:utf-8 -*-
from pymongo import MongoClient

settings = {
    "ip":'127.0.0.1',   #ip
    "port":27017,           #埠
    "db_name" : "mydb",    #資料庫名字,沒有則自動建立
    "set_name" : "test_set"   #集合名字,沒有則自動建立
}

class MyMongoDB(object):
    def __init__(self):
        try:
            self.conn = MongoClient(settings["ip"], settings["port"])
        except Exception as e:
            print(e)
        self.db = self.conn[settings["db_name"]]
        self.my_set = self.db[settings["set_name"]]
    #插入
    def insert(self,dic):
        self.my_set.insert(dic)
        print("插入成功")
    #更新
    def update(self,dic,newdic):
        self.my_set.update(dic,newdic)
        print("更新成功")
    #刪除
    def delete(self,dic):
        self.my_set.remove(dic)
        print("刪除成功")
    #查詢
    def dbFind(self,dic):
        data = self.my_set.find(dic)
        for result in data:
            print(result)
        print("查詢成功")
    #查詢全部
    def findAll(self):
        # 查詢全部
        for i in self.my_set.find():
            print(i)

if __name__ == "__main__":
    dic = {"name": "tom", "age": 18}
    mongo = MyMongoDB()

    mongo.insert(dic)
    mongo.findAll()

    mongo.update({"name": "tom"}, {"$set": {"age": "25"}})
    mongo.dbFind({"name": "tom"})

    mongo.delete({"name": "tom"})
    mongo.findAll()

執行結果:

插入成功
{'name': 'lisi', '_id': ObjectId('5b0ce85ef869ba31d0c3abc7'), 'age': 20}
{'name': 'tom', '_id': ObjectId('5b0e4a4ef869ba2c84890cb0'), 'age': 18}
更新成功
{'name': 'tom', '_id': ObjectId('5b0e4a4ef869ba2c84890cb0'), 'age': '25'}
查詢成功
刪除成功
{'name': 'lisi', '_id': ObjectId('5b0ce85ef869ba31d0c3abc7'), 'age': 20}

相關文章