Reputation: 89
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.
Upvotes: 0
Views: 46
Reputation: 1035
If you're using this lib you can do this by following code:
$collection->insertOne($document);
if ($collection->count() > 10) {
$collection->findOneAndDelete([], ['sort' => 'id']);
}
Upvotes: 1