MongoDB.live, free & fully virtual. Register Now MongoDB.live, free & fully virtual. Register Now

Delete Many with Limit

Does Golang support Delete with Limit in addition to a filter? We need to run a periodic cleanup, and we need it to be quick, so do not want to delete more than 1000 documents at a time. So wanted to do something like this https://docs.mongodb.com/manual/reference/command/delete/#dbcmd.delete , but looking at the delete many, it does not seem to support the limit. Will you be adding this support?

Hi @parvathi_nair,

The best way to perform this operation is by fetching the needed for cleanup _id with a query using a limit and than pass it to a bulk delete bulk.find({_id : xxxxx}).remove():
https://docs.mongodb.com/manual/reference/method/Bulk.find.remove/

Than execute the batch in 1000 chunks.

Please note that a better cleanup maybe using ttl index on a date field:
https://docs.mongodb.com/manual/core/index-ttl/

Best
Pavel

1 Like

Also, the server-side delete command doesn’t actually support an arbitrary limit. Per https://docs.mongodb.com/manual/reference/command/delete/#deletes-array-limit, the limit can be 1 to delete no more than one document and 0 to delete all documents that match the filter. These values map to the DeleteOne and DeleteMany functions in the Go driver, respectively.

– Divjot

1 Like

Thanks for the reply. I noticed the limit as 0 or 1 after I posted the message. I ended up using the id range to delete in batches.