python 操作mongoDB資料庫

2022-03-21 10:12:54 字數 2944 閱讀 1562

#

!/usr/bin/python

#-*- coding: utf-8 -*-

import

pymongo

import

reconnection = pymongo.mongoclient('

10.38.164.80

',27017)

tdb =connection.test

collection =tdb.article

#插入資料

try:

insert_data=

collection.insert(insert_data)

except

baseexception:

print

"插入異常"#

查詢資料

try:

print collection.find_one()

cursor = collection.find((女神)

")},)

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(,})

except

baseexception,e:

print

"更新資料失敗

"printe#

刪除資料

try:

collection.remove()

except

baseexception,e:

print

"刪除資料異常

"print e

工具類(物件導向,使用更方便)

#

-*- coding: utf-8 -*-

import

pymongo

import

reclass

mongoutil:

def__init__

(self,host,port):

self.host=host

self.port=port

self.mongoclient=pymongo.mongoclient(host,port)

definsert(self,dbname,collectionname,data):

db=self.mongoclient.get_database(dbname)

collection=db.get_collection(collectionname)

collection.insert(data)

defquery(self,dbname,collectionname,queryobj,fieldobj):

db =self.mongoclient.get_database(dbname)

collection =db.get_collection(collectionname)

if fieldobj.__eq__

({}):

return

collection.find(queryobj)

else

:

return

collection.find(queryobj,fieldobj)

defupdate(self,dbname,collectionname,queryobj,newinfo):

db =self.mongoclient.get_database(dbname)

collection =db.get_collection(collectionname)

collection.update(queryobj,newinfo)

defdelete(self,dbname,collectionname,queryobj):

db =self.mongoclient.get_database(dbname)

collection =db.get_collection(collectionname)

collection.delete_many(queryobj)

mongoclient = mongoutil("

10.38.164.80

",27017)

#增加資料

try:

mongoclient.insert(

"test

","article

",)except

baseexception,e:

printe#

查詢資料

cursor = mongoclient.query("

test

","article

",(明星)

")},)

for result in

cursor:

print str(result).decode("

unicode-escape")

#修改資料

mongoclient.update("

test

","article

",,})

#刪除資料

mongoclient.delete("

test

","article

",)

view code

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

使用python操作MongoDB

from pymongo import mongoclient connect mongoclient host 127.0.0.1 port 27017 連線到資料庫主機 返回乙個連線 mongoclient host 127.0.0.1 27017 document class dict,tz ...

python對MongoDB的操作

python連線 try conn mongoclient ip,port database conn db db為資料庫名稱 my set database tb tb為表名稱 logger.info 需要檢測的字段 format field nm all my set.estimated doc...

python操作MongoDB資料庫

首先連線資料庫 如果你對python感興趣,我這有個學習python基地,裡面有很多學習資料,感興趣的 q群 688244617 import pymongo 連線資料庫 myclient pymongo.mongoclient mongodb localhost 27017 mydb myclie...