关键详细介绍了python连接mongodb实际操作数据实例,关键包含插进数据、升级数据 、查询数据、删掉数据等
1、数据库配备类 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

2 、ngoDemo.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():
    '''只改动最终一条搭配到的数据
           第三个基本参数为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()
文章来源于网络 ,如有侵权请联系站长QQ61910465删除
本文版权归去快排Seo www.SEOgurublog.com 所有,如有转发请注明来出,竞价开户托管,seo优化请联系QQ▷61910465