0

https://mongoosejs.com/docs/5.x/docs/api.html#model_Model.deleteMany

mongoose.connection.db.collection('sessions', function (err, collection) {
      collection.deleteMany({ session: { $not: /.*passport.*/i }}, function(err, result){
        console.log(err);
        console.log(result);
      });
    });

How do I limit this to only 100 documents? I tried

collection.deleteMany({ session: { $not: /.*passport.*/i }}, { limit: 100}, function(err, result){
        console.log(err);
        console.log(result);
      });

because it looked like from the documents that may worked, but it didn't it deleted every document. How do I limit to only 100 documents?

Anthony
  • 13,434
  • 14
  • 60
  • 80
  • Curious to know, why would you delete something with limit? – Ravi Kumar Gupta Oct 04 '21 at 15:22
  • 1
    @RaviKumarGupta because the collection is so large, if I try and remove them all at once it times out. Just trying this out as a workaround – Anthony Oct 04 '21 at 15:45
  • The deleteMany operation doesn't support a limit option. See [here](https://stackoverflow.com/a/22521865/16602311). – Giusseppe Oct 04 '21 at 15:48
  • As others have described in the comments above, you cannot successfully issue a delete with a limit. Instead, find N number the IDs of the records you want to delete, then issue the delete statement. https://stackoverflow.com/questions/19065615/how-to-delete-n-numbers-of-documents-in-mongodb – barrypicker Oct 04 '21 at 16:18
  • @barrypicker Thanks guys for the explanation, which is odd is that I tried that in the mongoshell and it didn't work. I suppose I will try with mongoose in a script. – Anthony Oct 04 '21 at 16:54
  • @Anthony I delete content from my collection(>40mn) with query (on epoch). That's the only way I understand can limit delete :) – Ravi Kumar Gupta Oct 04 '21 at 17:13
  • Yeah I'm trying to delete around 17 million items. Mongodb times out before I ever get it done. And it seems it does a find first before it does a delete, because none of them end up getting deleted. – Anthony Oct 04 '21 at 17:48

0 Answers0