From 5a81cb70eee81e9387ee125c0ea8cb5bb1e6c329 Mon Sep 17 00:00:00 2001 From: Kyle Banker Date: Tue, 27 Oct 2009 14:05:45 -0400 Subject: [PATCH] Added Collection#distinct [RUBY-61] --- lib/mongo/collection.rb | 22 ++++++++++++++++++++++ lib/mongo/errors.rb | 3 +++ test/test_collection.rb | 15 +++++++++++++++ 3 files changed, 40 insertions(+) diff --git a/lib/mongo/collection.rb b/lib/mongo/collection.rb index b27be8b..29ca43e 100644 --- a/lib/mongo/collection.rb +++ b/lib/mongo/collection.rb @@ -383,6 +383,28 @@ EOS return @db.eval(Code.new(group_function, scope))["result"] end + # Returns a list of distinct values for +key+ across all + # documents in the collection. The key may use dot notation + # to reach into an embedded object. + # @collection.save({:zip => 10010, :name => {:age => 27}}) + # @collection.save({:zip => 94108, :name => {:age => 24}}) + # @collection.save({:zip => 10010, :name => {:age => 27}}) + # @collection.save({:zip => 99701, :name => {:age => 24}}) + # @collection.save({:zip => 94108, :name => {:age => 27}}) + # + # @collection.distinct(:zip) + # [10010, 94108, 99701] + # @collection.distinct("name.age") + # [27, 24] + def distinct(key) + raise MongoArgumentError unless [String, Symbol].include?(key.class) + command = OrderedHash.new + command[:distinct] = @name + command[:key] = key.to_s + + @db.db_command(command)["values"] + end + # Rename this collection. # # If operating in auth mode, client must be authorized as an admin to diff --git a/lib/mongo/errors.rb b/lib/mongo/errors.rb index d4ce9ef..76274ed 100644 --- a/lib/mongo/errors.rb +++ b/lib/mongo/errors.rb @@ -21,6 +21,9 @@ module Mongo # Raised when configuration options cause connections, queries, etc., to fail. class ConfigurationError < MongoRubyError; end + # Raised when invalid arguments are sent to Mongo Ruby methods. + class MongoArgumentError < MongoRubyError; end + # Raised when a database operation fails. class OperationFailure < RuntimeError; end diff --git a/test/test_collection.rb b/test/test_collection.rb index 927399c..a83325c 100644 --- a/test/test_collection.rb +++ b/test/test_collection.rb @@ -59,6 +59,21 @@ class TestCollection < Test::Unit::TestCase assert_equal 5, @@db.collection("test.foo").find_one()["x"] 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}]) + + assert_equal [0, 1, 2, 3], @@test.distinct(:a).sort + assert_equal ["a", "b", "c"], @@test.distinct("b.c").sort + end + end + def test_safe_insert a = {"hello" => "world"} @@test.insert(a)