You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Mongoose删除MongoDB中除最后10条外的所有数据?

解决方案

要让数据库仅保留最近10条历史记录,你可以在创建新记录后自动清理超出数量限制的旧记录,直接修改create方法即可实现:

修改后的history.service.ts代码:

@Injectable()
export class HistoryService {
  constructor(
    @InjectModel(HistoryItem.name)
    private historyModel: Model<HistoryItemDocument>,
  ) {}
  async create(dto: CreateHistoryItemDto): Promise<HistoryItem> {
    // 创建新的历史记录
    const historyItem = await this.historyModel.create({ ...dto });

    // 清理超出数量限制的旧记录
    const totalCount = await this.historyModel.countDocuments();
    if (totalCount > maxNumberOfDBItemsToDisplay) {
      // 获取所有需要删除的旧记录ID(跳过最新的10条,剩下的都是要删除的)
      const oldItemIds = await this.historyModel
        .find()
        .sort({ _id: -1 }) // 利用MongoDB _id自带的时间戳倒序排序
        .skip(maxNumberOfDBItemsToDisplay)
        .select('_id');
      
      // 批量删除旧记录
      await this.historyModel.deleteMany({
        _id: { $in: oldItemIds.map(item => item._id) }
      });
    }

    return historyItem;
  }

  // 其余方法保持不变
  async getAll(): Promise<HistoryItem[]> {
    const allHistoryItems = await this.historyModel
      .find()
      .sort({ _id: -1 })
      .limit(maxNumberOfDBItemsToDisplay);   
    return allHistoryItems;
  }

  async getOne(id: ObjectId): Promise<HistoryItem> {
    const historyItem = await this.historyModel.findById(id);
    return historyItem;
  }

  async delete(id: ObjectId): Promise<ObjectId> {
    const historyItem = await this.historyModel.findByIdAndDelete(id);
    return historyItem.id;
  }
}

逻辑说明

  1. 创建新记录后,先统计数据库中历史记录的总条数
  2. 如果总数超过你设定的maxNumberOfDBItemsToDisplay(即10),就查询出最新10条之后的所有记录ID
  3. 通过deleteMany批量删除这些旧记录,确保数据库里始终只保留最近的10条

这种方式无需额外定时任务,每次添加新记录时自动维护数据量,逻辑简单直接。

内容的提问来源于stack exchange,提问作者tresor13

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 19:06:18