Python 的MongoDB驱动 pymongo ,使用pip Install pymongo安装即可

最近发现网上的很多实例已经过时了,在此自我探究记录下来。

编写一个接口类来支持MongoDB的基本操作(连接数据库,添加文档,删除文档,更新文档,读取文档),代码基本功能已通过测试,但难免还有一些BUG,如果有,望指正,谢谢。

测试环境 Centos7 Python3.6.3

from pymongo import MongoClient
from bson.objectid import ObjectId
import syslog class MongoDriver(object):
def __init__(self, ip='localhost', port=27017):
"""Init MongoDB Option.
wait more option added.
"""
self.ip = ip
self.port = port def init_connect(self):
""" Connect To MongoDB.
return True or False.
"""
try:
self.client = MongoClient(self.ip, self.port)
except Exception as e:
syslog.syslog(syslog.LOG_ERR, "MongoClient Connect failed : " + str(e))
return False
else:
return True def init_db(self, db):
""" Connect To MongoDB -> DB.
return True or False.
"""
try:
self.db = self.client[db]
except Exception as e:
syslog.syslog(syslog.LOG_ERR, "MongoClient Getdb {db} failed:".format(db=db) + str(e))
self.db = ""
return False
else:
return True def init_collection(self, collection):
""" Connect To MongoDB -> DB -> collection.
return True or False.
""" try:
self.collection = self.db[collection]
except Exception as e:
syslog.syslog(syslog.LOG_ERR,\
"MongoClient GetCollection {collection} failed:".format(collection=collection) + str(e))
self.collection = ""
return False
else:
return True
def format_id(self, object_id):
"""
Format Id.
return a dict.
"""
return {'_id': ObjectId(object_id)} def insert_one(self, document):
"""
Insert One Document To MongoDB.
document must be a dict.
return a dict with document's inserted_id or False when Error occured
"""
if not isinstance(document, dict):
raise TypeError
try:
return self.collection.insert_one(document).inserted_id
except Exception as e:
syslog.syslog(syslog.LOG_ERR,\
"MongoClient Insert_one {document} failed:".format(document=document) + str(e))
return False def insert_many(self, documents):
"""
Insert Many Documents To MongoDB.
documents must be a list.
eveny document must be a dict.
return a list with documents's inserted_ids or False when Error occured
"""
if not isinstance(documents, list):
raise TypeError
for document in documents:
if not isinstance(document, dict):
raise TypeError
try:
return self.collection.insert_many(documents).inserted_ids
except Exception as e:
syslog.syslog(syslog.LOG_ERR,\
"MongoClient insert_many {document} failed:".format(document=document) + str(e))
return False def find_one_by_id(self, object_id):
"""
Find Result By Object_id.
Return a dict with a document
"""
if not isinstance(object_id, str):
raise TypeError
try:
return self.collection.find_one(self.format_id(object_id)) except Exception as e:
syslog.syslog(syslog.LOG_ERR,\
"MongoClient find_by_id {id} failed:".format(id=object_id) + str(e))
return False def find_one_by_param(self, kws):
"""
Find Document By Object_id.
return a dict with a document
"""
if not isinstance(kws, dict):
raise TypeError
try:
return self.collection.find_one(kws)
except Exception as e:
syslog.syslog(syslog.LOG_ERR,\
"MongoClient find_by_param {kws} failed:".format(kws=kws) + str(e))
return False def find_many_by_param(self, kws):
"""
Find Document By Object_id.
return a cursor object with a or many document
"""
if not isinstance(kws, dict):
raise TypeError
try:
return self.collection.find(kws)
except Exception as e:
syslog.syslog(syslog.LOG_ERR,\
"MongoClient find_by_param {kws} failed:".format(kws=kws) + str(e))
return False def update_one_by_id(self, object_id, kws):
"""
Update Document By Object_id.
Return True or False
"""
if not isinstance(kws, dict) :
raise TypeError try:
self.collection.update_one(self.format_id(object_id), {"$set": kws}, upsert=False)
except Exception as e:
syslog.syslog(syslog.LOG_ERR,\
"MongoClient update_one_by_id failed:" + str(e))
return False
else:
return True
def update_one_by_param(self, condition, kws):
"""
Update Document By Object_id.
Return True or False
"""
if not isinstance(condition, dict) or not isinstance(kws, dict):
raise TypeError
try:
self.collection.update_one(condition, {"$set": kws}, upsert=False)
except Exception as e:
syslog.syslog(syslog.LOG_ERR,\
"MongoClient update_one_by_param failed:" + str(e))
return False
else:
return True def update_many_by_param(self, condition, kws):
"""
Update Document By Object_id.
Return True or False
"""
if not isinstance(condition, dict) or not isinstance(kws, dict):
raise TypeError
try:
self.collection.update_many(condition, {"$set": kws}, upsert=False)
except Exception as e:
syslog.syslog(syslog.LOG_ERR,\
"MongoClient update_many_by_param failed:" + str(e))
return False
else:
return True def remove_all(self):
"""
Remove all documents from a collection .
Return True or False
"""
try:
self.collection.remove()
except Exception as e:
syslog.syslog(syslog.LOG_ERR,\
"MongoClient remove_all failed:" + str(e))
return False
else:
return True def remove_documents(self, kws):
"""
Remove some documents from a collection .
Return True or False
"""
if not isinstance(kws, dict):
raise TypeError
try:
self.collection.remove(kws)
except Exception as e:
syslog.syslog(syslog.LOG_ERR,\
"MongoClient remove_documents failed:" + str(e))
return False
else:
return True

