这是个人在项目中抽取的代码,自己写的utils的通用模块,使用的框架是tronado,包括了数据库的认证,以及增删改查排序,如有特别需要可以联系我或者自己扩展,刚学python不久,仅供参考,例子如下。

# -*- coding: utf-8 -*-
import pymongo
import logging
from bson.objectid import ObjectId from etc.config import *
conf_log = logging class DatabaseAPI(object):
def __init__(self):
super(DatabaseAPI, self).__init__()
self.log = logging # MongoDB info set in config
self.mg_host = mgHost
self.mg_port = str(mgPort)
self.mg_username = mgUsername
self.mg_password = mgPassword
self.mg_database = mgDatabase
self.mg_auth_method = mgAuthMethod
self.mg_client = None
self.mg_conn = None # Login mongoDB
self.mg_client = pymongo.MongoClient("mongodb://%s:%s" % (mgHost, mgPort))
self.mg_conn = self.mg_client[self.mg_database]
if self.mg_username or self.mg_password:
auth_method = mgAuthMethod if mgAuthMethod else 'DEFAULT'
self.mg_conn.authenticate(mgUsername, mgPassword, mechanism=auth_method) def login_mongodb(self):
# Login mongodb using or not using authentication
self.mg_client = pymongo.MongoClient("mongodb://%s:%s" % (mgHost, mgPort))
self.mg_conn = self.mg_client[self.mg_database]
if self.mg_username or self.mg_password:
auth_method = mgAuthMethod if mgAuthMethod else 'DEFAULT'
self.mg_conn.authenticate(mgUsername, mgPassword, mechanism=auth_method)
return self.mg_conn def std_filter_exp(self, filter_exp):
# Standardize filter expression
self.log.error("Filter_exp before modified: " + str(filter_exp))
if filter_exp:
if filter_exp.get("_id"):
if isinstance(filter_exp["_id"], str) \
or isinstance(filter_exp["_id"], unicode):
filter_exp["_id"] = ObjectId(str(filter_exp["_id"]))
elif isinstance(filter_exp["_id"], dict):
if filter_exp["_id"].get("$in"):
filter_exp["_id"]["$in"] = [ObjectId(str(doc_id)) for doc_id in filter_exp["_id"]["$in"]]
self.log.error("Filter_exp after modified: " + str(filter_exp))
return filter_exp def stdout_documents(self, documents):
# Standardize content of expression
self.log.debug("Output before modified: " + str(documents))
for document in documents:
if document.get("_id"):
document["_id"] = str(document["_id"])
self.log.debug("Output after modified: " + str(documents))
return documents def stdin_documents(self, documents):
# Standardize content of expression
self.log.debug("Input before modified: " + str(documents))
if isinstance(documents, (list, tuple)):
for document in documents:
if document.get("_id"):
document["_id"] = ObjectId(str(document["_id"]))
self.log.debug("Input after modified: " + str(documents))
else:
documents = [documents]
return documents def mongo_find(self, collection, filter_exp=None, projection=None, skip=0, limit=0, sort=None):
# Find documents in certain collection
self.log.debug("MongoDB find: %s, %s, %s, %s, %s, %s" %
(str(collection), str(filter_exp), str(projection), str(skip), str(limit), str(sort)))
mg_col = self.mg_conn[collection]
filter_exp = self.std_filter_exp(filter_exp)
result = mg_col.find(filter=filter_exp, projection=projection, skip=skip, limit=limit, sort=sort)
db_resource = self.stdout_documents([section for section in result])
return db_resource def mongo_insert(self, collection, documents, ordered=False):
# Insert documents into certain collection
mg_col = self.mg_conn[collection]
documents = self.stdin_documents(documents)
result = mg_col.insert_many(documents, ordered)
return result def mongo_update(self, collection, filter_exp, update_exp, upsert=False):
# Update documents matching certain filter
mg_col = self.mg_conn[collection]
filter_exp = self.std_filter_exp(filter_exp)
result = mg_col.update_many(filter_exp, update_exp, upsert)
return result def mongo_delete(self, collection, filter_exp):
# Delete documents matching the filter
mg_col = self.mg_conn[collection]
filter_exp = self.std_filter_exp(filter_exp)
result = mg_col.delete_many(filter_exp)
return result

