如何把MongoDB做为循环队列

咱们在使用MongoDB的时候,一个集合里面能放多少数据,通常取决于硬盘大小,只要硬盘足够大,那么咱们能够无休止地往里面添加数据。python

而后,有些时候,我只想把MongoDB做为一个循环队列来使用,指望它有这样一个行为:数据库

  1. 设定队列的长度为10
  2. 插入第1条数据,它被放在第1个位置
  3. 插入第2条数据,它被放在第2个位置
  4. ...
  5. 插入第10条数据,它被放在第10个位置
  6. 插入第11条数据,它被放在第1个位置,覆盖原来的内容
  7. 插入第12条数据,它被放在第2个位置,覆盖原来的内容
  8. ...

MongoDB有一种Collection叫作capped collection,就是为了实现这个目的而设计的。微信

普通的Collection不须要提早建立,只要往MongoDB里面插入数据,MongoDB自动就会建立。而capped collection须要提早定义一个集合为capped类型。app

语法以下:优化

import pymongo

conn = pymongo.MongoClient()
db = conn.test_capped

db.create_collection('info', capped=True, size=1024 * 1024 * 10, max=5)
复制代码

对一个数据库对象使用create_collection方法,建立集合,其中参数capped=True说明这是一个capped collection,并限定它的大小为10MB,这里的size参数的单位是byte,因此10MB就是1024 * 1024 * 10. max=5表示这个集合最多只有5条数据,一旦超过5条,就会从头开始覆盖。spa

建立好之后,capped collection的插入操做和查询操做就和普通的集合彻底同样了:设计

col = db.info
for i in range(5):
    data = {'index': i, 'name': 'test'}
    col.insert_one(data)
复制代码

这里我插入了5条数据,效果以下图所示:code

其中,index为0的这一条是最早插入的。cdn

接下来,我再插入一条数据:对象

data = {'index': 100, 'name': 'xxx'}
col.insert_one(data)
复制代码

此时数据库以下图所示:

能够看到,index为0的数据已经被最新的数据覆盖了。

咱们再插入一条数据看看:

data = {'index': 999, 'name': 'xxx'}
col.insert_one(data)
复制代码

运行效果以下图所示:

能够看到,index为1的数据也被覆盖了。

这样咱们就实现了一个循环队列。

MongoDB对capped collection有特别的优化,因此它的读写速度比普通的集合快。

可是capped collection也有一些缺点,在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里面的每一条记录,能够更新,可是更新不能改变记录的大小,不然更新就会失败。

不能单独删除capped collection中任何一条记录,只能总体删除整个集合而后重建。

若是这篇文章对你有帮助,请关注个人微信公众号: 未闻Code(ID: itskingname),第一时间获的最新更新:

相关文章
相关标签/搜索