0

I have a setup where we are concerned about the size of the Mongo db going out of proportion.

capped collection is not an option for us as we are dynamically updating documents.

I am thinking of implementing it in such a way that if the count of the documents reaches 1000 in that collection then 500 documents would be deleted starting from the oldest.

So far i found the following to be most relevant however there is no way to limit and sort on the basis of time. https://docs.mongodb.com/manual/reference/method/Bulk.find.remove/#example

On researching further, I found:

How to delete N numbers of documents in mongodb

however i think there should be something more simple and efficient.

  • Well `_id` is already somewhat indicative of "time" as long as you have `ObjectId` values and have not replaced it with something else. Essentially you do actually want something like `.find().sort({ _id: 1 }).limit(500)`, just like the response referenced says. You can either feed the `_id` values to `.remove()` via `$in` or you can use the "first" and "last" `_id` values from the result in a range `.remove({ "_id" : { "$gte": lastId, "$lte": firstId })`. But if your expecting a `limit` directly on `remove()` then it does not exist. – Neil Lunn Apr 18 '18 at 01:49
  • FYI. `Bulk.find.remove()` and `Collection.remove()` are essentially the same method. Underneath, **ALL** API collection methods ( except the `findBy*` varieties ) actually call the `Bulk` API in their underlying implementation. Just not with a "batch" of operations. – Neil Lunn Apr 18 '18 at 01:51

0 Answers0