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

时间:2016-05-23 10:01:57

标签: mongodb scala casbah

我有以下功能,并希望修改它以仅返回最近的项目:

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'

我做错了什么?

1 个答案:

答案 0 :(得分:1)

根据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))
  }

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

相关问题