Permalink
Browse files

Add sorting

  • Loading branch information...
1 parent 81157c2 commit f46b21e55a45c2f89970f0c370faa5a047956270 @gdb committed Jul 11, 2011
Showing with 41 additions and 1 deletion.
  1. +39 −0 lib/embedded-mongo/backend/collection.rb
  2. +2 −1 lib/embedded-mongo/cursor.rb
@@ -18,6 +18,7 @@ def insert_documents(documents)
def find(selector, opts)
limit = opts.delete(:limit)
+ sort = opts.delete(:sort)
raise ArgumentError.new("Unrecognized opts: #{opts.inspect}") unless opts.empty?
results = []
@@ -27,7 +28,12 @@ def find(selector, opts)
break if limit > 0 and results.length >= limit
end
end
+
EmbeddedMongo.log.info("Query has #{results.length} matches")
+ if sort
+ sort = [sort] unless sort.first.kind_of?(Array)
+ results.sort! { |x, y| sort_cmp(sort, x, y) }
+ end
results
end
@@ -81,6 +87,39 @@ def insert(doc)
@data << doc
end
+ def sort_cmp(sort, x, y)
+ sort.each do |field, direction|
+ x_val = x[field]
+ y_val = y[field]
+ if direction.to_s == 'ascending' or direction.to_s == 'asc'
+ if x_val.kind_of?(Numeric) and y_val.kind_of?(Numeric)
+ cmp = x_val <=> y_val
+ elsif x_val.kind_of?(Numeric)
+ cmp = -1
+ elsif y_val.kind_of?(Numeric)
+ cmp = 1
+ else
+ cmp = 0
+ end
+ return cmp if cmp != 0
+ elsif direction.to_s == 'descending' or direction.to_s == 'desc'
+ if x_val.kind_of?(Numeric) and y_val.kind_of?(Numeric)
+ cmp = y_val <=> x_val
+ elsif x_val.kind_of?(Numeric)
+ cmp = 1
+ elsif y_val.kind_of?(Numeric)
+ cmp = -1
+ else
+ cmp = 0
+ end
+ return cmp if cmp != 0
+ else
+ raise NotImplementedError.new("Unrecognized sort [field, direction] = [#{field.inspect}, #{direction.inspect}] (full spec #{sort.inspect}")
+ end
+ end
+ 0
+ end
+
def selector_match?(selector, doc)
raise NotImplementedError.new('Does not current support $where queries') if selector.has_key?('$where')
selector.all? { |k, v| partial_match?(v, doc[k]) }
@@ -8,7 +8,8 @@ def send_initial_query
if @query_run
false
else
- results = @connection.request(:find, @db.name, @collection.name, selector, :limit => @limit)
+ results = @connection.request(:find, @db.name, @collection.name, selector,
+ :limit => @limit, :sort => @order)
@returned += results.length
@cache += results
@query_run = true

0 comments on commit f46b21e

Please sign in to comment.