#!/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. java变量的命名使用规则

    1.环境变量通常是指在操作系统中,用来指定操作系统运行时需要的一些参数 2.变量名以字母.下划线或者美元符(4上面的¥)开头,不能以数字开头,后面跟字母.下划线.美元符.数字,变量名对大小写敏感,无长 ...

  2. 【BZOJ 2437】 2437: [Noi2011]兔兔与蛋蛋 (博弈+二分图匹配**)

    未经博主同意不得转载 2437: [Noi2011]兔兔与蛋蛋 Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 693  Solved: 442 Des ...

  3. Codeforces 1037 H. Security

    \(>Codeforces \space 1037\ H. Security<\) 题目大意 : 有一个串 \(S\) ,\(q\) 组询问,每一次给出一个询问串 \(T\) 和一个区间 ...

  4. [BZOJ4416][SHOI2013]阶乘字符串(子集DP)

    怎么也没想到是子集DP,想到了应该就没什么难度了. 首先n>21时必定为NO. g[i][j]表示位置i后的第一个字母j在哪个位置,n*21求出. f[S]表示S的所有全排列子序列出现的最后末尾 ...

  5. UESTC 2015dp专题 F 邱老师看电影 概率dp

    邱老师看电影 Time Limit: 20 Sec  Memory Limit: 256 MB 题目连接 http://acm.uestc.edu.cn/#/contest/show/65 Descr ...

  6. input输入框限制输入英文,数字,汉字

    <h1>js验证输入框内容</h1><br /><br /> 只能输入英文<input type="text" onkeyup ...

  7. 用rem设置文字大小

    一.px与em 用px设置文字大小是再正常不过的事情,比如 html {font-size: 12px;} 随处可见的在设置width.height使用px,这也是细致稳妥的设置方法,这样做的缺点在于 ...

  8. 单向可控硅(SCR)双向可控硅(TRIAC)

    双向可控硅工作原理与特点 从理论上来讲,双向可控硅可以说是有两个反向并列的单向可控硅组成,理解单向可控硅的工作原理是理解双向可控硅工作原理的基础 单向可控硅 单向可控硅也叫晶闸管,其组成结构图如图1- ...

  9. Spring Bean InitializingBean和DisposableBean实例

    在Spring中,InitializingBean和DisposableBean是两个标记接口,为Spring执行时bean的初始化和销毁某些行为时的有用方法. 对于Bean实现 Initializi ...

  10. 图形图像的绘制 GandyDraw

    源代码:下载地址, http://pan.baidu.com/s/1eQIzj3c 具体在下面的这个地方找,