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 ...
随机推荐
- XP下安装ubuntu
一,环境说明 dell vostro 1400笔记本,winxp sp3操作系统,ubuntu-9.10-desktop-i386.iso 写这篇随笔的时候我用的已经是ubuntu了. 我是在我的移动 ...
- 【Linux】linux中删除指定日期之前的文件
要删除系统中就的备份文件,就需要使用命令了: #find /tmp -mtime +30 -type f -name *.sh[ab] -exec rm -f {} \; 假如在一个目录中保留最近30 ...
- Spring Boot:整合Swagger文档
综合概述 spring-boot作为当前最为流行的Java web开发脚手架,越来越多的开发者选择用其来构建企业级的RESTFul API接口.这些接口不但会服务于传统的web端(b/s),也会服务于 ...
- pytorch实现yolov3(3) 实现forward
之前的文章里https://www.cnblogs.com/sdu20112013/p/11099244.html实现了网络的各个layer. 本篇来实现网络的forward的过程. 定义网络 cla ...
- spring 5.x 系列第16篇 —— 整合dubbo (代码配置方式)
文章目录 一. 项目结构说明 二.项目依赖 三.公共模块(dubbo-ano-common) 四. 服务提供者(dubbo-ano-provider) 4.1 提供方配置 4.2 使用注解@Servi ...
- 【jar包管理】Maven BOM
BOM Alibaba Spring Boot Dependencies is a Maven BOM used to manage the versions of most used Alibaba ...
- RocketMQ(7)---RocketMQ顺序消费
RocketMQ顺序消费 如果要保证顺序消费,那么他的核心点就是:生产者有序存储.消费者有序消费. 一.概念 1.什么是无序消息 无序消息 无序消息也指普通的消息,Producer 只管发送消息,Co ...
- IO解惑:cephfs、libaio与io瓶颈
最近笔者在对kernel cephfs客户端进行fio direct随机大io读测试时发现,在numjobs不变的情况下,使用libaio作为ioengine,无论怎么调节iodepth,测试结果都变 ...
- RABC权限控制(二级菜单实现)
目前大部分系统由于用户体验,基本上菜单不会做的很深,以二级菜单为例,做了一个简单的权限控制实现,可精确到按钮级别(基于django),下面具体看看实现 1.表结构的设计 无论开发什么都需要先梳理清楚需 ...
- 并发编程-concurrent指南-原子操作类-AtomicBoolean
类AtomicBoolean