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']);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?