ReactiveMongo:如何使用投影

时间:2014-02-21 18:28:54

标签: json mongodb scala reactivemongo

我在使用ReactiveMongo从MongoDB查询文档时尝试过滤掉password字段:

val projection = Json.obj("password" -> 0)

def find(selector: JsValue, projection: Option[JsValue]) = {
  val query = collection.genericQueryBuilder.query(selector)
  projection.map(query.projection(_))
  query.cursor[JsValue].collect[Vector](perPage).transform(
    success => success,
    failure => failure match {
      case e: LastError => DaoException(e.message, Some(DATABASE_ERROR))
    }
  )
}

上面的代码没有效果......我也得到了password字段。如果我从mongo客户端尝试以下操作,那么它可以工作,并且不会返回password

db.users.find( { username: 'j3d' }, { password:0} )

我错过了什么吗?

1 个答案:

答案 0 :(得分:2)

以下是解决方案:

def find(selector: JsValue, projection: Option[JsValue]) = {
  var query = collection.genericQueryBuilder.query(selector)
  projection.map(query = query.projection(_))

  query.cursor[JsValue].collect[Vector](perPage).transform(
    success => success,
    failure => failure match {
      case e: LastError => DaoException(e.message, Some(DATABASE_ERROR))
    }
  )
}

或者:

def find(selector: JsValue, projection: Option[JsValue]) = {
  val query = collection.genericQueryBuilder
    .query(selector)
    .projection(projection.getOrElse(Json.obj())

  query.cursor[JsValue].collect[Vector](perPage).transform(
    success => success,
    failure => failure match {
      case e: LastError => DaoException(e.message, Some(DATABASE_ERROR))
    }
  )
}

我希望有所帮助。