未知的顶级运算符:使用 findOne 时的 $query

unknown top level operator: $query when using findOne

我有以下功能,想将其修改为 return 只有最近的项目:

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

所以我尝试了这个:

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

记录的查询看起来像这样:

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

但我收到以下错误:

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

我做错了什么?

根据 casbah 2.7.3 文档,findOne 将查询和 orderBy 作为参数

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

所以我觉得这个方法应该是

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

我没有测试过这段代码,我希望这会有所帮助。