pymongo基礎使用方法


本文通過文章同步功能推送至博客園,排版可能會有所錯誤,敬請見諒!

1.客戶端初始化

初始化MongoDB客戶端

client = pymongo.MongoClient('localhost',27017)

2.創建數據庫和數據表

pymongo支持以字典或屬性的形式(內置了__item____getattr__方法)連接數據庫和數據表,若該數據庫/表不存在,則創建。

db = client['mydatabase']

sheet = db['sheetname']

3.數據的增加

pymongo中,對數據的增刪改查,全部在數據表對象(sheet)中執行。

MongoDB屬於非關系型數據庫,它被常用於存儲JSON結構,可以很方便的存儲序列化信息。

· insert_one方法

· insert_many方法

· insert方法

(1)insert_one插入一條記錄

insert_one(document, bypass_document_validation=False, session=None)

document往往是一條以字典形式的數據

可以是

data = {

'city': soup.find(attrs={'name': 'location'})['content'].split('city=')[-1].split(';')[0],

'district':soup.title.get_text().split('短租房')[0][1:] + '',

'title': soup.select('#indexPage > div > div.houseIntroduce > div.border_b > p')[-1].get_text().strip(),

'addr': soup.select('#indexPage > div > section > p')[0].get_text().strip(),

'price': int(soup.select('div.priceBox > div > div > span.newPcrice')[0].get_text().strip()),

'introduce':soup.select('div.houseIntroduceBox > div.houseIntroduce_P_con > p')[0].get_text().strip(),

'tags':[],

}

(2)insert_many插入多條記錄

insert_one(document, ordered=True, bypass_document_validation=False,

session=None)

document是一個可迭代對象,通常是數據組成的列表或者元組。

ordered如果為真,數據將按照提供的順序連續插入數據表,否則以任意順序。

(3)insert方法

pymongo3.6.1中,insert方法是不被贊成的方法,請使用insert_one或者insert_many

4.數據的刪除

使用下面幾種方法可以刪除任意條數據:

· delete_one方法

· delete_many方法

(1)delete_one刪除一條記錄

delete_one(filter, collation=False, session=None)

filter為字典形式的查詢對象

(2)delete_many刪除多條記錄

delete_many(filter, collation=False, session=None)

filter為字典形式的查詢對象

(3)find_one_and_delete找到並刪除一條數據

find_one_and_delete(filter, projection=None, sort=None, session=None)

5.數據的修改

· replace_one方法

· update_one方法

· update_many方法

(1)replace_one替換一條記錄

replace_one(filter, replacement, upsert=False,

bypass_document_validation=False, collation=None,

session=None)

filter是過濾條件

replacement是替換后的數據

upsert如果為真,則當找不到過濾條件時,會直接插入替換后的數據。

(2)update_one修改一條記錄數據

replace_one替換方法的簡單粗暴相比,update_one更注重於修改一條數據本身,update方法系列也支持更高級的操作符。

update_one(filter, update, upsert=False,

bypass_document_validation=False,

collation=None, array_filters=None, session=None)

filter是過濾條件

update是要修改字段的數據集合(通常以字典表現)

update支持MongoDB的操作符(詳見MongDB的操作運算符),這是一個非常重要的特性。

6.數據的查詢

· find方法

· find_one方法

(1)find查詢所有匹配數據

sheet.find({'district':'岳麓區', 'deposit':{'$lt':301}})

(2)find_one查詢匹配的第一條數據

使用方法與find一致。

在數據的查詢中,主要掌握MongoDB的操作運算符才是靈活使用的關鍵點。

7.其他內置方法

· count() - 返回查詢結果數量

· sorted() - 接收一個字段,按其排序

· create_index() - 創建索引詳見官方文檔

8.補充:MongDB的操作運算符

參考資料:mongodb常用操作符

(1)比較操作符

· $gt - 匹配字段值大於指定值的文檔( > )

· $lt - 匹配字段值大於指定值的文檔( < )

· $gte - 匹配字段值大於等於指定值的文檔( >= )

· $lte - 匹配字段值小於等於指定值的文檔( <= )

· $eq - 匹配字段值等於指定值的文檔( = )

· $in - 匹配字段值等於指定數組中的任何值

o { field: { $in: [<value1>, <value2>, ... <valueN> ] } }

· $ne - 匹配字段值不等於指定值的文檔,包括沒有這個字段的文檔

· $nin - 字段值不在指定數組或者不存在

o { field: { $nin: [<value1>, <value2>, ... <valueN> ] } }

(2)邏輯操作符

· $or - 文檔至少滿足其中的一個表達式

o { $or: [ { <expression1> }, ... , { <expressionN> } ] }

· $and - 文檔同時滿足所有的表達式

o { $and: [ { <expression1> }, ... , { <expressionN> } ] }

· $nor - 字段值不匹配所有的表達式的文檔,包括那些不包含這些字段的文檔

o { $nor: [ { <expression1> }, ... , { <expressionN> } ] }

(3)元素操作符

· $type - 匹配字段值為指定數據類型的文檔(詳見)

o { field: { $type: <BSON type number> | <String alias> } }

o sheet.find({'deposit':{'$type':'string'}})

o sheet.find({'deposit':{'$type':2}})

· $exists - 匹配字段存在的數據

(4)評估操作符

· $mod - 匹配字段值被除有指定的余數的文檔

o { field: { $mod: [ divisor(除數), remainder(余數) ] } }

· $regex - 正則表達式可以匹配到的文檔

o { <field>: { $regex: 'pattern', $options: '<options>' } }

· $text - 針對創建了全文索引的字段進行文本搜索

附表1MongoDB數據類型

mestamp”

Type

Number

Alias

Notes

Double

1

double

 

String

2

string

 

Object

3

object

 

Array

4

array

 

Binary data

5

binData

 

Undefined

6

undefined

Deprecated.

ObjectId

7

objectId

 

Boolean

8

bool

 

Date

9

date

 

Null

10

null

 

Regular Expression

11

regex

 

DBPointer

12

dbPointer "182" valign="top" style="border:solid #A3A3A3 1.0pt;background:white;">

JavaScript

13

javascript

 

Symbol

14

symbol

Deprecated.

JavaScript (with scope)

15

javascriptWithScope

 

32-bit integer

16

int

 

64-bit integer

18

long

 

Decimal128

19

decimal

New in version 3.4.

Min key

-1

minKey

 

Max key

127

“maxKey”

 



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM