zoukankan      html  css  js  c++  java
  • 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



  • 相关阅读:
    Java集合类总结 (三)
    Java集合类总结 (二)
    Java集合类总结 (一)
    发布方配ASP.NET网站服务器
    Ubuntu重启搜狗输入法
    常用期刊检索
    latex 写大论文图目录中图注过长解决方案
    understanding backpropagation
    Ubuntu安装Adobe Reader
    【转】pdf文件自动切白边
  • 原文地址:https://www.cnblogs.com/fyangq/p/12517190.html
Copyright © 2011-2022 走看看