Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and remove all in mongo/mongoid

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.

like image 379
Kosma Dunikowski Avatar asked Sep 03 '12 10:09

Kosma Dunikowski


People also ask

How do I delete all entries in MongoDB?

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.

What does find () do in MongoDB?

In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.

How do I delete multiple ids in MongoDB?

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.

How get all items from MongoDB?

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.


1 Answers

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.

like image 67
Quentin Avatar answered Oct 16 '22 02:10

Quentin