python连接mongodb操作数据示例(mongodb数据库配置类)

yipeiwu_com6年前Python基础

一、相关代码
数据库配置类 MongoDBConn.py

复制代码 代码如下:

#encoding=utf-8
'''

Mongo Conn连接类
'''

import pymongo

class DBConn:
    conn = None
    servers = "mongodb://localhost:27017"

    def connect(self):
        self.conn = pymongo.Connection(self.servers)

    def close(self):
        return self.conn.disconnect()

    def getConn(self):
        return self.conn

MongoDemo.py 类

复制代码 代码如下:

#encoding=utf-8
'''

Mongo操作Demo
Done:
'''
import MongoDBConn

dbconn = MongoDBConn.DBConn()
conn = None
lifeba_users = None

def process():
    #建立连接
    dbconn.connect()
    global conn
    conn = dbconn.getConn()

    #列出server_info信息
    print conn.server_info()

    #列出全部数据库
    databases = conn.database_names()
    print databases

    #删除库和表
    dropTable()
    #添加数据库lifeba及表(collections)users
    createTable()
    #插入数据
    insertDatas()
    #更新数据
    updateData()
    #查询数据
    queryData()
    #删除数据
    deleteData()

    #释放连接
    dbconn.close()

def insertDatas():
    datas=[{"name":"steven1","realname":"测试1","age":25},
           {"name":"steven2","realname":"测试2","age":26},
           {"name":"steven1","realname":"测试3","age":23}]
    lifeba_users.insert(datas)

def updateData():
    '''只修改最后一条匹配到的数据
           第3个参数设置为True,没找到该数据就添加一条
           第4个参数设置为True,有多条记录就不更新
    '''
    lifeba_users.update({'name':'steven1'},{'$set':{'realname':'测试1修改'}}, False,False)

def deleteData():
    lifeba_users.remove({'name':'steven1'})

def queryData():
    #查询全部数据
    rows = lifeba_users.find()
    printResult(rows)
    #查询一个数据
    print lifeba_users.find_one()
    #带条件查询
    printResult(lifeba_users.find({'name':'steven2'}))
    printResult(lifeba_users.find({'name':{'$gt':25}}))

def createTable():
    '''创建库和表'''
    global lifeba_users
    lifeba_users = conn.lifeba.users

def dropTable():
    '''删除表'''
    global conn
    conn.drop_database("lifeba")

def printResult(rows):
    for row in rows:
        for key in row.keys():#遍历字典
            print row[key], #加, 不换行打印
        print ''

if __name__ == '__main__':
    process()

相关文章

fastcgi文件读取漏洞之python扫描脚本

fastcgi文件读取漏洞之python扫描脚本

PHP FastCGI的远程利用 说到FastCGI,大家都知道这是目前最常见的webserver动态脚本执行模型之一。目前基本所有web脚本都基本支持这种模式,甚至有的类型脚本这是唯一...

解决pycharm运行程序出现卡住scanning files to index索引的问题

有时候会出现索引问题,显示scanning files to index 解决方法: in pycharm, go to the "File" on the left top, then...

Python实现将数据写入netCDF4中的方法示例

本文实例讲述了Python实现将数据写入netCDF4中的方法。分享给大家供大家参考,具体如下: nc文件为处理气象数据文件。用户可以去https://www.lfd.uci.edu/~...

python通过pil为png图片填充上背景颜色的方法

本文实例讲述了python通过pil为png图片填充上背景颜色的方法。分享给大家供大家参考。具体分析如下: png图片有些是没有背景颜色,如果希望以单色(比如白色)填充背景,可以使用下面...

Python pip替换为阿里源的方法步骤

Python pip替换为阿里源的方法步骤

背景 由于 python 自带的源下载速度非常慢,特别是安装一些库的时候,甚至有时会失败。 pip国内的一些镜像   阿里云 http://mirror...