#!/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)

最新文章

  1. B/S结构的流程简单概述
  2. 用ADO.NET存入数据库
  3. Tomcat配置文件server.xml详解
  4. Codeforces 720A. Closing ceremony
  5. VMware12 安装 CentOS 6.5 64位
  6. Mybatis+struts2+spring整合
  7. iOS开发——语法OC篇&amp;Block回顾
  8. win7常用快捷键
  9. 浅析JAVA设计模式(三)
  10. Js冒泡事件和捕获事件
  11. .net FrameWork4.0安装未成功
  12. find the safest road--hdu1596
  13. 【指数型母函数+非递归快速幂】【HDU2065】&quot;红色病毒&quot;问题
  14. 好用的侧边栏菜单/面板jQuery插件
  15. chrome开发工具指南(十一)
  16. [Mysql]备份同库中一张表的历史记录 insert into ..select
  17. 小米Max 2获取ROOT超级权限的经验
  18. 汲取营养的blog专栏
  19. Nginx log日志参数详解
  20. boost::function 介绍

热门文章

  1. PHP 5.4 内置 web 服务器
  2. windows下重置mysql的root密码方法介绍(转)
  3. pycharm中在andconda环境中配置pyqt环境
  4. NOIP2012 D2 T2借教室
  5. 利用linux判断elf文件是64位还是32位
  6. SSM demo :投票系统
  7. django 编码错误
  8. FastReport.Net使用:[22]地图(Map)控件
  9. 1 Spring4 之环境搭建和HelloWorld
  10. PHP -- 类和对象基础入门