Skip to content

Commit 50a54cd

Browse files
author
Karl Seguin
committed
can drop an index using the same type of spec used to create an index
1 parent 6992c6b commit 50a54cd

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

lib/mongo/collection.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -497,6 +497,9 @@ def ensure_index(spec, opts={})
497497
#
498498
# @core indexes
499499
def drop_index(name)
500+
if name.is_a?(Array)
501+
return drop_index(index_name(name))
502+
end
500503
@cache[name.to_s] = nil
501504
@db.drop_index(@name, name)
502505
end
@@ -824,6 +827,14 @@ def normalize_hint_fields(hint)
824827
end
825828

826829
private
830+
831+
def index_name(spec)
832+
field_spec = parse_index_spec(spec)
833+
index_information.each do |index|
834+
return index[0] if index[1]['key'] == field_spec
835+
end
836+
nil
837+
end
827838

828839
def parse_index_spec(spec)
829840
field_spec = BSON::OrderedHash.new

test/collection_test.rb

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -762,6 +762,41 @@ def test_ensure_index_timeout
762762
assert_equal 1, @collection.size
763763
end
764764
end
765+
766+
context "Drop index " do
767+
setup do
768+
@@db.drop_collection('test-collection')
769+
@collection = @@db.collection('test-collection')
770+
end
771+
772+
should "drop an index" do
773+
@collection.create_index([['a', Mongo::ASCENDING]])
774+
assert @collection.index_information['a_1']
775+
@collection.drop_index([['a', Mongo::ASCENDING]])
776+
assert_nil @collection.index_information['a_1']
777+
end
778+
779+
should "drop an index which was given a specific name" do
780+
@collection.create_index([['a', Mongo::DESCENDING]], {:name => 'i_will_not_fear'})
781+
assert @collection.index_information['i_will_not_fear']
782+
@collection.drop_index([['a', Mongo::DESCENDING]])
783+
assert_nil @collection.index_information['i_will_not_fear']
784+
end
785+
786+
should "drops an composite index" do
787+
@collection.create_index([['a', Mongo::DESCENDING], ['b', Mongo::ASCENDING]])
788+
assert @collection.index_information['a_-1_b_1']
789+
@collection.drop_index([['a', Mongo::DESCENDING], ['b', Mongo::ASCENDING]])
790+
assert_nil @collection.index_information['a_-1_b_1']
791+
end
792+
793+
should "drops an index with symbols" do
794+
@collection.create_index([['a', Mongo::DESCENDING], [:b, Mongo::ASCENDING]])
795+
assert @collection.index_information['a_-1_b_1']
796+
@collection.drop_index([['a', Mongo::DESCENDING], [:b, Mongo::ASCENDING]])
797+
assert_nil @collection.index_information['a_-1_b_1']
798+
end
799+
end
765800

766801
context "Creating indexes " do
767802
setup do

0 commit comments

Comments
 (0)