首页 > 数据库技术 > 详细

python 操作mongoDB数据库

时间:2017-05-08 17:14:18      阅读:276      评论:0      收藏:0      [点我收藏+]

网上关于python 操作mongoDB的相关文章相对不是很多,并且质量也不是很高!下面给出一个完整的 增删改查示例程序!

 

#!/usr/bin/python
# -*- coding: utf-8 -*-
import pymongo
import re

connection = pymongo.MongoClient(10.38.164.80,27017)
tdb = connection.test
collection = tdb.article

#插入数据
try:
    insert_data={"id":"2","value":"abc"}
    collection.insert(insert_data)
except BaseException:
    print "插入异常"

#查询数据
try:
    print collection.find_one({"id":"2"})
    cursor =  collection.find({"title":re.compile("^.{0,50}(女神)")},{"title":1,"url":1})
    for result in cursor:
        print type(result)  #查看类型
        print str(result).decode("unicode-escape")
        print result.get("title")
        #print str(result).decode(‘unicode_escape‘)
except BaseException,e:
    print "查询数据异常" + str(e)

#修改数据
try:
    collection.update({"id":"2"},{"$set":{"value":"123"}})
except BaseException,e:
    print "更新数据失败"
    print e

#删除数据
try:
    collection.remove({"id":"2"})
except BaseException,e:
    print "删除数据异常"
    print e

 

需要安装mongo库,安装命令如下(ubuntu):pip install pymongo

python 操作mongoDB数据库

原文:http://www.cnblogs.com/tengpan-cn/p/6825942.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!