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引用模块和查找模块路径
模块间相互独立相互引用是任何一种编程语言的基础能力.对于"模块"这个词在各种编程语言中或许是不同的,但我们可以简单认为一个程序文件是一个模块,文件里包含了类或者方法的定义.对于编译 ...
随机推荐
- 关于如何在 Unity 的 UI 菜单中默认创建出的控件 Raycast Target 属性默认为 false
关于如何在 Unity 的 UI 菜单中默认创建出的控件 Raycast Target 属性默认为 false 我们在 Unity 中通过 UI 菜单创建的各种控件,比如 Text, Image 等, ...
- chomd 1+2+4
2,把目录 /tmp/sco修改为可写可读可执行 chmod 777 /tmp/sco 要修改某目录下所有的文件夹属性为可写可读可执行 chmod 777 * 把文件夹名称用*来代替就可以了 要修改/ ...
- 应用程序首选项(application preference)及数据存储
应用程序首选项(application preference)用来存储用户设置,考虑以下案例: a. 假设有一款MP3播放器程序,当用户调节了音量,当下次运行该程序时,可能希望保持上一次调节的音量值. ...
- 在eclipse中安装TestNG
https://www.cnblogs.com/baixiaozheng/p/4989856.html 1.可借助Eclipse的Marketplace来安装TestNG Eclipse插件 a.打开 ...
- 【BZOJ 3106】 3106: [cqoi2013]棋盘游戏 (对抗搜索)
3106: [cqoi2013]棋盘游戏 Time Limit: 10 Sec Memory Limit: 128 MBSubmit: 544 Solved: 233 Description 一个 ...
- 【BZOJ 4148】 4148: [AMPPZ2014]Pillars (乱搞)
4148: [AMPPZ2014]Pillars Time Limit: 5 Sec Memory Limit: 256 MBSec Special JudgeSubmit: 100 Solve ...
- 【BZOJ 2654】 MST
2654: tree Description 给你一个无向带权连通图,每条边是黑色或白色.让你求一棵最小权的恰好有need条白色边的生成树. 题目保证有解. Input 第一行V,E,need分别表示 ...
- herbinate 数据库乱码
改jdbc或者hibernate编码: jdbc:mysql://127.0.0.1:3306/db?useUnicode=true&characterEncoding=utf-8 ...
- 2015 UESTC 数据结构专题H题 秋实大哥打游戏 带权并查集
秋实大哥打游戏 Time Limit: 1 Sec Memory Limit: 256 MB 题目连接 http://acm.uestc.edu.cn/#/contest/show/59 Descr ...
- c语言把mysql数据库语句和变量封装为一个语句
我有一个语句 sql = "insert into talbe_name values(name,age)" 其中name和age两个变量根据外面的输入来确定,有两种方法 1: ...