本文整理汇总了Scala中reactivemongo.api.collections.bson.BSONCollection类的典型用法代码示例。如果您正苦于以下问题:Scala BSONCollection类的具体用法?Scala BSONCollection怎么用?Scala BSONCollection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了BSONCollection类的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: CounterDao
//设置package包名称以及导入依赖的类
package dao
import javax.inject.Inject
import play.api.libs.concurrent.Execution.Implicits._
import play.modules.reactivemongo.ReactiveMongoApi
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.bson._
import scala.concurrent.Future
class CounterDao @Inject()(reactiveMongoApi: ReactiveMongoApi) {
def countersFuture: Future[BSONCollection] = reactiveMongoApi.database.map(_.collection[BSONCollection]("counters"))
def nextId(collection: String): Future[Long] = {
val query = BSONDocument("collection" -> collection)
val update = BSONDocument("$inc" -> BSONDocument("counter" -> 1))
findAndModify(query, update)
}
def resetId(collection: String) : Future[Long] = {
val query = BSONDocument("collection" -> collection)
val update = BSONDocument("$set" -> BSONDocument("counter" -> 0))
findAndModify(query, update)
}
private def findAndModify(query: BSONDocument, update: BSONDocument): Future[Long] = {
val modify = countersFuture.map(_.BatchCommands.FindAndModifyCommand.Update(
update,
fetchNewObject = true,
upsert = true))
modify.flatMap(modify =>
countersFuture.flatMap(_.findAndModify(query, modify) map { res =>
res.result.get.get("counter") match {
case Some(BSONLong(id)) => id
case Some(BSONDouble(id)) => id.toLong
case Some(BSONInteger(id)) => id.toLong
case _ => 1L
}
})
)
}
}
示例2: MongoLogger
//设置package包名称以及导入依赖的类
package webmonitor
import reactivemongo.api.collections.bson.BSONCollection
import scala.concurrent.{ ExecutionContext, Future }
import reactivemongo.api._
import reactivemongo.bson.{
BSONDocumentWriter, Macros
}
class MongoLogger(conString: String, dbName: String, colName: String) extends MRecordLogger
{
private implicit def personWriter: BSONDocumentWriter[MRecord] = Macros.writer[MRecord]
private var database: Option[Future[DefaultDB]] = None
private def getConnection(): Future[MongoConnection] = {
val driver = MongoDriver()
val parsedUri = MongoConnection.parseURI(conString)
val connection = parsedUri.map(driver.connection(_))
Future.fromTry(connection)
}
private def getDatabase(connection: MongoConnection)(implicit context: ExecutionContext): Future[DefaultDB] = connection.database(dbName)
private def getCollection(db: DefaultDB): BSONCollection = db.collection(colName)
private def insertRecord(collection: BSONCollection, mRecord: MRecord)(implicit ec: ExecutionContext): Future[Unit] = {
collection.insert(mRecord).map(_ => {})
}
private def getDBLazy()(implicit executor: ExecutionContext): Future[DefaultDB] = synchronized {
if(database.isEmpty) {
database = Some(getConnection.flatMap(getDatabase))
}
database.get
}
def insert(record: MRecord)(implicit executor: ExecutionContext): Future[Unit] = {
getDBLazy().flatMap(db => insertRecord(getCollection(db), record))
}
}
示例3: Database
//设置package包名称以及导入依赖的类
package de.choffmeister.microserviceutils.mongodb
import akka.Done
import com.typesafe.config.ConfigFactory
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.api.{DefaultDB, MongoConnection, MongoDriver}
import scala.concurrent.{ExecutionContext, Future}
abstract class Database(val database: DefaultDB, collectionNamePrefix: String = "")(implicit ec: ExecutionContext) {
def collection(name: String): BSONCollection = database.collection[BSONCollection](collectionNamePrefix + name)
def init(): Future[Done]
def clear(): Future[Done]
}
object Database {
def open[DB <: Database](f: DefaultDB => DB)(implicit ec: ExecutionContext): Future[DB] = {
val config = ConfigFactory.load().getConfig("mongodb")
val uri = config.getString("uri")
val databaseName = config.getString("database-name")
val driver = MongoDriver()
val mongodbUri = MongoConnection.parseURI(uri)
val connection = Future.fromTry(mongodbUri.map(driver.connection))
connection
.flatMap(_.database(databaseName).map(f))
.flatMap(db => db.init().map(_ => db))
}
}
示例4: CachedAdapter
//设置package包名称以及导入依赖的类
package lila.db
package paginator
import dsl._
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.api._
import reactivemongo.bson._
import lila.common.paginator.AdapterLike
final class CachedAdapter[A](
adapter: AdapterLike[A],
val nbResults: Fu[Int]
) extends AdapterLike[A] {
def slice(offset: Int, length: Int): Fu[Seq[A]] =
adapter.slice(offset, length)
}
final class Adapter[A: BSONDocumentReader](
collection: BSONCollection,
selector: BSONDocument,
projection: BSONDocument,
sort: BSONDocument,
readPreference: ReadPreference = ReadPreference.primary
) extends AdapterLike[A] {
def nbResults: Fu[Int] = collection.count(Some(selector))
def slice(offset: Int, length: Int): Fu[Seq[A]] =
collection.find(selector, projection)
.sort(sort)
.skip(offset)
.cursor[A](readPreference = readPreference)
.gather[List](length)
}
示例5: save
//设置package包名称以及导入依赖的类
package io.github.bszwej.core.repository
import com.typesafe.scalalogging.LazyLogging
import io.github.bszwej.MainConfig
import io.github.bszwej.core.exception.{MongoException, MongoWriteException}
import io.github.bszwej.core.model.Tweet
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.api.commands.WriteResult
import reactivemongo.bson.BSONDocument
import scala.concurrent.{ExecutionContext, Future}
def save(tweet: Tweet): Future[RepositorySuccess.type]
}
case object RepositorySuccess
class MongoTweetRepository(collection: Future[BSONCollection])(implicit ec: ExecutionContext) extends TweetRepository with LazyLogging with MainConfig {
override def save(tweet: Tweet): Future[RepositorySuccess.type] = {
val document = BSONDocument(
"username" ? tweet.username,
"message" ? tweet.message,
"hashtag" ? tweet.hashtag
)
collection.flatMap(_.insert(document).map(_ ? RepositorySuccess)) recoverWith {
case WriteResult.Message(message) ?
logger.error(s"Error during storing a tweet: $message.")
Future.failed(new MongoWriteException(message))
case e: Exception ?
logger.error(s"Error during storing a tweet: ${e.getMessage}.")
Future.failed(new MongoException(e.getMessage))
}
}
}
示例6: save
//设置package包名称以及导入依赖的类
package repository
import model.WithId
import reactivemongo.api._
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.bson.{BSONDocument, BSONDocumentReader, BSONDocumentWriter}
import scala.concurrent.Future
trait MongoDao[T <: WithId] extends MongoConnection {
def save(collectionFuture: Future[BSONCollection], entity: T)(implicit reader: BSONDocumentWriter[T]): Future[T] =
collectionFuture.flatMap(_.update(queryById(entity.id), entity, upsert = true).map(_ => entity))
def deleteById(collectionFuture: Future[BSONCollection], id: String) = collectionFuture.flatMap(_.remove(queryById(id)))
def find(collectionFuture: Future[BSONCollection], query: BSONDocument)(implicit reader: BSONDocumentReader[T]): Future[Option[T]] = {
collectionFuture.flatMap(
_.find(query)
.cursor[T]()
.collect[List](-1, Cursor.FailOnError[List[T]]())
.map {
case x :: xs => Some(x)
case _ => None
})
}
def findList(collectionFuture: Future[BSONCollection], query: BSONDocument)(implicit reader: BSONDocumentReader[T]): Future[List[T]] = {
collectionFuture.flatMap(
_.find(query)
.cursor[T]()
.collect[List](-1, Cursor.FailOnError[List[T]]()))
}
def findList(collectionFuture: Future[BSONCollection], query: BSONDocument, projection: BSONDocument)(
implicit reader: BSONDocumentReader[T]): Future[List[T]] = {
collectionFuture.flatMap(
_.find(query)
.cursor[T]()
.collect[List](-1, Cursor.FailOnError[List[T]]()))
}
def queryById(id: String) = BSONDocument("_id" -> id)
}
示例7: ReceiptRepository
//设置package包名称以及导入依赖的类
package repository
import model.{FileEntity, ReceiptEntity}
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.bson.{BSONArray, BSONDocument, BSONString}
import scala.concurrent.Future
class ReceiptRepository extends MongoDao[ReceiptEntity] {
lazy val collectionFuture: Future[BSONCollection] = dbFuture.map(db => db[BSONCollection]("receipts"))
def save(receiptEntity: ReceiptEntity): Future[ReceiptEntity] = save(collectionFuture, receiptEntity)
def deleteById(id: String): Future[Unit] = deleteById(collectionFuture, id).map(_ => ())
def findForUserId(userId: String): Future[List[ReceiptEntity]] =
findList(collectionFuture, BSONDocument("userId" -> userId)).map(_.sortWith(_.timestamp > _.timestamp))
def findByIds(ids: Seq[String]): Future[List[ReceiptEntity]] =
findList(collectionFuture,
BSONDocument(
"_id" ->
BSONDocument("$in" -> BSONArray(ids.map(BSONString)))))
.map(_.sortWith(_.timestamp > _.timestamp))
def addFileToReceipt(receiptId: String, file: FileEntity): Future[Unit] =
collectionFuture
.flatMap(
_.update(
selector = BSONDocument("_id" -> receiptId),
update = BSONDocument(
"$push" -> BSONDocument("files" -> file),
"$set" -> BSONDocument("lastModified" -> System.currentTimeMillis())
)
))
.map(_ => ())
def findById(id: String): Future[Option[ReceiptEntity]] = find(collectionFuture, queryById(id))
}
示例8: OcrRepository
//设置package包名称以及导入依赖的类
package repository
import model.{OcrEntity, OcrTextOnly}
import reactivemongo.api.Cursor
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.api.commands.WriteResult
import reactivemongo.bson.{BSONDocument, BSONRegex}
import scala.concurrent.Future
class OcrRepository extends MongoDao[OcrEntity] {
lazy val collectionFuture: Future[BSONCollection] = dbFuture.map(db => db[BSONCollection]("ocr"))
def save(ocrEntity: OcrEntity): Future[OcrEntity] = save(collectionFuture, ocrEntity)
def deleteById(id: String): Future[WriteResult] = deleteById(collectionFuture, id)
def findById(id: String): Future[Option[OcrEntity]] = find(collectionFuture, queryById(id))
def findTextOnlyForUserId(userId: String, query: String): Future[List[OcrTextOnly]] =
collectionFuture.flatMap(
_.find(BSONDocument(
"userId" -> userId,
"result.text" -> BSONRegex(query, "i")
),
BSONDocument("result.text" -> 1))
.cursor[OcrTextOnly]()
.collect[List](-1, Cursor.FailOnError[List[OcrTextOnly]]()))
}
示例9: TrackingDao
//设置package包名称以及导入依赖的类
package com.fourstars.prodbox.repositories
import com.fourstars.prodbox.model.TrackingItem
import com.google.inject.{Inject, Singleton}
import com.typesafe.scalalogging.LazyLogging
import play.api.libs.concurrent.Execution.Implicits._
import play.api.mvc.Action
import play.modules.reactivemongo.json.ImplicitBSONHandlers._
import play.modules.reactivemongo.json._
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.bson.{BSONDocument, BSONObjectID}
import scala.concurrent.Future
@Singleton
class TrackingDao @Inject()(val reactiveMongoApi: ReactiveMongoApi) extends MongoController with ReactiveMongoComponents with LazyLogging with BsonFormatters {
def collection: BSONCollection = db.collection[BSONCollection]("persons")
def index = Action {
Ok("works")
}
def create(url: String): Future[TrackingItem] = {
val trackingItem = new TrackingItem(Some(BSONObjectID.generate), url)
val futureResult = collection.insert(trackingItem)
futureResult.map {
response =>
logger.debug(s"response is $response")
logger.debug(s"t is now $trackingItem")
trackingItem
}
}
def find(id: String): Future[Option[TrackingItem]] = {
collection.find((BSONDocument("_id" -> BSONObjectID(id)))).one[TrackingItem]
}
def count(): Future[Int] = {
collection.count()
}
}
示例10: CachedAdapter
//设置package包名称以及导入依赖的类
package lila.db
package paginator
import dsl._
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.api._
import reactivemongo.bson._
import lila.common.paginator.AdapterLike
final class CachedAdapter[A](
adapter: AdapterLike[A],
val nbResults: Fu[Int]
) extends AdapterLike[A] {
def slice(offset: Int, length: Int): Fu[Seq[A]] =
adapter.slice(offset, length)
}
final class Adapter[A: BSONDocumentReader](
collection: BSONCollection,
selector: BSONDocument,
projection: BSONDocument,
sort: BSONDocument,
readPreference: ReadPreference = ReadPreference.primary
) extends AdapterLike[A] {
def nbResults: Fu[Int] = collection.countSel(selector, readPreference)
def slice(offset: Int, length: Int): Fu[List[A]] =
collection.find(selector, projection)
.sort(sort)
.skip(offset)
.cursor[A](readPreference = readPreference)
.gather[List](length)
}
示例11: JobManager
//设置package包名称以及导入依赖的类
package com.mongo.db
import com.mongo.models._
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.bson.{BSONDocument, BSONObjectID}
import reactivemongo.api.QueryOpts
import reactivemongo.core.commands.Count
import reactivemongo.bson.{BSONDocument, BSONObjectID}
import reactivemongo.api.collections.bson.BSONCollection
import scala.concurrent.ExecutionContext
object JobManager {
import MongoDB._
val collection = db[BSONCollection]("jobs")
def saveJob(jobEntity: JobEntity)(implicit ec: ExecutionContext) =
collection.insert(jobEntity)//.map(_ => Created(jobEntity.id))
def save(jobEntity: JobEntity)(implicit ec: ExecutionContext) =
collection.insert(jobEntity).map(_ => Created(jobEntity.id))
def findById(id: String)(implicit ec: ExecutionContext) =
collection.find(queryById(id)).one[JobEntity]
def deleteById(id: String)(implicit ec: ExecutionContext) =
collection.remove(queryById(id)).map(_ => Deleted)
def find(implicit ec: ExecutionContext) =
collection.find(emptyQuery).cursor[BSONDocument].collect[List]()
private def queryById(id: String) = BSONDocument("_id" -> BSONObjectID(id))
private def emptyQuery = BSONDocument()
}
示例12: insert
//设置package包名称以及导入依赖的类
package org.cristal.repository.dao
import org.cristal.model.User
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.api.commands.WriteResult
import reactivemongo.bson.BSONDocument
import scala.concurrent.{ExecutionContext, Future}
import scala.util.{Failure, Success}
trait UserDAO {
def insert(user: User): Future[Unit]
}
class UserDAOImpl(implicit executor: ExecutionContext) extends UserDAO with UserCollection {
override def insert(user: User) = handleInsertResult(
usersCollection.flatMap(_.insert(userToDocument(user))))
private def handleInsertResult(result: Future[WriteResult]) = {
result.onComplete {
case failure @ Failure(e) => e.printStackTrace(); failure
case Success(_) => println(s"User successfully inserted.")
}
result.map(_ => ())
}
def usersCollection : Future[BSONCollection] = db.map(_.collection("users"))
def userToDocument(user: User) = BSONDocument(
"username" -> user.username,
"password" -> user.password,
"first_name" -> user.firstName,
"last_name" -> user.lastName,
"email" -> user.email
)
}
trait UserCollection extends DBConnection {
}