python 操作mongoDB数据库
时间:2021-07-01 10:21:17
帮助过:21人阅读
!/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