这是个人在项目中抽取的代码,自己写的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. ADMethodsAccountManagement 一些简单注释添加

    using System; using System.Collections; using System.Text; using System.DirectoryServices.AccountMan ...

  2. 关于Git 的管理凭据操作

    1.桌面-->2.我的电脑-->3.右击选择属性-->4.控制面板主页-->5.在用户账户和家庭安全下,选择添加或删除用户账户-->转到“主用户账户”页面-->6. ...

  3. 浅谈我在.net core一年里的收获

    前言:以前一直在winserver的环境里从事web工作,安装一个sqlserver,iis,把项目部署上面就OK了,简单轻松一.结缘nginx以前一直听说nginx这个反向代理的web服务器,当玩n ...

  4. Spring Boot:集成Druid数据源

    综合概述 数据库连接池负责分配.管理和释放数据库连接,它允许应用程序重复使用一个现有的数据库连接,而不是再重新建立一个:释放空闲时间超过最大空闲时间的数据库连接来避免因为没有释放数据库连接而引起的数据 ...

  5. Python自学day-15

    一.防止页面变形 在改变浏览器大小时,可能会导致里面的元素变形(特别是用百分比设置的宽度). 那么,我们如何解决这个问题? 可以在最外层的元素(例如div)中,设置一个固定像素的宽度,例如: < ...

  6. Hadoop起步之图解SSH、免密登录原理和实现

    1. 前言 emmm….最近学习大数据,需要搭建Hadoop框架,当弄好linux系统之后,第一件事就是SSH免密登录的设置.对于SSH,我觉得使用过linux系统的程序员应该并不陌生.可是吧,用起来 ...

  7. Windows鼠标右键菜单添加SublimeText打开选项

    Windows上将使用SublimeText打开文件的选项添加到鼠标右键菜单. 新建reg后缀的注册表文件,编辑添加内容 Windows Registry Editor Version 5.00 [H ...

  8. Qt实现炫酷启动图-动态进度条

    目录 一.简述 二.动效进度条 1.光效进度条 2.延迟到达进度条 3.接口说明 三.启动图 1.实现思路 2.背景图切换 四.测试 1.构造启动图 2.背景图 3.其他信息 4.事件循环 五.源码 ...

  9. oraclesql遇见的问题(一)

    在oracle的数据库,对于字段为null的字段过滤条件只能用is null 或者 is not null,不能使用 != , <> , = 判断, 今天进行接口测试时,发现获取到的数据缺 ...

  10. iOS组件化开发一使用source管理远端库升级(四)

    一.克隆远端库代码到本地选择master分支 1.克隆 2.代码会显示出你所有版本的tag 二.可以在Example目录下验证代码的正确行: cd 到库的文件夹然后 pod install comma ...