码迷,mamicode.com
首页 > 数据库 > 详细

python 操作mongoDB数据库

时间:2017-05-08 17:26:12      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:nbsp   exception   date   需要   span   增删改查   logs   val   title   

网上关于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数据库

标签:nbsp   exception   date   需要   span   增删改查   logs   val   title   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!