本文整理汇总了Scala中reactivemongo.bson.BSONDocument类的典型用法代码示例。如果您正苦于以下问题:Scala BSONDocument类的具体用法?Scala BSONDocument怎么用?Scala BSONDocument使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了BSONDocument类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: insertUser
//设置package包名称以及导入依赖的类
package services
import models.db.User
import models.rest.{UserId, UserRest}
import play.modules.reactivemongo.MongoController
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.bson.{BSONDocument, BSONObjectID}
import scala.concurrent.Future
trait RegistrationService {
def insertUser(userData: UserRest): Future[UserId]
def findUser(uuid: String): Future[Option[UserRest]]
}
trait MongoRegistrationService extends RegistrationService {
self: MongoController =>
import scala.concurrent.ExecutionContext.Implicits.global
def collection: BSONCollection = db.collection[BSONCollection]("users")
def insertUser(userData: UserRest): Future[UserId] = {
val insertRec = User(_id = BSONObjectID.generate, firstName = userData.firstName, lastName = userData.lastName)
collection.insert(insertRec).map { _ =>
UserId(insertRec._id.stringify)
}
}
def findUser(uuid: String): Future[Option[UserRest]] = {
BSONObjectID.parse(uuid).map { objId =>
val query = BSONDocument("_id" -> objId)
collection.find(query).one[User].map { result =>
result.map { user => UserRest(firstName = user.firstName, lastName = user.lastName) }
}
} getOrElse(Future.successful(None))
}
}
示例2: find
//设置package包名称以及导入依赖的类
package repos
import scala.concurrent.{ExecutionContext, Future}
import reactivemongo.bson.{BSONDocument, BSONObjectID}
import play.api.libs.json.{JsObject, Json}
import reactivemongo.api.commands.WriteResult
import play.modules.reactivemongo.ReactiveMongoApi
import javax.inject._
import play.modules.reactivemongo.json._
import play.modules.reactivemongo.json.collection.JSONCollection
import reactivemongo.api.ReadPreference
trait PostRepo {
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]
}
class PostRepoImpl @Inject() (reactiveMongoApi: ReactiveMongoApi) extends PostRepo {
def collection = reactiveMongoApi.db.collection[JSONCollection]("posts");
override def find() (implicit ec: ExecutionContext): Future[List[JsObject]] = {
val genericQueryBuilder = collection.find(Json.obj());
val cursor = genericQueryBuilder.cursor[JsObject](ReadPreference.Primary);
cursor.collect[List]()
}
def select(selector: BSONDocument)(implicit ec: ExecutionContext): Future[Option[JsObject]] = {
collection.find(selector).one[JsObject]
}
def update(selector: BSONDocument, update: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.update(selector,update)
}
def remove(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.remove(document)
}
def save(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.update(BSONDocument("_id" -> document.get("_id").getOrElse(BSONObjectID.generate)), document, upsert = true)
}
}
示例3: Customer
//设置package包名称以及导入依赖的类
package model
import reactivemongo.api.MongoDriver
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.bson.BSONDocument
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Await
case class Customer(username:String,password:String,name:String,email:String,mobile:String)
case class Login(username:String,password:String)
class CustomerService {
val driver = new MongoDriver
val connection = driver.connection(List("localhost"))
val database = Await.result(connection.database("sonu"),10.seconds)
val collection= database.collection[BSONCollection]("customer")
def insert(username:String,password:String,name:String,email:String,mobile:String):String ={
try {
val document = BSONDocument("username" -> username, "password" -> password, "name" -> name,
"email" -> email, "mobile" -> mobile)
Await.result(collection.insert(document), 10.seconds)
"Inserted"
}
catch {
case error:Exception => "Duplicate"
}
}
def find(username:String,password:String):Boolean={
try {
val document = BSONDocument("username" -> username,"password" -> password)
val result = Await.result(collection.find(document).one[BSONDocument], 10.seconds)
if(result.isDefined) true else false
}
catch {
case error:Exception => false
}
}
}
object CustomerService extends CustomerService
示例4: Application
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.{Inject, Singleton}
import play.api.Logger
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json.Json
import play.api.mvc.{Action, Controller}
import play.modules.reactivemongo.json.collection.JSONCollection
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.api.commands.bson.BSONCountCommand.{Count, CountResult}
import reactivemongo.api.commands.bson.BSONCountCommandImplicits._
import reactivemongo.bson.BSONDocument
import scala.concurrent.Future
@Singleton
class Application @Inject()(val reactiveMongoApi: ReactiveMongoApi) extends Controller
with MongoController with ReactiveMongoComponents {
def index = Action {
Logger.info("Application startup...")
val posts = List(
Json.obj(
"name" -> "Widget One",
"description" -> "My first widget",
"author" -> "Justin"
),
Json.obj(
"name" -> "Widget Two: The Return",
"description" -> "My second widget",
"author" -> "Justin"
))
val query = BSONDocument("name" -> BSONDocument("$exists" -> true))
val command = Count(query)
val result: Future[CountResult] = bsonCollection.runCommand(command)
result.map { res =>
val numberOfDocs: Int = res.value
if (numberOfDocs < 1) {
jsonCollection.bulkInsert(posts.toStream, ordered = true).foreach(i => Logger.info("Record added."))
}
}
Ok("Your database is ready.")
}
def jsonCollection = reactiveMongoApi.db.collection[JSONCollection]("widgets")
def bsonCollection = reactiveMongoApi.db.collection[BSONCollection]("widgets")
def cleanup = Action {
jsonCollection.drop().onComplete {
case _ => Logger.info("Database collection dropped")
}
Ok("Your database is clean.")
}
}
示例5: 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)
}
}
示例6: StringMapFormatter
//设置package包名称以及导入依赖的类
package com.evojam.documents
import collection.JavaConversions._
import org.bson.Document
import reactivemongo.bson.{BSONString, BSONDocument, BSONDocumentReader, BSONDocumentWriter}
import com.evojam.driver.DocumentFormat
object StringMapFormatter {
implicit object Handler extends BSONDocumentReader[Map[String, String]] with BSONDocumentWriter[Map[String, String]] {
override def read(bson: BSONDocument): Map[String, String] =
bson.elements.map({case (key, value) => (key, value.asInstanceOf[BSONString].as[String])}).toMap
override def write(t: Map[String, String]): BSONDocument =
BSONDocument(t.toStream.map({case (k,v) => (k, BSONString(v))}))
}
implicit object javaFmt extends DocumentFormat[Map[String, String]] {
override def writes(a: Map[String, String]) = {
val doc = new Document()
a foreach {
case (k, v) => doc.append(k, v)
}
doc
}
override def reads(doc: Document): Map[String, String] =
doc.keySet().map(key => (key, doc.getString(key))).toMap
}
}
示例7: NestedDoc
//设置package包名称以及导入依赖的类
package com.evojam.documents
import org.bson.Document
import reactivemongo.bson.{BSONDocument, BSONDocumentReader, BSONDocumentWriter}
import com.evojam.driver.DocumentFormat
case class NestedDoc(name: String, _id: String, left: Option[NestedDoc], right: Option[NestedDoc])
object NestedDoc {
implicit object NestedDocHandler extends BSONDocumentReader[NestedDoc] with BSONDocumentWriter[NestedDoc]{
override def read(bson: BSONDocument): NestedDoc = {
val left = bson.get("left").map(t => read(t.asInstanceOf[BSONDocument]))
val right = bson.get("right").map(t => read(t.asInstanceOf[BSONDocument]))
NestedDoc(bson.getAs[String]("name").get, bson.getAs[String]("_id").get, left, right)
}
override def write(t: NestedDoc): BSONDocument = {
BSONDocument("_id" -> t._id, "name" -> t.name)
.add("left" -> t.left.map(write))
.add("right" -> t.right.map(write))
}
}
implicit val javaFormat = new DocumentFormat[NestedDoc] {
override def writes(a: NestedDoc): Document = {
val doc = new Document("name", a.name)
a.left.foreach(t => doc.append("left", writes(t)))
a.right.foreach(t => doc.append("right", writes(t)))
doc.append("_id", a._id)
}
override def reads(doc: Document): NestedDoc = {
val left = Option(doc.get[Document]("left", classOf[Document])).map(reads)
val right = Option(doc.get[Document]("right", classOf[Document])).map(reads)
NestedDoc(doc.getString("name"), doc.getString("_id"), left, right)
}
}
}
示例8: addBook
//设置package包名称以及导入依赖的类
package com.jjabuk.bookstore.catalog
import com.jjabuk.bookstore.catalog.protocols.CatalogueProtocol.{Book, BookAdded}
import com.jjabuk.bookstore.persistence.MongoDb
import org.slf4j.{Logger, LoggerFactory}
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.bson.{BSONDocument, BSONDocumentWriter, BSONObjectID}
import reactivemongo.core.errors.DatabaseException
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
trait BookCommands {
def addBook(book: Book): Future[BookAdded]
}
object MongoBookCommands extends BookCommands with MongoDb {
def logger: Logger = LoggerFactory.getLogger(this.getClass)
def books: Future[BSONCollection] = database map (_.collection("books"))
implicit def bookWriter = new BSONDocumentWriter[Book] {
def write(book: Book): BSONDocument =
BSONDocument(
"_id" -> BSONObjectID.parse(book.uuid).getOrElse(BSONObjectID.generate),
"isbn" -> book.isbn,
"title" -> book.title,
"review" -> book.review.orNull,
"publisher" -> book.publisher.orNull
)
}
def addBook(book: Book): Future[BookAdded] = {
logger.debug(s"Adding a book $book")
books
.flatMap(_
.insert(book)
.map(doc => {
BookAdded(book.uuid)
}))
.recover({
case de: DatabaseException =>
logger.warn("DatabaseException: " + de.getMessage())
logger.warn("Cause: " + de.getCause())
logger.warn("Code: " + de.code)
BookAdded(book.uuid)
})
}
}
示例9: findAll
//设置package包名称以及导入依赖的类
package com.jjabuk.bookstore.catalog
import com.jjabuk.bookstore.catalog.protocols.CatalogueProtocol.{Book, BooksFound}
import com.jjabuk.bookstore.persistence.MongoDb
import org.slf4j.LoggerFactory
import reactivemongo.api.ReadPreference
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.bson.{BSONDocument, BSONDocumentReader, BSONObjectID}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{ExecutionContext, Future}
trait BookQueries {
def findAll(implicit ec: ExecutionContext): Future[BooksFound]
def findByUuid(uuid: String)(implicit ec: ExecutionContext): Future[Option[BooksFound]]
}
object MongoBookQueries extends BookQueries with MongoDb {
def logger = LoggerFactory.getLogger(this.getClass)
def books: Future[BSONCollection] = database map (_.collection("books"))
implicit def bookReader = new BSONDocumentReader[Book] {
def read(doc: BSONDocument): Book =
Book(
uuid = doc.getAs[BSONObjectID]("_id").get.stringify,
isbn = doc.getAs[String]("isbn").get,
title = doc.getAs[String]("title").get,
review = doc.getAs[String]("review"),
publisher = doc.getAs[String]("publisher")
)
}
def findAll(implicit ec: ExecutionContext): Future[BooksFound] = {
logger.debug(s"Find all books")
books flatMap {
_.find(BSONDocument()).cursor[Book](ReadPreference.Primary).collect[List]()
} map (books => BooksFound(books))
}
def findByUuid(uuid: String)(implicit ec: ExecutionContext): Future[Option[BooksFound]] = {
logger.debug(s"Find a book by uuid=$uuid")
val selector = BSONDocument("_id" -> BSONObjectID.parse(uuid).get)
books
.flatMap(_.find(selector).one[Book])
.map {
case Some(book) => Some(BooksFound(List(book)))
case _ => Option.empty[BooksFound]
}
}
}
示例10: findOneOrCreate
//设置package包名称以及导入依赖的类
package com.aluxian.susucatbot
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.bson.{BSONDocument, BSONDocumentReader, BSONDocumentWriter, Macros}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{Future, Promise}
import scala.util.{Failure, Success, Try}
package object mongo {
def findOneOrCreate(collection: BSONCollection)
(userQuery: BSONDocument, getNewDoc: => Future[MongoUser]): Future[MongoUser] = {
implicit def mongoEntityWriter: BSONDocumentWriter[MongoEntity] = Macros.writer[MongoEntity]
implicit def mongoThoughtWriter: BSONDocumentWriter[MongoThought] = Macros.writer[MongoThought]
implicit def mongoMessageWriter: BSONDocumentWriter[MongoMessage] = Macros.writer[MongoMessage]
implicit def mongoUserWriter: BSONDocumentWriter[MongoUser] = Macros.writer[MongoUser]
implicit def mongoEntityReader: BSONDocumentReader[MongoEntity] = Macros.reader[MongoEntity]
implicit def mongoThoughtReader: BSONDocumentReader[MongoThought] = Macros.reader[MongoThought]
implicit def mongoMessageReader: BSONDocumentReader[MongoMessage] = Macros.reader[MongoMessage]
implicit def mongoUserReader: BSONDocumentReader[MongoUser] = Macros.reader[MongoUser]
val p = Promise[MongoUser]()
collection.find(userQuery).one[MongoUser].onComplete {
case Success(docOpt) =>
if (docOpt.isDefined) {
p.complete(Try(docOpt.get))
} else {
getNewDoc.onComplete {
case Success(newDocOpt) =>
collection.insert(newDocOpt).onComplete { r =>
collection.find(userQuery).one[MongoUser]
.onComplete {
case Success(docOpt2) =>
val mongoUser = docOpt2.get
p.complete(Try(mongoUser))
case Failure(ex) => p.failure(ex)
}
}
case Failure(ex) => p.failure(ex)
}
}
case Failure(ex) => p.failure(ex)
}
p.future
}
}
示例11: Order
//设置package包名称以及导入依赖的类
package models
import reactivemongo.bson.{BSONDocument, BSONDocumentReader}
case class Order(orderID: Int, accountId: String, date: String, time: String, orderStatus: String, paymentMethod: String, orderLines: Array[OrderLine], totalPrice: Double, rating: Int) {}
object Order {
implicit object OrderReader extends BSONDocumentReader[Order] {
def read(doc: BSONDocument): Order =
Order(
doc.getAs[Int]("orderID").get,
doc.getAs[String]("accountID").get,
doc.getAs[String]("date").get,
doc.getAs[String]("time").get,
doc.getAs[String]("orderStatus").get,
doc.getAs[String]("paymentMethod").get,
doc.getAs[Array[OrderLine]]("orderLines").get,
doc.getAs[Double]("totalPrice").get,
doc.getAs[Int]("rating").get
)
}
}
示例12: Product
//设置package包名称以及导入依赖的类
package models
import reactivemongo.bson.{BSONDocument, BSONDocumentReader}
case class Product(itemID: String, product: String, images: Array[String], category: Array[String], description: String, var stock: Int, price: Double) {
def hasXAvailable(x: Int): Boolean = {
this.stock >= x
}
// URL: String
def decrementStock(quantity: Int): Unit = {
//Add stock validation here?
stock = stock - quantity
}
def incrementStock(quantity: Int): Unit = {
//Add stock validation here?
stock += quantity
}
}
object Product {
implicit object productReader extends BSONDocumentReader[Product] {
def read(doc: BSONDocument): Product =
Product(
doc.getAs[String]("itemID").get,
doc.getAs[String]("Product").get,
doc.getAs[Array[String]]("images").get,
doc.getAs[Array[String]]("Category").get,
doc.getAs[String]("Description").get,
doc.getAs[Int]("Stock").get,
doc.getAs[Double]("price").get
)
}
}
示例13: JumanppAdmin
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import code.{AnalysisResult, MongoWorker}
import org.joda.time.format.DateTimeFormat
import play.api.mvc.{Action, Controller}
import reactivemongo.bson.BSONDocument
import ws.kotonoha.akane.utils.XInt
import scala.concurrent.ExecutionContext
class JumanppAdmin @Inject() (
mw: MongoWorker
)(implicit ec: ExecutionContext) extends Controller {
def stats() = Action { Ok(views.html.jppadmin()) }
def queries() = Action.async { req =>
val from = req.getQueryString("from").flatMap(XInt.unapply).getOrElse(0)
val fixed = req.getQueryString("fixed").contains("true")
val sorting = req.getQueryString("sorting").collect({
case "date" => BSONDocument("timestamp" -> 1)
case "date-" => BSONDocument("timestamp" -> -1)
}).getOrElse(BSONDocument("timestamp" -> 1))
mw.get(from, 100, fixed, sorting).map { items =>
val dateFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm")
val data = items.map { a =>
AnalysisResult(
a._id.stringify,
dateFormatter.print(a.timestamp),
a.input,
JumanppConversion.convertLatttice(a._id, a.analysis),
a.version,
a.dicVersion,
a.reported.map(_.nodes)
)
}
val string = upickle.default.write(data)
Ok(string)
}
}
}
示例14: IndexModel
//设置package包名称以及导入依赖的类
package it.agilelab.bigdata.wasp.core.models
import it.agilelab.bigdata.wasp.core.utils.ConfigManager
import reactivemongo.bson.{BSONDocument, BSONObjectID, BSONString}
object IndexModel {
val readerType = "index"
val schema_base_elastic =
"""
"id_event":{"type":"double","index":"not_analyzed","store":"true","enabled":"true"},
"source_name":{"type":"string","index":"not_analyzed","store":"true","enabled":"true"},
"Index_name":{"type":"string","index":"not_analyzed","store":"true","enabled":"true"},
"metric_name":{"type":"string","index":"not_analyzed","store":"true","enabled":"true"},
"timestamp":{"type":"date","format":"date_time","index":"not_analyzed","store":"true","enabled":"true"},
"latitude":{"type":"double","index":"not_analyzed","store":"true","enabled":"true"},
"longitude":{"type":"double","index":"not_analyzed","store":"true","enabled":"true"},
"value":{"type":"double","index":"not_analyzed","store":"true","enabled":"true"},
"payload":{"type":"string","index":"not_analyzed","store":"true","enabled":"true"}
"""
val schema_base_solr = """
{ "name":"id_event", "type":"tdouble", "stored":true },
{ "name":"source_name", "type":"string", "stored":true },
{ "name":"topic_name", "type":"string","stored":true },
{ "name":"metric_name", "type":"string","stored":true },
{ "name":"timestamp", "type":"string","stored":true },
{ "name":"latitude", "type":"tdouble", "stored":true },
{ "name":"longitude", "type":"tdouble", "stored":true },
{ "name":"value", "type":"string", "stored":true },
{ "name":"payload", "type":"string", "stored":true }
"""
def normalizeName(basename: String) = s"${basename.toLowerCase}_index"
}
case class IndexModel(override val name: String,
creationTime: Long,
schema: Option[BSONDocument],
_id: Option[BSONObjectID] = None,
query: Option[String] = None,
numShards: Option[Int] = Some(1),
replicationFactor: Option[Int] = Some(1))
extends Model {
def resource = s"${ConfigManager.buildTimedName(name)}/$dataType"
def collection = s"${ConfigManager.buildTimedName(name)}"
def dataType =
schema
.map(
bson =>
bson.elements.headOption
.getOrElse(("undefined", BSONString("undefined")))
._1)
.getOrElse("undefined")
}
示例15: TopicModel
//设置package包名称以及导入依赖的类
package it.agilelab.bigdata.wasp.core.models
import reactivemongo.bson.{BSONDocument, BSONObjectID}
object TopicModel {
val readerType = "topic"
val schema_base = """
{"name":"id_event","type":"double"},
{"name":"source_name","type":"string"},
{"name":"topic_name","type":"string"},
{"name":"metric_name","type":"string"},
{"name":"timestamp","type":"string","java-class" : "java.util.Date"},
{"name":"latitude","type":"double"},
{"name":"longitude","type":"double"},
{"name":"value","type":"double"},
{"name":"payload","type":"string"}
"""
def name(basename: String) = s"${basename.toLowerCase}.topic"
}
case class TopicModel(override val name: String,
creationTime: Long,
partitions: Int,
replicas: Int,
topicDataType: String, // avro, json, xml
schema: Option[BSONDocument],
_id: Option[BSONObjectID] = None) extends Model