蒙古历史10个文件



我有一个存储stuff文档的stuffs-historic集合。我想把最后的10 stuffs存储在这个集合中,当保存一个新的stuff时,如果已经保存了10个东西,它应该替换最旧的。是否有可能以一种更优化的方式做到这一点?我通过以下步骤做到了这一点:

  1. 获取stuffs-history中所有stuffs与给定stuff-id按日期排序
  2. 如果返回的数组长度小于10,我复制stuffstuffs-historic
  3. 如果没有,我替换旧的。

如前所述,一个有上限的集合将是最好的起点。下面是一个使用节点驱动程序的示例:

const { MongoClient } = require('mongodb')
const uri = 'mongodb://localhost:27017/local'
const client = new MongoClient(uri)
const run = async () => {
try {
await client.connect()
const db = client.db('local')
await db.createCollection('capped', { capped: true, size: 10 }) // 10 = bytes, not records
const capped = db.collection('capped')
await capped.deleteMany()
let counter = 0
while (counter <= 30) {
await capped.insertOne({ counter: counter++ })
const current = (await capped.find().toArray()).map(d => d.counter).join(', ')
console.log('records ->', current)
}
await db.dropCollection('capped')
} finally {
await client.close()
}
}
run().catch(console.dir)

它将创建一个有上限的集合(容量为10字节,而不是10条记录),然后插入31条记录,但该集合最多只存储10个字节。最古老的记录首先被清除。每次插入之后,我记录集合中的文档,以证明文档的大小不超过10个,并且最早的文档首先被清除。

示例输出:

records -> 1
records -> 1, 2
records -> 1, 2, 3
records -> 1, 2, 3, 4
records -> 1, 2, 3, 4, 5
records -> 1, 2, 3, 4, 5, 6
records -> 1, 2, 3, 4, 5, 6, 7
records -> 2, 3, 4, 5, 6, 7, 8
records -> 3, 4, 5, 6, 7, 8, 9
records -> 4, 5, 6, 7, 8, 9, 10
records -> 5, 6, 7, 8, 9, 10, 11
records -> 6, 7, 8, 9, 10, 11, 12
records -> 7, 8, 9, 10, 11, 12, 13
records -> 8, 9, 10, 11, 12, 13, 14
records -> 9, 10, 11, 12, 13, 14, 15
records -> 10, 11, 12, 13, 14, 15, 16
records -> 11, 12, 13, 14, 15, 16, 17
records -> 12, 13, 14, 15, 16, 17, 18
records -> 13, 14, 15, 16, 17, 18, 19
records -> 14, 15, 16, 17, 18, 19, 20
records -> 15, 16, 17, 18, 19, 20, 21
records -> 16, 17, 18, 19, 20, 21, 22
records -> 17, 18, 19, 20, 21, 22, 23
records -> 18, 19, 20, 21, 22, 23, 24
records -> 19, 20, 21, 22, 23, 24, 25
records -> 20, 21, 22, 23, 24, 25, 26
records -> 21, 22, 23, 24, 25, 26, 27
records -> 22, 23, 24, 25, 26, 27, 28
records -> 23, 24, 25, 26, 27, 28, 29
records -> 24, 25, 26, 27, 28, 29, 30

为了获得准确的记录数量,使集合比你需要的更大(你必须计算出这将有多大的字节),和ObjectID(假设你使用默认值),将给你插入顺序,所以你可以反向排序并限制你的结果,例如:

db.capped.find().sort({_id:-1}).limit(5)

相关内容

最新更新