本文整理汇总了Scala中reactivemongo.play.json.collection.JSONCollection类的典型用法代码示例。如果您正苦于以下问题:Scala JSONCollection类的具体用法?Scala JSONCollection怎么用?Scala JSONCollection使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了JSONCollection类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: collection
//设置package包名称以及导入依赖的类
package dao
import play.api.libs.json._
import play.modules.reactivemongo.ReactiveMongoApi
import play.modules.reactivemongo.json._
import reactivemongo.api.commands.WriteResult
import reactivemongo.play.json.collection.JSONCollection
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
trait Repository[T] {
val collectionName: String
implicit val format: OFormat[T]
def collection()(implicit reactiveMongoApi: ReactiveMongoApi) = reactiveMongoApi.database.map(_.collection[JSONCollection](collectionName))
def save(doc: T)(implicit reactiveMongoApi: ReactiveMongoApi): Future[WriteResult] = {
collection.flatMap { c =>
c.insert(doc)
}
}
def update(selector: JsObject, update: JsObject)(implicit reactiveMongoApi: ReactiveMongoApi): Future[WriteResult] = {
collection.flatMap { c =>
c.update(selector, update, upsert = false)
}
}
def upsert(selector: JsObject, doc: T)(implicit reactiveMongoApi: ReactiveMongoApi): Future[WriteResult] = {
collection.flatMap { c =>
c.update(selector, Json.obj("$set" -> doc), upsert = true)
}
}
def remove(query: JsObject)(implicit reactiveMongoApi: ReactiveMongoApi): Future[WriteResult] = {
collection.flatMap { c =>
c.remove(query)
}
}
def list(query: JsObject = Json.obj())(implicit reactiveMongoApi: ReactiveMongoApi): Future[Seq[T]] = {
collection.flatMap { c =>
c.find(query).cursor[T]().collect[Seq]()
}
}
def list(implicit reactiveMongoApi: ReactiveMongoApi): Future[Seq[T]] = list()
def findByOpt(query: JsObject)(implicit reactiveMongoApi: ReactiveMongoApi): Future[Option[T]] = {
collection.flatMap { c =>
c.find(query).one[T]
}
}
}
示例2: PublishedStoryDAOImpl
//设置package包名称以及导入依赖的类
package io.soheila.cms.daos
import javax.inject.Inject
import grizzled.slf4j.Logger
import io.soheila.cms.daos.exceptions.DAOException
import io.soheila.cms.entities.Story
import play.api.libs.json.Json
import play.modules.reactivemongo.ReactiveMongoApi
import reactivemongo.play.json.collection.JSONCollection
import scala.concurrent.{ ExecutionContext, Future }
class PublishedStoryDAOImpl @Inject() (override val reactiveMongoApi: ReactiveMongoApi)(implicit override val ec: ExecutionContext) extends StoryDAOImpl(reactiveMongoApi) {
private val logger = Logger[this.type]
override def collection: Future[JSONCollection] = reactiveMongoApi.database.map(_.collection[JSONCollection]("published_stories"))
override def findAndUpdateLatest(story: Story, upsert: Boolean): Future[Either[DAOException, Option[Story]]] = {
findAndUpdateByCriteria(Json.obj("uuid" -> story.uuid.get), story, upsert)
.map {
case Left(err) => Left(DAOException(err.getMessage, err))
case Right(res) => Right(res)
}
}
}
示例3: find
//设置package包名称以及导入依赖的类
package repos
import javax.inject.Inject
import play.api.libs.json.{JsObject, Json}
import play.modules.reactivemongo.ReactiveMongoApi
import play.modules.reactivemongo.json._
import reactivemongo.api.ReadPreference
import reactivemongo.api.commands.WriteResult
import reactivemongo.bson.{BSONDocument, BSONObjectID}
import reactivemongo.play.json.collection.JSONCollection
import scala.concurrent.{ExecutionContext, Future}
trait RepoLike {
def find()(implicit ec: ExecutionContext): Future[List[JsObject]]
def select(selector: BSONDocument)(implicit ec: ExecutionContext): Future[Option[JsObject]]
def update(selector: BSONDocument, update: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult]
def remove(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult]
def save(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult]
}
abstract class Repo @Inject()(reactiveMongoApi: ReactiveMongoApi) extends RepoLike {
val collectionName: String
override def find()(implicit ec: ExecutionContext): Future[List[JsObject]] = {
collection.find(Json.obj())
.cursor[JsObject](ReadPreference.Primary)
.collect[List](100)
}
override def select(selector: BSONDocument)(implicit ec: ExecutionContext): Future[Option[JsObject]] = {
collection.find(selector).one[JsObject]
}
override def update(selector: BSONDocument, update: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.update(selector, update)
}
def collection: JSONCollection = reactiveMongoApi.db.collection[JSONCollection](collectionName)
override def remove(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.remove(document)
}
override def save(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.update(BSONDocument("_id" -> document.get("_id").getOrElse(BSONObjectID.generate)), document, upsert = true)
}
}
示例4: StashStore
//设置package包名称以及导入依赖的类
package services
import javax.inject.Inject
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json._
import play.modules.reactivemongo.ReactiveMongoApi
import reactivemongo.play.json.collection.JSONCollection
import scala.concurrent.Future
class StashStore @Inject()(val reactiveMongoApi: ReactiveMongoApi) {
implicit val locationFormat: OFormat[Stash] = new OFormat[Stash] {
override def writes(o: Stash): JsObject = Json.obj("_id" -> o._id, "stash" -> Stash.stashWrites.writes(o))
override def reads(json: JsValue): JsResult[Stash] = Stash.stashReads.reads((json \ "stash").get)
}
implicit val jsonFormat: OWrites[JsObject] = new OWrites[JsObject] {
override def writes(o: JsObject): JsObject = o
}
val locationCollection = reactiveMongoApi.database.map(d => d.collection[JSONCollection]("stashes"))
def addStash(stash: Stash): Future[Stash] = {
locationCollection.flatMap(l => l.insert[Stash](stash).map(_ => stash))
}
def getStashes(): Future[Seq[Stash]] = {
locationCollection.flatMap(l => l.find(Json.obj()).cursor[Stash]().collect[List]())
}
def getStash(id: String): Future[Option[Stash]] = {
locationCollection.flatMap(l => l.find(Json.obj("_id" -> id)).cursor[Stash].collect[List]().map {
case List(matchingStash) => Some(matchingStash)
case _ => None
})
}
def deleteStash(id: String): Future[Boolean] = {
locationCollection.flatMap(l => l.findAndRemove(Json.obj("_id" -> id)).map(result => true))
}
def updateStash(updatedStash: Stash): Future[Stash] = {
locationCollection.flatMap(l => l.findAndUpdate(Json.obj("_id" -> updatedStash._id), updatedStash).map(_ => updatedStash))
}
}
示例5: PasswordInfoDao
//设置package包名称以及导入依赖的类
package daos
import javax.inject.Inject
import scala.concurrent.{Await, Future}
import com.mohiva.play.silhouette.api.LoginInfo
import com.mohiva.play.silhouette.api.util.PasswordInfo
import com.mohiva.play.silhouette.persistence.daos.DelegableAuthInfoDAO
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json._
import play.modules.reactivemongo.ReactiveMongoApi
import play.modules.reactivemongo.json._
import reactivemongo.play.json.collection.JSONCollection
import models.User
import User._
import scala.concurrent.duration.Duration
class PasswordInfoDao @Inject() (
val reactiveMongoApi: ReactiveMongoApi
) extends DelegableAuthInfoDAO[PasswordInfo] {
val users = Await.result(reactiveMongoApi.database.map(_.collection[JSONCollection]("users")), Duration.Inf)
def find(loginInfo:LoginInfo):Future[Option[PasswordInfo]] = for {
user <- users.find(Json.obj(
"profiles.loginInfo" -> loginInfo
)).one[User]
} yield user.flatMap(_.profiles.find(_.loginInfo == loginInfo)).flatMap(_.passwordInfo)
def add(loginInfo:LoginInfo, authInfo:PasswordInfo):Future[PasswordInfo] =
users.update(Json.obj(
"profiles.loginInfo" -> loginInfo
), Json.obj(
"$set" -> Json.obj("profiles.$.passwordInfo" -> authInfo)
)).map(_ => authInfo)
def update(loginInfo:LoginInfo, authInfo:PasswordInfo):Future[PasswordInfo] =
add(loginInfo, authInfo)
def save(loginInfo:LoginInfo, authInfo:PasswordInfo):Future[PasswordInfo] =
add(loginInfo, authInfo)
def remove(loginInfo:LoginInfo):Future[Unit] =
users.update(Json.obj(
"profiles.loginInfo" -> loginInfo
), Json.obj(
"$pull" -> Json.obj(
"profiles" -> Json.obj("loginInfo" -> loginInfo)
)
)).map(_ => ())
}
示例6: find
//设置package包名称以及导入依赖的类
package daos
import java.util.UUID
import javax.inject.Inject
import scala.concurrent.{Await, Future}
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json._
import play.modules.reactivemongo.ReactiveMongoApi
import play.modules.reactivemongo.json._
import reactivemongo.play.json.collection.JSONCollection
import models.UserToken
import scala.concurrent.duration.Duration
trait UserTokenDao {
def find(id:UUID):Future[Option[UserToken]]
def save(token:UserToken):Future[UserToken]
def remove(id:UUID):Future[Unit]
}
class MongoUserTokenDao @Inject() (
val reactiveMongoApi: ReactiveMongoApi
) extends UserTokenDao {
val tokens = Await.result(reactiveMongoApi.database.map(_.collection[JSONCollection]("tokens")), Duration.Inf)
def find(id:UUID):Future[Option[UserToken]] =
tokens.find(Json.obj("id" -> id)).one[UserToken]
def save(token:UserToken):Future[UserToken] = for {
_ <- tokens.insert(token)
} yield token
def remove(id:UUID):Future[Unit] = for {
_ <- tokens.remove(Json.obj("id" -> id))
} yield ()
}
示例7: OAuth1InfoDao
//设置package包名称以及导入依赖的类
package daos
import javax.inject.Inject
import scala.concurrent.{Await, Future}
import com.mohiva.play.silhouette.api.LoginInfo
import com.mohiva.play.silhouette.impl.providers.OAuth1Info
import com.mohiva.play.silhouette.persistence.daos.DelegableAuthInfoDAO
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json._
import play.modules.reactivemongo.ReactiveMongoApi
import play.modules.reactivemongo.json._
import reactivemongo.play.json.collection.JSONCollection
import models.User
import User._
import scala.concurrent.duration.Duration
class OAuth1InfoDao @Inject() (
val reactiveMongoApi: ReactiveMongoApi
) extends DelegableAuthInfoDAO[OAuth1Info] {
val users = Await.result(reactiveMongoApi.database.map(_.collection[JSONCollection]("users")), Duration.Inf)
def find(loginInfo:LoginInfo):Future[Option[OAuth1Info]] = for {
user <- users.find(Json.obj(
"profiles.loginInfo" -> loginInfo
)).one[User]
} yield user.flatMap(_.profiles.find(_.loginInfo == loginInfo)).flatMap(_.oauth1Info)
def add(loginInfo:LoginInfo, authInfo:OAuth1Info):Future[OAuth1Info] =
users.update(Json.obj(
"profiles.loginInfo" -> loginInfo
), Json.obj(
"$set" -> Json.obj("profiles.$.oauth1Info" -> authInfo)
)).map(_ => authInfo)
def update(loginInfo:LoginInfo, authInfo:OAuth1Info):Future[OAuth1Info] =
add(loginInfo, authInfo)
def save(loginInfo:LoginInfo, authInfo:OAuth1Info):Future[OAuth1Info] =
add(loginInfo, authInfo)
def remove(loginInfo:LoginInfo):Future[Unit] =
users.update(Json.obj(
"profiles.loginInfo" -> loginInfo
), Json.obj(
"$pull" -> Json.obj(
"profiles" -> Json.obj("loginInfo" -> loginInfo)
)
)).map(_ => ())
}
示例8: MasterActor
//设置package包名称以及导入依赖的类
package actors
import java.util.Date
import javax.inject.Inject
import akka.actor.Actor
import models.HourlyMessage
import play.api.libs.mailer.MailerClient
import play.api.libs.ws.WSClient
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import reactivemongo.play.json.collection.JSONCollection
import play.api.libs.json.Json
import play.modules.reactivemongo.json._
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import reactivemongo.api.ReadPreference
import reactivemongo.play.json.collection.JSONCollection
import services.Counter
import scala.concurrent.{ExecutionContext, Future}
import scala.util.{Failure, Success}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
class MasterActor @Inject()(mailerClient: MailerClient, val reactiveMongoApi: ReactiveMongoApi, ws: WSClient,counter: Counter) extends Actor with MongoController with ReactiveMongoComponents {
override val database = reactiveMongoApi.connection.database("dummy")
def receive = {
case HourlyMessage(message) => {
def patternFuture: Future[JSONCollection] = database.map(_.collection[JSONCollection]("testdb"))
val date = new Date()
val _count = counter.nextCount().toString
val _date = date.toString
for{
pattern <- patternFuture
lastError <- pattern.insert(Json.obj("count"-> _count,"date" -> _date))
}yield{
//Ok("Mongo LastError: %s".format(lastError))
println("count "+_count)
var status = 0
if(lastError.hasErrors){
status = 0
} else{
status = 1
}
status
}
}
}
}
示例9: Application
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.{Inject, Singleton}
import models._
import models.JsonFormats._
import org.slf4j.{Logger, LoggerFactory}
import play.api.libs.json.Json
import play.api.mvc._
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import play.modules.reactivemongo.json._
import reactivemongo.api.Cursor
import reactivemongo.play.json.collection.JSONCollection
import services.{UUIDGenerator,SimpleUUIDGenerator}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
@Singleton
class Application @Inject() (
val uuidGenerator: UUIDGenerator,
val reactiveMongoApi: ReactiveMongoApi
)
extends Controller
with MongoController
with ReactiveMongoComponents
{
private final val logger: Logger = LoggerFactory.getLogger(classOf[Application])
def collection: JSONCollection = db.collection[JSONCollection]("greek")
def index = Action.async {
logger.info("Serving index page...")
val cursor: Cursor[Sentence] = collection.
// find all people with name `name`
find(Json.obj("_id.scheme" -> "urn", "_id.namespace"->"cts", "_id.domain"->"greekLit", "_id.textgroup"->"tlg0003", "_id.work"->"tlg001", "_id.edition"->"perseus-grc1")).
// perform the query and get a cursor of JsObject
cursor[Sentence]
// gather all the JsObjects in a list
val futureUsersList: Future[List[Sentence]] = cursor.collect[List]()
// everything's ok! Let's reply with the array
futureUsersList.map { persons =>
Ok(Json.toJson(persons))
}
}
def randomUUID = Action {
logger.info("calling UUIDGenerator...")
Ok(uuidGenerator.generate.toString)
}
}
示例10: mongodb
//设置package包名称以及导入依赖的类
package uk.gov.bis.levyApiMock.mongo
import play.api.libs.json.Json.JsValueWrapper
import play.api.libs.json._
import play.modules.reactivemongo.ReactiveMongoApi
import reactivemongo.play.json._
import reactivemongo.play.json.collection.JSONCollection
import scala.concurrent.{ExecutionContext, Future}
trait MongoCollection[T] {
def mongodb: ReactiveMongoApi
def collectionName: String
def collectionF(implicit ec: ExecutionContext): Future[JSONCollection] = mongodb.database.map(_.collection[JSONCollection](collectionName))
def findMany(params: (String, JsValueWrapper)*)(implicit ec: ExecutionContext, reads: Reads[T]): Future[Seq[T]] = {
val selector = Json.obj(params: _*)
for {
collection <- collectionF
o <- collection.find(selector).cursor[JsObject]().collect[List](100)
} yield o.flatMap {
_.validate[T] match {
case JsSuccess(resp, _) => Some(resp)
case JsError(errs) => None
}
}
}
def findOne(params: (String, JsValueWrapper)*)(implicit ec: ExecutionContext, reads: Reads[T]): Future[Option[T]] = {
val selector = Json.obj(params: _*)
val of = for {
collection <- collectionF
o <- collection.find(selector).cursor[JsObject]().collect[List](1).map(_.headOption)
} yield o
of.map {
case Some(o) => o.validate[T] match {
case JsSuccess(resp, _) => Some(resp)
case JsError(errs) => None
}
case _ => None
}
}
def remove(params: (String, JsValueWrapper)*)(implicit ec: ExecutionContext): Future[Unit] = {
collectionF.map(coll => coll.remove(Json.obj(params: _*)))
}
}
示例11: authenticate
//设置package包名称以及导入依赖的类
package services
import javax.inject.Inject
import org.mindrot.jbcrypt.BCrypt
import play.api.libs.json.{JsObject, Json}
import play.modules.reactivemongo.ReactiveMongoApi
import reactivemongo.bson.BSONObjectID
import reactivemongo.play.json._
import reactivemongo.play.json.collection.JSONCollection
import scala.concurrent.{ExecutionContext, Future}
trait AuthService {
def authenticate(email:String,password:String)(implicit ec: ExecutionContext):Future[Option[String]]
}
class MongoAuthService @Inject()(val reactiveMongoApi: ReactiveMongoApi) extends AuthService {
val collection = "users"
override def authenticate(email: String, password: String)(implicit ec: ExecutionContext): Future[Option[String]] = {
for {
users <- reactiveMongoApi.database.map(_.collection[JSONCollection](collection))
userOpt <- users.find(Json.obj("email"->email)).one[JsObject]
authenticated <- userOpt.map { user =>
Future.successful(BCrypt.checkpw(password,(user \ "password").as[String]))
}.getOrElse(Future.successful(false))
id <- (userOpt,authenticated) match {
case (Some(user),true) =>
val _id:String= (user \ "_id").as[BSONObjectID].stringify
Future.successful(Some(_id))
case (None,_) => Future.successful(None)
case (_,false) => Future.successful(None)
}
} yield id
}
}
示例12: MongoUserActivityDAO
//设置package包名称以及导入依赖的类
package io.soheila.um.daos.activities
import javax.inject.Inject
import io.soheila.commons.crud.MongoCRUDDAO
import io.soheila.commons.entities.Page
import io.soheila.commons.exceptions.MongoDAOException
import io.soheila.um.entities.UserActivity
import io.soheila.um.vos.activities.UserActivityQuery
import play.api.libs.json.{ JsObject, Json }
import play.modules.reactivemongo.ReactiveMongoApi
import reactivemongo.api.indexes.{ Index, IndexType }
import reactivemongo.play.json.collection.JSONCollection
import scala.concurrent.{ ExecutionContext, Future }
class MongoUserActivityDAO @Inject() (val reactiveMongoApi: ReactiveMongoApi)(implicit override val ec: ExecutionContext)
extends MongoCRUDDAO[UserActivity, String] with UserActivityDAO {
override def collection: Future[JSONCollection] = reactiveMongoApi.database.map(_.collection[JSONCollection]("user_activity"))
override def find(userActivityQuery: UserActivityQuery, page: Int, limit: Int, sortFilter: Option[(String, Int)]): Future[Either[MongoDAOException, Page[UserActivity]]] = {
Json.toJson(userActivityQuery)
find(Json.toJson(userActivityQuery).as[JsObject], page, limit, sortFilter)
}
override def indexSet: Set[Index] = Set(
Index(Seq("userUUID" -> IndexType.Ascending)),
Index(Seq("activityType" -> IndexType.Ascending)),
Index(Seq("userIP" -> IndexType.Ascending)),
Index(Seq("userDevice" -> IndexType.Ascending)),
Index(Seq("timestamp" -> IndexType.Ascending))
)
}
示例13: MongoUserDAO
//设置package包名称以及导入依赖的类
package io.soheila.um.daos.accounts
import javax.inject.Inject
import com.mohiva.play.silhouette.api.LoginInfo
import io.soheila.um.entities.User
import io.soheila.um.exceptions.UMDAOException
import io.soheila.commons.crud.MongoCRUDDAO
import play.api.libs.json._
import play.modules.reactivemongo.ReactiveMongoApi
import play.modules.reactivemongo.json._
import reactivemongo.api.indexes.IndexType.Geo2DSpherical
import reactivemongo.api.indexes.{ Index, IndexType }
import reactivemongo.play.json.collection.JSONCollection
import scala.concurrent.{ ExecutionContext, Future }
class MongoUserDAO @Inject() (val reactiveMongoApi: ReactiveMongoApi)(implicit override val ec: ExecutionContext)
extends MongoCRUDDAO[User, String] with UserDAO {
override def collection: Future[JSONCollection] = reactiveMongoApi.database.map(_.collection[JSONCollection]("users"))
def find(loginInfo: LoginInfo): Future[Option[User]] = {
collection.flatMap(_.find(Json.obj("loginInfo" -> loginInfo)).one[User])
}
override def archive(uuid: String): Future[Either[UMDAOException, Boolean]] = {
archive(uuid, archived = true)
}
override def restore(uuid: String): Future[Either[UMDAOException, Boolean]] = {
archive(uuid, archived = false)
}
private def archive(uuid: String, archived: Boolean): Future[Either[UMDAOException, Boolean]] = {
collection.flatMap(col => {
val updateOp = col.updateModifier(Json.obj("$set" -> Json.obj("archived" -> archived)), fetchNewObject = true)
col.findAndModify(Json.obj("uuid" -> uuid), updateOp) map {
entity => Right(true)
}
}).recover {
case err =>
Left(UMDAOException(err.getMessage, err))
}
}
override def indexSet: Set[Index] = Set(
Index(Seq("uuid" -> IndexType.Ascending), unique = true),
Index(Seq("email" -> IndexType.Ascending), unique = true),
Index(Seq("roles" -> IndexType.Ascending)),
Index(List("firstName" -> IndexType.Ascending, "lastName" -> IndexType.Ascending, "fullName" -> IndexType.Text)),
Index(Seq("createdOn" -> IndexType.Descending, "updatedOn" -> IndexType.Descending)),
Index(Seq(("coordinate", Geo2DSpherical)), Some("geo2DSphericalIdx")),
Index(List("attributes.key" -> IndexType.Ascending, "attributes.value" -> IndexType.Ascending))
)
}
示例14: TranslatorRepositoryImpl
//设置package包名称以及导入依赖的类
package Repositories.implements
import Repositories.TranslatorRepository
import com.google.inject.Inject
import models.Translator
import play.api.libs.json.{JsObject, Json}
import play.modules.reactivemongo.ReactiveMongoApi
import reactivemongo.api.{QueryOpts, ReadPreference}
import reactivemongo.api.commands.WriteResult
import reactivemongo.play.json.collection.JSONCollection
import utils.Pagination
import play.modules.reactivemongo.json._
import scala.concurrent.{ExecutionContext, Future}
class TranslatorRepositoryImpl @Inject()(reactiveMongoApi: ReactiveMongoApi) extends TranslatorRepository{
def collection(implicit ec: ExecutionContext) = reactiveMongoApi.database.map(_.collection[JSONCollection]("translators"))
override def getAllTranslators(pagination: Pagination, sortField: String)(implicit ec: ExecutionContext): Future[List[JsObject]] = {
var sort : Int = 1; var getField: String = sortField
if(sortField.startsWith("-")){
sort = -1; getField = sortField.drop(1)
}
val genericQueryBuilder = collection.map(_.find(Json.obj()).sort(Json.obj(getField -> sort)).options(QueryOpts(pagination.Offset)))
val cursor = genericQueryBuilder.map(_.cursor[JsObject](ReadPreference.Primary))
cursor.flatMap(_.collect[List](pagination.Limit))
}
override def insertTranslator(translator: Translator)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.flatMap(_.insert(translator))
}
override def count()(implicit ec: ExecutionContext): Future[Int] = {
val count = collection.flatMap(_.count()); count
}
}
示例15: MsgDAOImpl
//设置package包名称以及导入依赖的类
package models.daos
import java.util.UUID
import javax.inject.{ Inject, Singleton }
import mikanMessages.InternalMsg
import play.api.Configuration
import play.api.libs.json.Json
import play.modules.reactivemongo.ReactiveMongoApi
import reactivemongo.api.{ Cursor, ReadPreference }
import reactivemongo.play.json._
import reactivemongo.play.json.collection.JSONCollection
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
@Singleton
class MsgDAOImpl @Inject() (playConf: Configuration, val reactiveMongoApi: ReactiveMongoApi) extends MsgDAO {
private val msgCol: String = playConf.getString("mongo.collection.clientmsg").getOrElse("clientmsg")
def collection: Future[JSONCollection] = reactiveMongoApi.database.map(_.collection(msgCol))
def find(userID: UUID): Future[Option[InternalMsg]] =
collection.flatMap(_.find(Json.obj("userID" -> userID)).one[InternalMsg])
def save(msg: InternalMsg): Future[InternalMsg] = {
collection.flatMap(_.insert(msg))
Future.successful(msg)
}
// get all current msg filtered by topicList and userId
// note: if userId="" all objects will be retrieved, otherwise
// all msg BUT NOT those with the given userId
def findAll(topicList: List[String], userID: UUID): Future[List[InternalMsg]] = {
val qry = Json.obj("userID" -> Json.obj("$ne" -> userID), "topic" -> Json.obj("$in" -> topicList))
for {
colection <- collection
theList <- colection.find(qry).
cursor[InternalMsg](ReadPreference.nearest).
collect[List](-1, Cursor.FailOnError[List[InternalMsg]]())
} yield theList
}
}