【问题标题】:Mongo historic of 10 documents10 个文档的 Mongo 历史记录
【发布时间】:2022-12-18 09:21:31
【问题描述】:

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

  1. 获取我在stuffs-history中的所有stuffs,并按给定的stuff-id按日期排序
  2. 如果返回的数组长度小于10,我copy the stuff to stuffs-historic
  3. 如果没有,我将替换最旧的。

【问题讨论】:

  • capped collection是你要找的吗?
  • 实际上不是,因为我只能拥有 10 个 stuff-id,而不是整个系列最多 10 个

标签: mongodb


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-14
    • 2012-04-25
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多