diff --git a/lib/mongo/collection.rb b/lib/mongo/collection.rb index 4dcad84..96cc44e 100644 --- a/lib/mongo/collection.rb +++ b/lib/mongo/collection.rb @@ -441,11 +441,17 @@ EOS # [10010, 94108, 99701] # @collection.distinct("name.age") # [27, 24] - def distinct(key) + # + # You may also pass a document selector as the second parameter + # to limit the documents over which distinct is run: + # @collection.distinct("name.age", {"name.age" => {"$gt" => 24}}) + # [27] + def distinct(key, query=nil) raise MongoArgumentError unless [String, Symbol].include?(key.class) command = OrderedHash.new command[:distinct] = @name - command[:key] = key.to_s + command[:key] = key.to_s + command[:query] = query @db.command(command)["values"] end diff --git a/test/test_collection.rb b/test/test_collection.rb index 46685cb..ba461d9 100644 --- a/test/test_collection.rb +++ b/test/test_collection.rb @@ -75,17 +75,29 @@ class TestCollection < Test::Unit::TestCase end if @@version > "1.1" - def test_distinct - @@test.remove - @@test.insert([{:a => 0, :b => {:c => "a"}}, - {:a => 1, :b => {:c => "b"}}, - {:a => 1, :b => {:c => "c"}}, - {:a => 2, :b => {:c => "a"}}, - {:a => 3}, - {:a => 3}]) + context "distinct queries" do + setup do + @@test.remove + @@test.insert([{:a => 0, :b => {:c => "a"}}, + {:a => 1, :b => {:c => "b"}}, + {:a => 1, :b => {:c => "c"}}, + {:a => 2, :b => {:c => "a"}}, + {:a => 3}, + {:a => 3}]) + end - assert_equal [0, 1, 2, 3], @@test.distinct(:a).sort - assert_equal ["a", "b", "c"], @@test.distinct("b.c").sort + should "return distinct values" do + assert_equal [0, 1, 2, 3], @@test.distinct(:a).sort + assert_equal ["a", "b", "c"], @@test.distinct("b.c").sort + end + + should "filter collection with query" do + assert_equal [2, 3], @@test.distinct(:a, {:a => {"$gt" => 1}}).sort + end + + should "filter nested objects" do + assert_equal ["a", "b"], @@test.distinct("b.c", {"b.c" => {"$ne" => "c"}}).sort + end end end