2016-05-23 8 views
1

hatte ich die folgende Funktion, und wollte es ändert nur den letzten Artikel zurückgeben:

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

So habe ich versucht, diese:

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

die protokollierten Abfragen sieht ungefähr so ​​aus:

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

Aber ich erhalte den folgenden Fehler:

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

Was mache ich falsch?

Antwort

1

Per Casbah 2.7.3 Dokumente nimmt FindOne Abfrage und orderBy als Argumente

/** 
    * 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] 

Also ich denke, diese Methode

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

ich nicht getestet habe diesen Code sein sollte, ich diesen Willen hoffen Hilfe.