1. 程式人生 > >python 操作mongoDB數據庫

python 操作mongoDB數據庫

查看 $set 一個 關於 pan date set 完整 mongodb

網上關於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數據庫