Python Mongo操作
# -*- coding: utf-8 -*- ''' Python Mongo操作Demo Done: ''' from pymongo import MongoClient conn = None topics = None users=None def process(): connection=MongoClient('localhost', 27017) global conn conn = connection; #列出server_info信息 #print conn.server_info() #列出全部数据库 databases = conn.database_names() print databases topics = conn.node.topics users=conn.node.users ret=users.find({'loginname':'dingxiaoyuehao'}) if ret and ret.count() > 0: print "yes" else: print "no" #删除库和表 #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}] topics.insert(datas) def updateData(): '''只修改最后一条匹配到的数据 第3个参数设置为True,没找到该数据就添加一条 第4个参数设置为True,有多条记录就不更新 ''' topics.update({'name':'steven1'},{'$set':{'realname':'测试1修改'}}, False,False) def deleteData(): topics.remove({'name':'steven1'}) def queryData(): #查询全部数据 rows = topics.find() printResult(rows) #查询一个数据 print topics.find_one() #带条件查询 printResult(topics.find({'name':'steven2'})) printResult(topics.find({'name':{'$gt':25}})) def createTable(): '''创建库和表''' global topics topics = conn.lifeba.topics def dropTable(): '''删除表''' global conn conn.drop_database("lifeba") def printResult(rows): for row in rows: for key in row.keys():#遍历字典 print row[key].encode('gb2312'), #加, 不换行打印 print '' if __name__ == '__main__': process()