Python 驱动 MongoDB 示例(PyMongo)的更多相关文章

  1. Windows平台下为Python添加MongoDB支持PyMongo

    到Python官网下载pymongo-2.6.3.win-amd64-py2.7.exe 安装pymongo-2.6.3.win-amd64-py2.7.exe 参照官方的用例进行测试 打开命令提示符 ...

  2. 2.1 python使用MongoDB 示例代码

    import pymongo client = pymongo.MongoClient('localhost', 27017) # MongoDB 客户端 walden = client['walde ...

  3. CentOS平台下为Python添加MongoDB支持PyMongo

    下载PyMongo [root@leezhen ~]# wget https://pypi.python.org/packages/source/p/pymongo/pymongo-2.6.3.tar ...

  4. MongoDB的安装与python操作MongoDB

    一.安装MongoDB 因为我个人使用的是windows,就只记录下windows下的安装 1.下载安装 就是官网,下载msi,选个路径安装 2.配置 看见别的地方说需要手动在bin同级目录创建dat ...

  5. pymongo和mongoengine安装和使用教程 包含常用命令行和代码示例 | pymongo and mongoengine tutorial on ubuntu 16.04

    本文首发于个人博客https://kezunlin.me/post/e88f04e5/,欢迎阅读最新内容! pymongo and mongoengine tutorial on ubuntu 16. ...

  6. MongoDB聚合查询及Python连接MongoDB操作

    今日内容概要 聚合查询 Python操作MongoDB 第三方可视化视图工具 今日内容详细 聚合查询 Python操作MongoDB 数据准备 from pymongo import MongoCli ...

  7. Python 连接MongoDB并比较两个字符串相似度的简单示例

    本文介绍一个示例:使用 pymongo 连接 MongoDB,查询MongoDB中的 字符串 记录,并比较字符串之间的相似度. 一,Python连接MongoDB 大致步骤:创建MongoClient ...

  8. python操作三大主流数据库(8)python操作mongodb数据库②python使用pymongo操作mongodb的增删改查

    python操作mongodb数据库②python使用pymongo操作mongodb的增删改查 文档http://api.mongodb.com/python/current/api/index.h ...

  9. Python操作MongoDB代码示例

    import pymongo #pip install pymongo安装python操作mongodb的模块 myclient=pymongo.MongoClient(host='127.0.0.1 ...

随机推荐

  1. Java之List排序功能举例

    package test_demo; import java.util.ArrayList; import java.util.Collections; import java.util.List; ...

  2. mybatis之注解方式实现

    * 使用mybatis举例,使用注解方式实现* 不需要针对UserMapperI接口去编写具体的实现类代码,这个具体的实现类由MyBatis帮我们动态构建出来,我们只需要直接拿来使用即可.* 1.导入 ...

  3. JXOI2017颜色 解题报告

    JXOI2017颜色 首先记录每个位置上颜色在序列中上次出现的位置 开两颗线段树,第一棵维护区间最大值,实际上是维护当前必须被删去的颜色的位置的最大值,第二棵则是维护区间和 首先倒着扫一遍,对于当前颜 ...

  4. 洛谷P3348 [ZJOI2016]大森林(LCT,虚点,树上差分)

    洛谷题目传送门 思路分析 最简单粗暴的想法,肯定是大力LCT,每个树都来一遍link之类的操作啦(T飞就不说了) 考虑如何优化算法.如果没有1操作,肯定每个树都长一样.有了1操作,就来仔细分析一下对不 ...

  5. 【agc001e】BBQ HARD(动态规划)

    [agc001e]BBQ HARD(动态规划) 题面 atcoder 洛谷 题解 这些agc都是写的整场的题解,现在还是把其中一些题目单独拿出来发 这题可以说非常妙了. 我们可以把这个值看做在网格图上 ...

  6. 20145215卢肖明《网络对抗》逆向及Bof基础

    20145215卢肖明<网络对抗>逆向及Bof基础 实践目标 本次实践的对象是一个名为pwn1的linux可执行文件. 该程序正常执行流程是:main调用foo函数,foo函数会简单回显任 ...

  7. DataGridView刷新数据

    在DataGridView上操作数据之后,无论是增删改都是对数据库进行了操作,而DataGridView这个控件在操作之后是不会变化的,需要重新的去数据库里读取一下数据才行,可以理解为之刷新 Data ...

  8. bzoj千题计划283:bzoj4516: [Sdoi2016]生成魔咒(后缀数组)

    http://www.lydsy.com/JudgeOnline/problem.php?id=4516 考虑在后面新加一个字母产生的影响 假设是第i个 如果不考虑重复,那么会增加i个不同的字符串 考 ...

  9. git 查看一个分支是否被合并过

    1.查看该分支的提交历史 git log 分支名 2.git log master |grep comitid 如果包含,就证明已经合并过 3.git branch -d 分支名,如果报错,就是没合并 ...

  10. 如何用javascript获取和设置css3属性

    ==================获取======================== 我想到的第一个思路 var test = document.getElementById('test'); c ...