donglin6109 2018-06-08 23:21
浏览 56
已采纳

MongoDB使用PHP插入集合限制

So I am trying to find a way where I can limit the amount of documents stored in a db of MongoDB. For example let's say that I have 10 documents in a db and have a new document inserted every 1 min but I only want 10 document in my db, what I am trying to figure out is what is the best way to solve this in, when enter a new document that it deletes the oldest document .

for example with id "1,2,3,4,5,6,7,8,9,10" and when id 11 gets inserted I want that id 1 gets deleted and when id 12 gets inserted i want that id 2 gets deleted and so on,

I tested the TTL function for MongoDB but it doesn't give me the result that I am looking for.

Any help is greatly appreciated.

  • 写回答

1条回答 默认 最新

  • doupang9080 2018-06-08 23:39
    关注

    If you're using this lib you can do this by following code:

    $collection->insertOne($document);
    if ($collection->count() > 10) {
        $collection->findOneAndDelete([], ['sort' => 'id']);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装