Python操作Mongodb的用法,并将其简单封装起来

Pymongo

pip install pymongo

pymongo是python的mongodb client,这里将其使用方法封装成class,并提供单元测试用以展示其基本用法。直接看代码。

Code list

# mongodb database
from pymongo import MongoClient


class Database(object):
    def __init__(self, address, port, database):
        self.conn = MongoClient(host=address, port=port)
        self.db = self.conn[database]

    def get_state(self):
        return self.conn is not None and self.db is not None

    def insert_one(self, collection, data):
        if self.get_state():
            ret = self.db[collection].insert_one(data)
            return ret.inserted_id
        else:
            return ""

    def insert_many(self, collection, data):
        if self.get_state():
            ret = self.db[collection].insert_many(data)
            return ret.inserted_id
        else:
            return ""

    def update(self, collection, data):
        # data format:
        # {key:[old_data,new_data]}
        data_filter = {}
        data_revised = {}
        for key in data.keys():
            data_filter[key] = data[key][0]
            data_revised[key] = data[key][1]
        if self.get_state():
            return self.db[collection].update_many(data_filter, {"$set": data_revised}).modified_count
        return 0

    def find(self, col, condition, column=None):
        if self.get_state():
            if column is None:
                return self.db[col].find(condition)
            else:
                return self.db[col].find(condition, column)
        else:
            return None

    def delete(self, col, condition):
        if self.get_state():
            return self.db[col].delete_many(filter=condition).deleted_count
        return 0


if __name__ == '__main__':
    # unit test
    import time
    import random

    db = Database("127.0.0.1", 27017, "hellofly")
    print(db.get_state())
    print(db.delete("ut", {}))
    print(time.time())
    start_time = int(time.time() * 1e6)
    for i in range(100):
        t = int(time.time() * 1e6)
        db.insert_one("ut", {"username": str(t),
                             "timestamp": t,
                             "password": "aaaa",
                             "telephone": str(random.random() * 1000000)})
    print("deleted count: ", db.delete("ut", {"timestamp": {"$gt": start_time + 500}}))
    print(db.find("ut", {}).count())
    print(db.update("ut", {"password": ["aaaa", "bbbb"]}))
    print(db.find("ut", {}, {"password": 1, "username": 1}).count())
  • 1
    点赞
  • 0
    评论
  • 9
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

打赏
文章很值,打赏犒劳作者一下
相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页

打赏

WotChin

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者