Added sort() method to Cursor Class, with tests and docs.

This commit is contained in:
mbernstein 2009-09-04 19:04:11 -04:00 committed by Mike Dirolf
parent 3321a90739
commit bdafae6eeb
2 changed files with 29 additions and 0 deletions

View File

@ -72,6 +72,18 @@ module Mongo
return 0 if response['errmsg'] == "ns missing" return 0 if response['errmsg'] == "ns missing"
raise OperationFailure, "Count failed: #{response['errmsg']}" raise OperationFailure, "Count failed: #{response['errmsg']}"
end end
# Sort the results of the query with a hash of keys and orders
#
# Sorts should be formed as such:
# {:name=>-1} (sort by name, descending) OR {:name=>1} (sort by name, ascending)
# options are stackable, with the last option being the priority, i.e.:
# {:name => -1, :age => 1} (name descending, age asending)
def sort(order_hash = {})
raise InvalidOperation, "can't call Cursor#sort on a used cursor" if @query_run
@query.order_by = order_hash
self
end
# Limits the number of results to be returned by this cursor. # Limits the number of results to be returned by this cursor.
# #

View File

@ -57,6 +57,23 @@ class CursorTest < Test::Unit::TestCase
assert_equal 0, @@db['acollectionthatdoesn'].count() assert_equal 0, @@db['acollectionthatdoesn'].count()
end end
def test_sort
@@coll.clear
5.times{|x| @@coll.insert({"a" => x, "b" => 5-x}) }
assert_kind_of Cursor, @@coll.find().sort({:a=>1})
assert_equal 0, @@coll.find().sort({:a => 1}).next_object["a"]
assert_equal 4, @@coll.find().sort({:a => -1}).next_object["a"]
assert_equal 1, @@coll.find().sort({:a => 1, :b => 1}).next_object["b"]
assert_equal 5, @@coll.find().sort({:a => 1, :b => -1}).next_object["b"]
assert_equal 4, @@coll.find().sort({:a => 1}).sort({:a => -1}).next_object["a"]
assert_equal 4, @@coll.find().sort({:a => 1}).sort({:a => -1}).next_object["a"]
end
def test_limit def test_limit
@@coll.clear @@coll.clear