mongodb数据库常用操作的整理
这是个人在项目中抽取的代码,自己写的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数据库常用操作的整理的更多相关文章
- MongoDB数据库常用操作
推荐文章 --- 一天精通MongoDB数据库 注意: monogdb数据在使用之后必须及时 mongodb.close()否则后台崩溃. 1. 删除文档中的一个字段 db.<集合名>.u ...
- mongodb的常用操作
对于nosql之前工作中有用到bekerlydb,最近开始了解mongodb,先简单写下mongodb的一些常用操作,当是个总结: 1.mongodb使用数据库(database)和集合(collec ...
- php模拟数据库常用操作效果
test.php <?php header("Content-type:text/html;charset='utf8'"); error_reporting(E_ALL); ...
- DBA必备:MySQL数据库常用操作和技巧
DBA必备:MySQL数据库常用操作和技巧 2011-02-25 15:31 kaduo it168 字号:T | T MySQL数据库可以说是DBA们最常见和常用的数据库之一,为了方便大家使用,老M ...
- MongoDB数据库简单操作
之前学过的有mysql数据库,现在我们学习一种非关系型数据库 一.简介 MongoDB是一款强大.灵活.且易于扩展的通用型数据库 MongoDB 是由C++语言编写的,是一个基于分布式文件存储的开源数 ...
- 【mongodb系统学习之八】mongodb shell常用操作
八.mongodb shell常用基础操作(每个语句后可以加分号,也可以不加,看情况定(有的工具中可以不加),最好是加): 1).进入shell操作界面:mongo,上边已有演示: 2).查看当前使 ...
- MongoDB数据库基础操作
前面的话 为了保存网站的用户数据和业务数据,通常需要一个数据库.MongoDB和Node.js特别般配,因为Mongodb是基于文档的非关系型数据库,文档是按BSON(JSON的轻量化二进制格式)存储 ...
- mongodb数据库集合操作
1:更新update update() 方法用于更新已存在的文档.语法格式如下: db.collection.update( <query>, <update>, { upse ...
- linux下的mongodb数据库原生操作
mongodb,是一种结构最像mysql的nosql mysql中的数据库,mongodb中也有,区别在于, myql中数据库下的是表,字段和数据的形式存在 mongodb数据库下的是叫集合(和pyt ...
随机推荐
- sublime3使用笔记
1.ctrl+n 新建一个文件: 2.alt+shift+数字 分屏显示: 3.ctrl+alt+down(向下键) 连选很多行的指定开始位置: 如图: 紧接着再按shift+right(选中需要更改 ...
- hadoop之hive建表语句备份
转自:https://blog.csdn.net/t___z/article/details/78492113 #!/bin/bash hive -e "use lbi;show table ...
- Nginx多种负载均衡策略搭建
背景介绍 上篇介绍了利用Nginx反向代理实现负载均衡,本文详细讲述Nginx下的几种负载均衡策略. 轮询 轮询,顾名思义,就是轮流请求,基于上篇文章的介绍,我们将负载均衡策略聚焦于default.c ...
- BDC
TC:SHDB 复制到应用处并更改参数. 附上部分代码 * Batchinputdata of single transaction DATA: bdcdata LIKE bdcdat ...
- vscode左边侧边栏字体的大小
相信很多小伙伴们都会在用vscode的时候,当屏幕大小发生变化的时候,你可能会觉得左边的字体太小了,我也遇到了这样的问题,百度也没有找到解决办法,自己摸索了几天,发现可以通过ctrl+shift+ + ...
- Linux/windows com串口 java 接收数据 并解析 web程序
1.首先应公司要求再 com 口本来使用 .net 由于 .net 适用 linux 太麻烦 改为java 准备工作 准备 RXTXconmm.jar(版本很重要) 因为版本问题我搞了一天. 主要讲述 ...
- 阿里云服务器CentOS7.5安装RabbitMQ
RabbitMQ是实现了高级消息队列协议(AMQP)的开源消息代理软件(亦称面向消息的中间件).RabbitMQ服务器是用Erlang语言编写的,而集群和故障转移是构建在开放电信平台框架上的. 为什么 ...
- eclipse中一个项目引用另一个项目,运行报:java.lang.NoClassDefFoundError
项目右击-properties-Java Build Path -Porjects-add.选中了某个项目. 项目用tomcat启动时,报错:java.lang.NoClassDefFoundErro ...
- java请求转发,响应重定向的区别
请求转发:request.getRequestDispatcher().forward(); 例:request.getRequestDispatcher("/index.jsp" ...
- HDU 1394:Minimum Inversion Number(线段树区间求和单点更新)
http://acm.hdu.edu.cn/showproblem.php?pid=1394 Minimum Inversion Number Problem Description The in ...