Python mongoHelper模块
#!/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模块的更多相关文章
- Python标准模块--threading
1 模块简介 threading模块在Python1.5.2中首次引入,是低级thread模块的一个增强版.threading模块让线程使用起来更加容易,允许程序同一时间运行多个操作. 不过请注意,P ...
- Python的模块引用和查找路径
模块间相互独立相互引用是任何一种编程语言的基础能力.对于“模块”这个词在各种编程语言中或许是不同的,但我们可以简单认为一个程序文件是一个模块,文件里包含了类或者方法的定义.对于编译型的语言,比如C#中 ...
- Python Logging模块的简单使用
前言 日志是非常重要的,最近有接触到这个,所以系统的看一下Python这个模块的用法.本文即为Logging模块的用法简介,主要参考文章为Python官方文档,链接见参考列表. 另外,Python的H ...
- Python标准模块--logging
1 logging模块简介 logging模块是Python内置的标准模块,主要用于输出运行日志,可以设置输出日志的等级.日志保存路径.日志文件回滚等:相比print,具备如下优点: 可以通过设置不同 ...
- python基础-模块
一.模块介绍 ...
- python 安装模块
python安装模块的方法很多,在此仅介绍一种,不需要安装其他附带的pip等,python安装完之后,配置环境变量,我由于中英文分号原因,环境变量始终没能配置成功汗. 1:下载模块的压缩文件解压到任意 ...
- python Queue模块
先看一个很简单的例子 #coding:utf8 import Queue #queue是队列的意思 q=Queue.Queue(maxsize=10) #创建一个queue对象 for i in ra ...
- python logging模块可能会令人困惑的地方
python logging模块主要是python提供的通用日志系统,使用的方法其实挺简单的,这块就不多介绍.下面主要会讲到在使用python logging模块的时候,涉及到多个python文件的调 ...
- Python引用模块和查找模块路径
模块间相互独立相互引用是任何一种编程语言的基础能力.对于"模块"这个词在各种编程语言中或许是不同的,但我们可以简单认为一个程序文件是一个模块,文件里包含了类或者方法的定义.对于编译 ...
随机推荐
- thinkphp5.0安装
ThinkPHP5的环境要求如下: PHP >= 5.4.0 PDO PHP Extension MBstring PHP Extension CURL PHP Extension 严格来说,T ...
- 几何:pick定理详解
一.概念 假设P的内部有I(P)个格点,边界上有B(P)个格点,则P的面积A(P)为:A(P)=I(P)+B(P)/2-1. 二.说明 Pick定理主要是计算格点多边形(定点全是格点的不自交图形)P的 ...
- [BZOJ4408&&BZOJ4299][FJOI2016 && Codechef]神秘数&&FRBSUM(主席树)
4299: Codechef FRBSUM Time Limit: 10 Sec Memory Limit: 128 MBSubmit: 550 Solved: 351[Submit][Statu ...
- Mac 下解压NDK .bin文件
Mac Android Studio 开发NDK,首先下载NDK文件----->android-ndk-r10d-darwin-x86_64.bin 1.打开终端获取文件权限 chmod a+x ...
- php正则给图片提取/替换/添加alt标签的正则代码
有的时候我们需要对富文本编辑器的内容做一些处理,例如图片的alt标签.百度的富文本编辑器添加的图片就是没有的,那么我们要添加就必须使用正则了,下面一起来看看如何实现吧. $preg = "/ ...
- bzoj 1086 树分块
将树分成一些块,做法见vfleaking博客. /************************************************************** Problem: 108 ...
- 内功心法 -- java.util.LinkedList<E> (3)
写在前面的话:读书破万卷,编码如有神--------------------------------------------------------------------下文主要对java.util ...
- [转]Android应用中返回键的监听及处理
用户在点击手机的返回按钮时,默认是推出当前的activty,但是有时用户不小心按到返回,所以需要给用户一个提示,这就需要重写onkeydown事件,实现的效果如下: 标签: Android ...
- HTML5 元素拖动 - 实现元素左右拖动, 或更改自身排序
1.拖放(Drag 和 drop)是 HTML5 标准的组成部分. 拖放是一种常见的特性,即抓取对象以后拖到另一个位置.在 HTML5 中,拖放是标准的一部分,任何元素都能够拖放. 浏览器支持:Int ...
- 典型案例收集-使用OpenVPN连通多个机房内网(转)(静态路由)
说明: 1.这篇文章主要是使用静态路由表实现的多个机房通过VPN连接后的子网机房互通. 2.OpenVPN使用的是桥接模式(server-bridge和dev tap),这个是关键点,只有这样设置才可 ...