1

I had the following function, and wanted to modify it to return only the most recent item:

def findOne(filter: DBObject) = collection.findOne(filter)

So I tried this:

  def findOne(filter: DBObject) = {
    val query = MongoDBObject("$query" -> filter, "$orderby" -> MongoDBObject("created" -> -1))
    logger.info("Finding one: %s".format(query))
    collection.findOne(query)
  }

The logged queries looks something like this:

Finding one: { "$query" : { "_id" : { "$oid" : "5742d42154466f195b221175"}} , "$orderby" : { "created" : -1}}

But I get the following error:

com.mongodb.MongoQueryException: Query failed with error code 2 and error message 'unknown top level operator: $query'

What am I doing wrong?

fredley
  • 32,953
  • 42
  • 145
  • 236

1 Answers1

1

As per casbah 2.7.3 documents findOne takes query and orderBy as arguments

/**
   * Returns a single object from this collection matching the query.
   *
   * @param o           the query object
   * @param fields      (optional) fields to return
   * @param orderBy     (optional) a document whose fields specify the attributes on which to sort the result set.
   * @param readPrefs   (optional)
   * @param maxTime     (optional) the maximum duration that the server will allow this operation to execute before killing it
   *
   * @return            (Option[T]) Some() of the object found, or <code>None</code> if no such object exists
   */
  def findOne[A <% DBObject, B <% DBObject, C <% DBObject](o: A = MongoDBObject.empty,
                                                           fields: B = MongoDBObject.empty,
                                                           orderBy: C = MongoDBObject.empty,
                                                           readPrefs: ReadPreference = getReadPreference,
                                                           maxTime: Duration = Duration(0, MILLISECONDS)): Option[T]

So i think this method should be

def findOne(filter: DBObject) = {
    collection.findOne(filter,orderBy =MongoDBObject("created" -> -1))
  }

i did not tested this code, i hope this will help.