Kosma Dunikowski
Kosma Dunikowski

Reputation: 172

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.

Upvotes: 11

Views: 5373

Answers (2)

Quentin
Quentin

Reputation: 1942

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.

Upvotes: 16

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230551

You could, for example, rename the underlying collection to something like tmp_cf20c448f824763454ada2c4b2434178. Then all new writes will go to a new, automatically created collection with old name, and you can, without haste and worries, read all documents and then simply drop that temp collection.

This kind of stuff is usually done more easily using the underlying ruby driver (10gen's mongo for mongoid 2.x or moped for mongoid 3.x).

Upvotes: 7

Related Questions