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 ...
随机推荐
- python代码检查工具pylint 让你的python更规范
1.pylint是什么? Pylint 是一个 Python 代码分析工具,它分析 Python 代码中的错误,查找不符合代码风格标准(Pylint 默认使用的代码风格是 PEP 8,具体信息,请参阅 ...
- Powerdesigner 从Oracle到mssql2008
database->update model for database> ->系统数据源->选择用户,选择表,确定... 1.database->change Curre ...
- HBase 学习之路(一)—— HBase简介
一.Hadoop的局限 HBase是一个构建在Hadoop文件系统之上的面向列的数据库管理系统. 要想明白为什么产生HBase,就需要先了解一下Hadoop存在的限制?Hadoop可以通过HDFS来存 ...
- 【数据结构】红黑树-Java实现
WIKI:https://en.wikipedia.org/wiki/Red%E2%80%93black_tree 转:红黑树(五)之 Java的实现 总结的比较精炼的: http://www.cnb ...
- Go - Struct 结构体
目录 概述 声明结构体 生成 JSON 改变数据 推荐阅读 概述 结构体是将零个或多个任意类型的变量,组合在一起的聚合数据类型,也可以看做是数据的集合. 声明结构体 //demo_11.go pack ...
- JavaScript非构造函数的继承( object()方法、浅拷贝与深拷贝 )
一.什么是"非构造函数"的继承? 比如,现在有一个对象,叫做"中国人". var Chinese = { nation:'中国' }; 还有一个对象,叫做&qu ...
- CSS3边框与圆角
1. CSS3 圆角 border-radius 属性 一个最多可指定四个border -*- radius属性的复合属性,这个属性允许你为元素添加圆角边框!语法:border-radius: 1-4 ...
- 源码阅读 - java.util.concurrent (四)CyclicBarrier
CyclicBarrier是一个用于线程同步的辅助类,它允许一组线程等待彼此,直到所有线程都到达集合点,然后执行某个设定的任务. 举个例子:几个人约定了某个地方集中,然后一起出发去旅行.每个参与的人就 ...
- Git 的一些使用细枝末节
新入职XX公司第一天, 使用旧同事的电脑 Step1: 在Android Studio 中配置帐号 $ git config --global user.name author #将用户名设为auth ...
- NetCore AutoMapper的封装
需要引用AutoMapper的Nuget包 如果需要忽略某个字段就在字段上面打标签如下: [IgnoreMap] public string IgnoreValue { get; set; } ...