• python mongodb 基本操作封装


    from pymongo import MongoClient


    class Database:
    def __init__(self, address, port, database,user,password):
    self.client = MongoClient(host=address, port=port)
    self.db = self.client.admin
    self.db.authenticate(user, password, mechanism='SCRAM-SHA-1')
    self.db = self.client[database]

    def get_state(self):
    return self.client 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, collection, condition, column=None):
    if self.get_state():
    if column is None:
    return self.db[collection].find(condition)
    else:
    return self.db[collection].find(condition, column)
    else:
    return None
    #查询的结果要打印的话需要用list转一下

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



  • 相关阅读:
    为什么要有handler机制
    安卓五种数据存储的方式
    Activity生命周期详解
    JS的一些简单实例用法
    JSP 中的EL表达式详细介绍
    JSP九大内置对象和四个作用域
    JS实现---图片轮播效果
    实现 鼠标移动到表格的某行 该行换背景 ---myEclipse编写
    JS 菜单收拉样式
    spring中aware接口的
  • 原文地址:https://www.cnblogs.com/fyangq/p/12517190.html
Copyright © 2020-2023  润新知