moped icon indicating copy to clipboard operation
moped copied to clipboard

Support other Query Modification Operators

Open jacaetevha opened this issue 11 years ago • 0 comments

It would be nice if Moped supported other query modification operators (eg. $min, $max, $maxScan). Here's some code that would allow for $min and $max.

class Moped::Query
  # ...

  def count
    if operation.selector.has_key?("$min") || operation.selector.has_key?("$max")
      # Of course, a Moped specific exception should be raised.
      # It would be nice if this were configurable, so that it raised only if
      # some sort of "strict" option were set.
      raise StandardError, "count is not a supported operation with the $min or $max query modification operators"
    end
    result = collection.database.command(
      count: collection.name,
      query: selector,
      limit: operation.limit,
      skip: operation.skip
    )

    result["n"]
  end

  # ...

  def max_by(max_doc)
    new_selector = {
      "$query" => selector,
      "$max" => max_doc
    }
    if operation.selector.has_key? "$query"
      operation.selector.merge! new_selector
    else
      operation.selector = new_selector
    end
    self
  end

  def min_by(min_doc)
    new_selector = {
      "$query" => selector,
      "$min" => min_doc
    }
    if operation.selector.has_key? "$query"
      operation.selector.merge! new_selector
    else
      operation.selector = new_selector
    end
    self
  end
end

jacaetevha avatar Jun 19 '13 20:06 jacaetevha