我們?cè)谑褂肕ongoDB的時(shí)候,一個(gè)集合里面能放多少數(shù)據(jù),一般取決于硬盤大小,只要硬盤足夠大,那么我們可以無休止地往里面添加數(shù)據(jù)。
然后,有些時(shí)候,我只想把MongoDB作為一個(gè)循環(huán)隊(duì)列來使用,期望它有這樣一個(gè)行為:
- 設(shè)定隊(duì)列的長(zhǎng)度為10
- 插入第1條數(shù)據(jù),它被放在第1個(gè)位置
- 插入第2條數(shù)據(jù),它被放在第2個(gè)位置
- ...
- 插入第10條數(shù)據(jù),它被放在第10個(gè)位置
- 插入第11條數(shù)據(jù),它被放在第1個(gè)位置,覆蓋原來的內(nèi)容
- 插入第12條數(shù)據(jù),它被放在第2個(gè)位置,覆蓋原來的內(nèi)容
- ...
MongoDB有一種Collection叫做capped collection,就是為了實(shí)現(xiàn)這個(gè)目的而設(shè)計(jì)的。
普通的Collection不需要提前創(chuàng)建,只要往MongoDB里面插入數(shù)據(jù),MongoDB自動(dòng)就會(huì)創(chuàng)建。而capped collection需要提前定義一個(gè)集合為capped類型。
語法如下:
import pymongo
conn = pymongo.MongoClient()
db = conn.test_capped
db.create_collection('info', capped=True, size=1024 * 1024 * 10, max=5)
對(duì)一個(gè)數(shù)據(jù)庫對(duì)象使用create_collection方法,創(chuàng)建集合,其中參數(shù)capped=True說明這是一個(gè)capped collection,并限定它的大小為10MB,這里的size參數(shù)的單位是byte,所以10MB就是1024 * 1024 * 10. max=5表示這個(gè)集合最多只有5條數(shù)據(jù),一旦超過5條,就會(huì)從頭開始覆蓋。
創(chuàng)建好以后,capped collection的插入操作和查詢操作就和普通的集合完全一樣了:
col = db.info
for i in range(5):
data = {'index': i, 'name': 'test'}
col.insert_one(data)
這里我插入了5條數(shù)據(jù),效果如下圖所示:

其中,index為0的這一條是最先插入的。
接下來,我再插入一條數(shù)據(jù):
data = {'index': 100, 'name': 'xxx'}
col.insert_one(data)
此時(shí)數(shù)據(jù)庫如下圖所示:

可以看到,index為0的數(shù)據(jù)已經(jīng)被最新的數(shù)據(jù)覆蓋了。
我們?cè)俨迦胍粭l數(shù)據(jù)看看:
data = {'index': 999, 'name': 'xxx'}
col.insert_one(data)
運(yùn)行效果如下圖所示:

可以看到,index為1的數(shù)據(jù)也被覆蓋了。
這樣我們就實(shí)現(xiàn)了一個(gè)循環(huán)隊(duì)列。
MongoDB對(duì)capped collection有特別的優(yōu)化,所以它的讀寫速度比普通的集合快。
但是capped collection也有一些缺點(diǎn),在MongoDB的官方文檔中提到:
If an update or a replacement operation changes the document size, the operation will fail.
You cannot delete documents from a capped collection. To remove all documents from a collection, use the drop() method to drop the collection and recreate the capped collection.
意思就是說,capped collection里面的每一條記錄,可以更新,但是更新不能改變記錄的大小,否則更新就會(huì)失敗。
不能單獨(dú)刪除capped collection中任何一條記錄,只能整體刪除整個(gè)集合然后重建。
總結(jié)
到此這篇關(guān)于把MongoDB作為循環(huán)隊(duì)列的文章就介紹到這了,更多相關(guān)MongoDB作循環(huán)隊(duì)列內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!