mongodb数据库常用操作的整理的更多相关文章

  1. MongoDB数据库常用操作

    推荐文章 --- 一天精通MongoDB数据库 注意: monogdb数据在使用之后必须及时 mongodb.close()否则后台崩溃. 1. 删除文档中的一个字段 db.<集合名>.u ...

  2. mongodb的常用操作

    对于nosql之前工作中有用到bekerlydb,最近开始了解mongodb,先简单写下mongodb的一些常用操作,当是个总结: 1.mongodb使用数据库(database)和集合(collec ...

  3. php模拟数据库常用操作效果

    test.php <?php header("Content-type:text/html;charset='utf8'"); error_reporting(E_ALL); ...

  4. DBA必备:MySQL数据库常用操作和技巧

    DBA必备:MySQL数据库常用操作和技巧 2011-02-25 15:31 kaduo it168 字号:T | T MySQL数据库可以说是DBA们最常见和常用的数据库之一,为了方便大家使用,老M ...

  5. MongoDB数据库简单操作

    之前学过的有mysql数据库,现在我们学习一种非关系型数据库 一.简介 MongoDB是一款强大.灵活.且易于扩展的通用型数据库 MongoDB 是由C++语言编写的,是一个基于分布式文件存储的开源数 ...

  6. 【mongodb系统学习之八】mongodb shell常用操作

    八.mongodb  shell常用基础操作(每个语句后可以加分号,也可以不加,看情况定(有的工具中可以不加),最好是加): 1).进入shell操作界面:mongo,上边已有演示: 2).查看当前使 ...

  7. MongoDB数据库基础操作

    前面的话 为了保存网站的用户数据和业务数据,通常需要一个数据库.MongoDB和Node.js特别般配,因为Mongodb是基于文档的非关系型数据库,文档是按BSON(JSON的轻量化二进制格式)存储 ...

  8. mongodb数据库集合操作

    1:更新update update() 方法用于更新已存在的文档.语法格式如下: db.collection.update( <query>, <update>, { upse ...

  9. linux下的mongodb数据库原生操作

    mongodb,是一种结构最像mysql的nosql mysql中的数据库,mongodb中也有,区别在于, myql中数据库下的是表,字段和数据的形式存在 mongodb数据库下的是叫集合(和pyt ...

随机推荐

  1. Spring之Bean的装配

    一.Bean的装配Bean的装配,即Bean对象的创建.容器根据代码要求创建Bean对象后再传递给代码的过程,称为Bean的装配.1.默认装配方式代码通过getBean()方式从容器获取指定的Bean ...

  2. ABP开发框架前后端开发系列---(11)菜单的动态管理

    在前面随笔<ABP开发框架前后端开发系列---(9)ABP框架的权限控制管理>中介绍了基于ABP框架服务构建的Winform客户端,客户端通过Web API调用的方式进行获取数据,从而实现 ...

  3. ZTree简单粗暴快速使用

    是什么:功能强大的树形插件 tip:查资料时痛苦的地方,自我改进 1.没有注明版本:版本不对应导致配置完成后各种无端的错误,特别难查找,运气好能找到英文的解答 2.没有写明配置文件,或者不指明配置文件 ...

  4. Ruby字符串(2):String方法详细整理

    String方法整理 官方手册 类方法 new new(str="") → new_str new(str="", encoding: enc) → new_s ...

  5. SQL Server 2016 + AlwaysOn 无域集群

    目录 AlwaysOn 搭建 WSFC 配置计算机的 DNS 后缀 安装故障转移集群 验证集群 创建集群 创建文件共享见证 配置 AlwaysOn 新建可用性组 创建侦听器 可读副本的负载均衡 主角色 ...

  6. Anemic Model

    In object-oriented programming, and especially in Domain-Driven Design, objects are said to be anemi ...

  7. 【JavaScript】深入理解call,以及与apply、bind的区别

    一.call call有两个妙用 1.继承(我前面的文章有提到用call实现call继承,有兴趣可以看下.https://www.cnblogs.com/pengshengguang/p/105476 ...

  8. SpringCloud解析之Zuul(一)

    本文基于Spring Cloud Edgware.SR6,Zuul版本1.3.1,解析Zuul的请求拦截机制,让大家对Zuul的原理有个大概的认识和了解.如有不对的地方,欢迎指正. spring bo ...

  9. Linux日志系统分析:rsyslog、syslog和klog

    参考博客: https://blog.csdn.net/lidonghat/article/details/55004280 https://blog.csdn.net/u012247418/arti ...

  10. 【字符串】P2084 进制转换-C++

    题目描述 今天小明学会了进制转换,比如(10101)2 ,那么它的十进制表示的式子就是 : 1*2^4+0*2^3+1*2^2+0*2^1+1*2^0, 那么请你编程实现,将一个M进制的数N转换成十进 ...