I have a necessity to remove all data from mongo collection. Droping of collection works faster than collection.remove(new BasicDBObject()). But it also removes index definitions. Therefore I want to restore index definitions after collection dropping.
In general I have following plan:
- Get all index definitions before dropping:
http://www.mongodb.org/display/DOCS/Java+Tutorial#JavaTutorial-GettingaListofIndexesonaCollection - Recreate definitions after dropping: http://www.mongodb.org/display/DOCS/Java+Tutorial#JavaTutorial-CreatingAnIndex
The issue for me is exact value that should be retrieved/passed for index recreation. E.g. will following correct work for all types of indexes:
List<DBObject> storedDefinitions = coll.getIndexInfo();
coll.drop();
for (DBObject storedDefinition : storedDefinitions) {
coll.createIndex(storedDefinition.get("key"));
}
If no – what is the best way to achieve my goals?
Thanks for any help!
You’re close. You will need to read the index options of the retrieved indexes and apply those to the newly created index using the createIndex(DBObject key, DBObject options) version of the method.