如何把MongoDB作為循環(huán)隊(duì)列
我們在使用MongoDB的時(shí)候,一個集合里面能放多少數(shù)據(jù),一般取決于硬盤大小,只要硬盤足夠大,那么我們可以無休止地往里面添加數(shù)據(jù)。
然后,有些時(shí)候,我只想把MongoDB作為一個循環(huán)隊(duì)列來使用,期望它有這樣一個行為:
- 設(shè)定隊(duì)列的長度為10
- 插入第1條數(shù)據(jù),它被放在第1個位置
- 插入第2條數(shù)據(jù),它被放在第2個位置
- ...
- 插入第10條數(shù)據(jù),它被放在第10個位置
- 插入第11條數(shù)據(jù),它被放在第1個位置,覆蓋原來的內(nèi)容
- 插入第12條數(shù)據(jù),它被放在第2個位置,覆蓋原來的內(nèi)容
- ...
MongoDB有一種Collection叫做capped collection,就是為了實(shí)現(xiàn)這個目的而設(shè)計(jì)的。
普通的Collection不需要提前創(chuàng)建,只要往MongoDB里面插入數(shù)據(jù),MongoDB自動就會創(chuàng)建。而capped collection需要提前定義一個集合為capped類型。
語法如下:
- import pymongo
- conn = pymongo.MongoClient()
- db = conn.test_capped
- db.create_collection('info', capped=True, size=1024 * 1024 * 10, max=5)
對一個數(shù)據(jù)庫對象使用create_collection方法,創(chuàng)建集合,其中參數(shù)capped=True說明這是一個capped collection,并限定它的大小為10MB,這里的size參數(shù)的單位是byte,所以10MB就是1024 * 1024 * 10. max=5表示這個集合最多只有5條數(shù)據(jù),一旦超過5條,就會從頭開始覆蓋。
創(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ù)覆蓋了。
我們再插入一條數(shù)據(jù)看看:
- data = {'index': 999, 'name': 'xxx'}
- col.insert_one(data)
運(yùn)行效果如下圖所示:
可以看到,index為1的數(shù)據(jù)也被覆蓋了。
這樣我們就實(shí)現(xiàn)了一個循環(huán)隊(duì)列。
MongoDB對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里面的每一條記錄,可以更新,但是更新不能改變記錄的大小,否則更新就會失敗。
不能單獨(dú)刪除capped collection中任何一條記錄,只能整體刪除整個集合然后重建。
本文轉(zhuǎn)載自微信公眾號「未聞Code」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請聯(lián)系未聞Code公眾號。