From 50a54cdcc096a40f16baea8f0637f90e585e35da Mon Sep 17 00:00:00 2001 From: Karl Seguin Date: Tue, 31 May 2011 19:52:50 +0800 Subject: [PATCH] can drop an index using the same type of spec used to create an index --- lib/mongo/collection.rb | 11 +++++++++++ test/collection_test.rb | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/lib/mongo/collection.rb b/lib/mongo/collection.rb index 056b079..63dcc3e 100644 --- a/lib/mongo/collection.rb +++ b/lib/mongo/collection.rb @@ -497,6 +497,9 @@ module Mongo # # @core indexes def drop_index(name) + if name.is_a?(Array) + return drop_index(index_name(name)) + end @cache[name.to_s] = nil @db.drop_index(@name, name) end @@ -824,6 +827,14 @@ module Mongo end private + + def index_name(spec) + field_spec = parse_index_spec(spec) + index_information.each do |index| + return index[0] if index[1]['key'] == field_spec + end + nil + end def parse_index_spec(spec) field_spec = BSON::OrderedHash.new diff --git a/test/collection_test.rb b/test/collection_test.rb index 811c83d..84afeb9 100644 --- a/test/collection_test.rb +++ b/test/collection_test.rb @@ -762,6 +762,41 @@ class TestCollection < Test::Unit::TestCase assert_equal 1, @collection.size end end + + context "Drop index " do + setup do + @@db.drop_collection('test-collection') + @collection = @@db.collection('test-collection') + end + + should "drop an index" do + @collection.create_index([['a', Mongo::ASCENDING]]) + assert @collection.index_information['a_1'] + @collection.drop_index([['a', Mongo::ASCENDING]]) + assert_nil @collection.index_information['a_1'] + end + + should "drop an index which was given a specific name" do + @collection.create_index([['a', Mongo::DESCENDING]], {:name => 'i_will_not_fear'}) + assert @collection.index_information['i_will_not_fear'] + @collection.drop_index([['a', Mongo::DESCENDING]]) + assert_nil @collection.index_information['i_will_not_fear'] + end + + should "drops an composite index" do + @collection.create_index([['a', Mongo::DESCENDING], ['b', Mongo::ASCENDING]]) + assert @collection.index_information['a_-1_b_1'] + @collection.drop_index([['a', Mongo::DESCENDING], ['b', Mongo::ASCENDING]]) + assert_nil @collection.index_information['a_-1_b_1'] + end + + should "drops an index with symbols" do + @collection.create_index([['a', Mongo::DESCENDING], [:b, Mongo::ASCENDING]]) + assert @collection.index_information['a_-1_b_1'] + @collection.drop_index([['a', Mongo::DESCENDING], [:b, Mongo::ASCENDING]]) + assert_nil @collection.index_information['a_-1_b_1'] + end + end context "Creating indexes " do setup do