skip to Main Content

I have MongoDB replica set running in the local environment using docker.

And I am using nodejs to communicate with mongodb by using the offical mongodb driver(not mongoose)

So what I want is When a limit exided in a collection I want to delete other documents that is after added to the collection and maintain the number of documents in that limit

Lets say I have a collection called orders.My limit is 10.

Warning orders is just a collection name I am not storing orders on that collection or my application isn’t related to that. Just a random name

So nodejs application will add documents to orders collection. And while adding the documents to mongodb my limit has exided.

That means number of documents in orders collection is equal to 10. And I want nodejs to stop adding documents to mongodb

How do I do it.

(1) Can I create a index in MongoDB to do that

(2) Or should I do it in the nodejs application

Can anybody share there ideas for how to do that. I don’t have any code to share with
you because I still have not designed yet

2

Answers


  1. Chosen as BEST ANSWER

    I manage to delete documents in a collection when a limit reached in mongodb

    For that I created nodejs process that will do the job

    Warning this is not a library. it's a working nodejs process that will run very time checking for collections that you specified.

    There are some info that need to run the nodejs process and they are define with .env variables

    For more info check my GitHub page

    I hope this will help and this my first git repo


  2. Option 1:

    You can use the build in feature mongoDB provide called:
    "Capped collection"

    Example:

     db.createCollection("orders", { capped : true, size : 171798691840, max : 10 } )
    

    Explained:
    You set the max limit of capped collection to 10 documents and size of 171798691840 ( 10x 16MB ) , this way when you insert document No.11 , the document No.1 will be deleted and so one so it keep your collection always with 10 documents.

    Option 2:

    As suggested by @Charchit Kapoor You can emulate the behaviour programatically from the application checking documents count() before the insert/update query execution.

    Option 3:

    If you are using ATLAS( mongoDB SaaS ) there is option to set trigger

    Option 4:

    Another option is from the app you can set the collection to be readOnly after inserting the last document so every time the user attept to write afterwards to receive authorization exception.

    P.S.
    Btw setting such a limit looks abit strange , if you provide some more details about your specific use case and why you like to do it this way perhaps we may think on some better design options …?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search