Is there any way in mongoid to find and 'read' all documents in a collection while also removing them in one, atomic query?
So far I was using:
Model.collection.find().to_json
Model.delete_all
Which can be easily broken by adding more data to collection between those two instructions.
To delete all documents in a collection, pass an empty document ( {} ). Optional. To limit the deletion to just one document, set to true . Omit to use the default value of false and delete all documents matching the deletion criteria.
In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.
deleteMany() method. This method deletes multiple documents from the collection according to the filter. deleteMany() is a mongo shell method, which can delete multiple documents. This method can be used in the multi-document transactions.
Fetch all data from the collection If we want to fetch all documents from the collection the following mongodb command can be used : >db. userdetails. find(); or >db.
There is a simpler solution to this. You can do:
Model.collection.drop
It will drop the current collection, and create a new one (empty of course) with the same name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With