#!/usr/bin/env python3
# -*- coding: utf-8 -*- '''
Defines a MongoOperator class and allows you to manipulate
the Mongodb Database.(insert, delete, update, select...)
''' from pymongo import MongoClient, errors class MongoOperator(object):
'''
MongoOperator class allows you to manipulate the Mongodb
Database. :Usage: ''' def __init__(self, **login):
'''
The constructor of Mongodb class. Creates an instance of MongoOperator and starts connecting
to the Mongodb server's test database. :Args:
- **login - Keyword arguments used in MongoClient() and
Database.authenticate() functions in order to connect to
test database and authenticate clients (including host,
user, password...)
'''
# connectin to test database:
self.__db = MongoClient(login['host'], login['port'])[login['database']]
self.__db.authenticate(login['user'], login['password']) def insertOne(self, document, *, collection='test'):
'''
Insert one document into collection named test in Mongodb
database. :Args:
- document - dict. One document to execute insertion.
- colletion - str. Named keyword argument used to specify
which collection to insert.
'''
# select a collection to execute insert operation:
test = self.__db[collection]
# insert transaction begin:
try:
result = test.insert_one(document)
print('>> MongoDB insertOne operation success.')
print('>> Inserted ID:',result.inserted_id)
except errors.PyMongoError as e:
print('>> MongoDB insertOne operation fail:', type(e), e.details)
# add exception logging function later: def insertMany(self, *documents, collection='test'):
'''
Insert many document into collection named test in Mongodb
database. :Args:
- *documents - list of document in variable arguments. Many
documents(require more than one) to execute insertion.
- colletion - str. Named keyword argument used to specify
which collection to insert.
'''
# params check:
if len(documents) <= 0:
raise ValueError("Documents can't be empty.")
elif len(documents) <= 1:
raise TypeError("MongoDB insertMany Operation need more then one record.")
# select a collection to execute insert operation:
test = self.__db[collection]
# insert transaction begin:
try:
results = test.insert_many(documents)
print('>> MongoDB insertMany operation success.')
print('>> Inserted IDs:', results.inserted_ids)
except errors.PyMongoError as e:
print('>> MongoDB insertMany operation fail:', type(e), e.details)
# add exception logging function later: def delete(self, filter, *, collection='test', many=False):
'''
Delete a single or many documents matching the filter
from collection test in Mongodb database. :Args:
- filter - A query that matches the document to delete.
- many - bool. Named keyword argument. If True, execute
delete_many(); If not, then execute delete_one().
- colletion - str. Named keyword argument used to specify
which collection to delete.
'''
# select a collection to execute delete operation:
test = self.__db[collection]
# delete transaction begin:
try:
results = test.delete_many(filter) if many else test.delete_one(filter)
# waiting for test:
print('>> MongoDB delete operation success.')
print('>> Delete Information:', results.raw_result)
print('>> Delete document count:', results.deleted_count)
except errors.PyMongoError as e:
print('>> MongoDB delete operation fail:', type(e), e)
# add exception logging function later: def select(self, filter=None, *, collection='test', many=False):
'''
Select a single or many documents matching the filter
from collection test in Mongodb database. :Args:
- filter - A query that matches the document to select.
- many - bool. Named keyword argument. If True, execute
find(); If not, then execute find_one().
- colletion - str. Named keyword argument used to specify
which collection to select. :Returns:
- results - If select success, returns a Cursor instance for
navigating select results. If not, returns None.
'''
# selcet a collection to execute select operation:
test = self.__db[collection]
# select transaction begin:
try:
results = test.find(filter, no_cursor_timeout=True) if many else test.find_one(filter)
# waiting for test:
print('>> MongoDB select operation success.', type(results))
except errors.PyMongoError as e:
print('>> MongoDB select operation fail:', type(e), e)
results = None
# add exception logging function later:
finally:
return results def update(self, filter, update, *, collection='test', many=False):
'''
Update a single or many documents matching the filter
from collection test in Mongodb database. :Args:
- filter - A query that matches the document to update.
- update - The modifications to apply.
- many - bool. Named keyword argument. If True, execute
update_many(); If not, then execute update_one().
- colletion - str. Named keyword argument used to specify
which collection to update.
''' # select a collection to execute update operation:
test = self.__db[collection]
# update transaction begin:
try:
results = test.update_many(filter, update) if many else test.update_one(filter, update)
# waiting for test:
print('>> MongoDB update operation success:', type(results), results)
print('>> Update Information:', results.raw_result)
print('>> Matching Counts:', results.matched_count)
print('>> Modified Counts:', results.modified_count)
except errors.PyMongoError as e:
print('>> MongoDB update operation fail:', type(e), e)
# add exception logging function later: # test:
if __name__ == '__main__': logIn = {'host': 'localhost', 'port': 27017, 'database': 'test',
'user': '', 'password': ''}
documents = [{'id': 1, 'name': 'zty'}, {'id': 2, 'name': 'zzz'}, {'id': 3, 'name': 'ttt'}]
document = {'id': 1, 'name': 'zty'} mongoHandler = MongoOperator(**logIn)
for document in mongoHandler.select({'name': 'zty'}, many=True):
print(document) mongoHandler.insertOne(document)
print(mongoHandler.select({'name': 'zty'})) mongoHandler.insertMany(*documents)
for document in mongoHandler.select({'name': 'zty'}, many=True):
print(document) mongoHandler.update({'name': 'zty'}, {'$set': {'name': 'yyy'}}, many=True)
for document in mongoHandler.select({'name': 'zzz'}, many=True):
print(document) mongoHandler.delete({'name': 'zzz'}, many=True)
for document in mongoHandler.select({'name': 'zzz'}, many=True):
print(document)

Python mongoHelper模块的更多相关文章

  1. Python标准模块--threading

    1 模块简介 threading模块在Python1.5.2中首次引入,是低级thread模块的一个增强版.threading模块让线程使用起来更加容易,允许程序同一时间运行多个操作. 不过请注意,P ...

  2. Python的模块引用和查找路径

    模块间相互独立相互引用是任何一种编程语言的基础能力.对于“模块”这个词在各种编程语言中或许是不同的,但我们可以简单认为一个程序文件是一个模块,文件里包含了类或者方法的定义.对于编译型的语言,比如C#中 ...

  3. Python Logging模块的简单使用

    前言 日志是非常重要的,最近有接触到这个,所以系统的看一下Python这个模块的用法.本文即为Logging模块的用法简介,主要参考文章为Python官方文档,链接见参考列表. 另外,Python的H ...

  4. Python标准模块--logging

    1 logging模块简介 logging模块是Python内置的标准模块,主要用于输出运行日志,可以设置输出日志的等级.日志保存路径.日志文件回滚等:相比print,具备如下优点: 可以通过设置不同 ...

  5. python基础-模块

    一.模块介绍                                                                                              ...

  6. python 安装模块

    python安装模块的方法很多,在此仅介绍一种,不需要安装其他附带的pip等,python安装完之后,配置环境变量,我由于中英文分号原因,环境变量始终没能配置成功汗. 1:下载模块的压缩文件解压到任意 ...

  7. python Queue模块

    先看一个很简单的例子 #coding:utf8 import Queue #queue是队列的意思 q=Queue.Queue(maxsize=10) #创建一个queue对象 for i in ra ...

  8. python logging模块可能会令人困惑的地方

    python logging模块主要是python提供的通用日志系统,使用的方法其实挺简单的,这块就不多介绍.下面主要会讲到在使用python logging模块的时候,涉及到多个python文件的调 ...

  9. Python引用模块和查找模块路径

    模块间相互独立相互引用是任何一种编程语言的基础能力.对于"模块"这个词在各种编程语言中或许是不同的,但我们可以简单认为一个程序文件是一个模块,文件里包含了类或者方法的定义.对于编译 ...

随机推荐

  1. brpc初探

    因为最近在看一个内部开源代码,看到了braft.braft又依赖于brpc.于是就看了相关的文档,打算接下来试一把. 这里引用下gejun大佬在知乎上的回答(https://www.zhihu.com ...

  2. NetBIOS主机名扫描工具nbtscan

    NetBIOS主机名扫描工具nbtscan   NetBIOS主机名是NetBIOS协议为主机分配的名称.通过NetBIOS主机名,系统可以利用WINS服务.广播及Lmhost文件等多种模式将NetB ...

  3. RxSwift 系列(九)

    前言 看完本系列前面几篇之后,估计大家也还是有点懵逼,本系列前八篇也都是参考RxSwift官方文档和一些概念做的解读.上几篇文章概念性的东西有点多,一时也是很难全部记住,大家脑子里面知道有这么个概念就 ...

  4. 深入理解javascript作用域系列第一篇

    前面的话 javascript拥有一套设计良好的规则来存储变量,并且之后可以方便地找到这些变量,这套规则被称为作用域.作用域貌似简单,实则复杂,由于作用域与this机制非常容易混淆,使得理解作用域的原 ...

  5. 【BZOJ 4104】 4104: [Thu Summer Camp 2015]解密运算 (智商)

    4104: [Thu Summer Camp 2015]解密运算 Time Limit: 10 Sec  Memory Limit: 512 MBSubmit: 370  Solved: 237 De ...

  6. codeforces 220 C. Game on Tree

    题目链接 codeforces 220 C. Game on Tree 题解 对于 1节点一定要选的 发现对于每个节点,被覆盖切选中其节点的概率为祖先个数分之一,也就是深度分之一 代码 #includ ...

  7. BZOJ4554 HEOI2016游戏

    网络流. 我一开始傻傻的将每条边与每一列连边,边权为联通块树,但是这样做是错的因为我们就在跑网络流中会忽略掉边和列的关系. 我们在做网络流题时一定要注意题目中给出的限制条件,一定要以限制条件建图!!! ...

  8. bzoj 5294: [Bjoi2018]二进制

    Description pupil 发现对于一个十进制数,无论怎么将其的数字重新排列,均不影响其是不是333 的倍数.他想研究对于二进 制,是否也有类似的性质.于是他生成了一个长为n 的二进制串,希望 ...

  9. [BZOJ5010][FJOI2017]矩阵填数(状压DP)

    5010: [Fjoi2017]矩阵填数 Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 90  Solved: 45[Submit][Status][ ...

  10. 2018/3/13 noiρ[rəʊ]模拟赛 125分

    T1 60分暴力,水分也不会水,打表也不会打,正解是不可能写正解的,这辈子都写不出来正解的,虽然是zz题但是也拿不到分这样子. 正解:(啥?正解是sb组合数?这都他娘的想不到,真鸡儿丢人我自杀吧.) ...