2

I'm looking to limit the number of documents in a collection dynamically. For example, I will store upto 1000 documents for GOLD members, and 500 for SILVER members. When the maximum is reached for a particular user and a new document is created by them, the oldest document belonging to that user should be deleted.

Capped collections aren't suitable for something like this so I was wondering if it is up to me to add my own logic to implement this "queue type" feature or whether there is some tried and tested approach out there somewhere?

tommyd456
  • 10,443
  • 26
  • 89
  • 163
  • Hope this gives you an idea - http://stackoverflow.com/questions/26220879/how-to-store-an-ordered-set-of-documents-in-mongodb-without-using-a-capped-colle/26230177#26230177 – BatScream Feb 03 '15 at 17:42

1 Answers1

1

Use a pre save middleware that performs the "capping" on every save.

schema.pre('save', function(next) {
    model.find({}, {
        sort: { $natural: -1 }, // sort in reverse
        limit: 50,             //  to get last 50 docs
    }).remove();
    next();
});
laggingreflex
  • 32,948
  • 35
  • 141
  • 196
  • This looks interesting. How can I use this per user though? – tommyd456 Feb 06 '15 at 11:07
  • How's the collection related to the user? Do this on that collection. – laggingreflex Feb 06 '15 at 12:08
  • I am trying to understand this @laggingreflex so this should find the last 50 docs, or does this say - check for 50 docs, and if there is 50 remove the last one? because this looks like it just removes the last one without checking, or does it do both? – Lion789 Jul 08 '15 at 23:18
  • @Lion789 It finds all documents (as an array), then sorts the array in reverse, and then keeps only 50 or less elements. And then it removes those elements (documents). – laggingreflex Jul 09 '15 at 00:07