Python增删改查MongoDB数据库

来源:互联网 发布:linux 抓包文件 导出 编辑:程序博客网 时间:2024/05/08 09:13

详细内容见代码注释↓

#-*-coding:utf-8 -*-import sysreload(sys)sys.setdefaultencoding('utf-8')import pymongo#建立MongoDB数据库连接client = pymongo.MongoClient('localhost',27017)# 连接所需数据库,test为数据库名db = client.test# 打印该数据库下所有collection名称print db.collection_names()# 连接所用集合,也就是我们通常所说的表,test_tb为表名collection = db.test_tb# 接下里就可以用collection来完成对数据库表的一些操作################################################ 查找集合中所有数据for stu in collection.find():    print stu['name'],stu['age'],stu['school']# 查找集合中指定数据(查到的第一条数据,若想查找多条则find(条件)迭代)stu = collection.find_one({'age':19})#collection.find({'title':re.compile('.*abc.*')}): 模糊查询使用re正则表达式匹配if stu:    print stu['name'],stu['age'],stu['school']# collection.find().sort('age',pymongo.ASCENDING):# 查询结果根据age排序,ASCENDING为升序,DESCENDING为降序# collection.find().sort([('age', pymongo.ASCENDING), ('name', pymongo.DESCENDING)]):# 查询结果根据多列排序for stu in collection.find().sort('age'):#查询结果根据UserName排序,默认为升序    print stu['name'], stu['age'], stu['school']################################################ 向集合中插入数据stu = {'name':'王五','age':23,'school':'东大'}collection.insert(stu)#插入一条stus = [{'name':'张三','age':19,'school':'东大'},        {'name':'李四','age':19,'school':'东大'},        {'name':'王五','age':19,'school':'东大'},        {'name':'赵六','age':19,'school':'东大'},        {'name':'小明','age':21,'school':'东大'}]collection.insert(stus)#插入多条################################################ 更新集合中的数据,第一个大括号里为更新条件,第二个大括号为更新之后的内容collection.update({'name':"王五"},{"$set":{'school':'南大'}})#只更新找到的第一个王五for item in collection.find({'name':"王五"}):#更新所有符合条件的项目    # 其实就是根据_id索引更新,可自建索引    collection.update({'_id':item['_id']},{"$set":{'school':'南大'}})################################################ 删除集合collection中的所有数据# collection.remove()# #删除集合指定数据# collection.remove({'name':'王五'})#删除所有王五# #删除集合collection# collection.drop()


原创粉丝点击