• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala BSONDocument类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中reactivemongo.bson.BSONDocument的典型用法代码示例。如果您正苦于以下问题:Scala BSONDocument类的具体用法?Scala BSONDocument怎么用?Scala BSONDocument使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了BSONDocument类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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))
  }
} 
开发者ID:monkeygroover,项目名称:basic-play-project,代码行数:43,代码来源:RegistrationService.scala


示例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)
  }
  
} 
开发者ID:Rheriel,项目名称:LightHouse,代码行数:52,代码来源:PostRepo.scala


示例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 
开发者ID:sonumehrotra,项目名称:MongoAssignment,代码行数:48,代码来源:Customer.scala


示例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.")
  }
} 
开发者ID:aphexcx,项目名称:iconoclast-api,代码行数:62,代码来源:Application.scala


示例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)
  }
} 
开发者ID:aphexcx,项目名称:iconoclast-api,代码行数:54,代码来源:Repo.scala


示例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
  }

} 
开发者ID:evojam,项目名称:mongo-drivers-benchmarks,代码行数:32,代码来源:StringMapFormatter.scala


示例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)
    }
  }

} 
开发者ID:evojam,项目名称:mongo-drivers-benchmarks,代码行数:40,代码来源:NestedDoc.scala


示例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)
      })
  }
} 
开发者ID:jjabuk,项目名称:bookstore,代码行数:52,代码来源:MongoBookCommands.scala


示例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]
      }
  }

} 
开发者ID:jjabuk,项目名称:bookstore,代码行数:59,代码来源:MongoBookQueries.scala


示例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
  }
} 
开发者ID:aluxian,项目名称:SusuCatBot,代码行数:50,代码来源:package.scala


示例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
      )
  }
} 
开发者ID:Smudgey,项目名称:qa_play_ims,代码行数:25,代码来源:Order.scala


示例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
      )
  }

} 
开发者ID:Smudgey,项目名称:qa_play_ims,代码行数:43,代码来源:Product.scala


示例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)
    }
  }
} 
开发者ID:eiennohito,项目名称:nlp-tools-demo,代码行数:46,代码来源:JumanppAdmin.scala


示例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")

} 
开发者ID:agile-lab-dev,项目名称:wasp,代码行数:60,代码来源:IndexModel.scala


示例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 
开发者ID:agile-lab-dev,项目名称:wasp,代码行数:30,代码来源:TopicModel.scala


示例16: delete

//设置package包名称以及导入依赖的类
package de.choffmeister.microserviceutils.mongodb

import akka.Done
import de.choffmeister.microserviceutils.mongodb.Repository._
import reactivemongo.bson.BSONDocument

import scala.concurrent.Future

trait RepositoryWithSoftDelete[I, T <: Entity[I], P] extends Repository[I, T, P] {
  override def delete(principal: P, id: I): Future[Done] = {
    collection
      .update(filterView(principal, BSONDocument("_id" -> id)), BSONDocument("$set" -> BSONDocument("deleted" -> true)))
      .map {
        case res if res.n == 1 => Done
        case _ => throw NotFoundException("Unknown entity id")
      }
  }

  override def filterView(principal: P, selector: BSONDocument): BSONDocument =
    super.filterView(principal, selector) ++ BSONDocument("deleted" -> false)
} 
开发者ID:choffmeister,项目名称:microservice-utils,代码行数:22,代码来源:RepositoryWithSoftDelete.scala


示例17: GalleryCommentEntity

//设置package包名称以及导入依赖的类
package com.rozilo.ussemble.models.db

import java.util.{Calendar, Date}

import com.rozilo.ussemble.models.api.GalleryCommentProtocol.GalleryComment
import io.circe.generic.JsonCodec
import reactivemongo.bson.{BSONDocument, BSONDocumentReader, BSONDocumentWriter, BSONObjectID, BSONString}
import io.circe._
import io.circe.generic.semiauto._


case class GalleryCommentEntity(id: BSONObjectID = BSONObjectID.generate,
                                body: String,
                                activity_id: BSONObjectID,
                                sender_id: BSONObjectID,
                                var read_by: Option[List[String]] = Some(List()),
                                createdAt: Option[Date] = Some(Calendar.getInstance.getTime),
                                updatedAt: Option[Date] = Some(Calendar.getInstance.getTime))


object GalleryCommentEntity {

  implicit def toGalleryCommentEntity(comment: GalleryComment): GalleryCommentEntity = GalleryCommentEntity(body = comment.body,
    activity_id = BSONObjectID.parse(comment.activity_id).get, sender_id = BSONObjectID.parse(comment.sender_id).get)

  import io.circe._
  import io.circe.syntax._
  import io.circe.generic.auto._


//  implicit val jsonEncoder = Encoder[GalleryCommentEntity]
//  implicit val jsonDecoder = Decoder[GalleryCommentEntity]

  implicit object GalleryCommentBSONReader extends BSONDocumentReader[GalleryCommentEntity] {

    def read(doc: BSONDocument): GalleryCommentEntity =
      GalleryCommentEntity(
        id = doc.getAs[BSONObjectID]("_id").get,
        body = doc.getAs[String]("body").get,
        activity_id = doc.getAs[BSONObjectID]("activity_id").get,
        sender_id = doc.getAs[BSONObjectID]("sender_id").get,
        read_by = doc.getAs[List[String]]("read_by")
      )
  }

  implicit object GalleryCommentBSONWriter extends BSONDocumentWriter[GalleryCommentEntity] {
    def write(commentEntity: GalleryCommentEntity): BSONDocument =
      BSONDocument(
        "_id" -> commentEntity.id,
        "body" -> BSONString(commentEntity.body),
        "activity_id" -> commentEntity.activity_id,
        "sender_id" -> commentEntity.sender_id,
        "read_by" -> commentEntity.read_by,
        "created_at" -> commentEntity.createdAt,
        "updated_at" -> commentEntity.updatedAt
      )
  }
} 
开发者ID:Rozilo,项目名称:uss-gallery,代码行数:59,代码来源:GalleryCommentEntity.scala


示例18: UserController

//设置package包名称以及导入依赖的类
package controllers.rest

import javax.inject.Inject

import Repositories.UserRepository
import models.User
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json.Json
import play.api.mvc._
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import reactivemongo.bson.{BSONDocument, BSONObjectID}
import utils.Pagination

import scala.concurrent.Await
import scala.concurrent.duration._



class UserController @Inject()(val userService: UserRepository, val reactiveMongoApi: ReactiveMongoApi) extends Controller
  with MongoController with ReactiveMongoComponents {

  def getAllUsers(page:Int, limit:Int, sort: String) = Action.async {implicit request =>

    val totalCount = Await.result(userService.count(), Duration.Inf)
    val pagination = new Pagination(page, limit, totalCount)
    userService.getAllUsers(pagination, sort).map(users => Ok(Json.obj("DATA" -> Json.toJson(users), "PAGINATION" -> Json.toJson(pagination))))
  }

  def getUserId(id: String) = Action.async { implicit request =>
    userService.getUserId(BSONDocument("_id" -> BSONObjectID(id))).map(user => Ok(Json.prettyPrint(Json.toJson(user))))
  }

  def insertUser = Action.async(BodyParsers.parse.json) { implicit request =>
    val userObj = (request.body).as[User]
    userService.insertUser(userObj).map(result => Created)
  }

  def updateUser(id: String) = Action.async(BodyParsers.parse.json) { implicit request =>
    val userObj = (request.body).as[User]
    userService.updateUser(BSONDocument("_id" -> BSONObjectID(id)), userObj).map(result => Accepted)
  }

  def deleteUser(id: String) = Action.async(BodyParsers.parse.json) { implicit request =>
    userService.deleteUser(BSONDocument("_id" -> BSONObjectID(id))).map(result => Accepted)
  }
} 
开发者ID:sopheakreth,项目名称:rest-api-play-scala-mongodb,代码行数:47,代码来源:UserController.scala


示例19: BsonFormats

//设置package包名称以及导入依赖的类
package repository

import javax.inject.Inject

import com.sharecare.lib.play.repository.MongoConfiguration
import model.API_DTO
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.api.commands.WriteResult
import reactivemongo.bson.{BSONDocument, Macros}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future


object BsonFormats {
  implicit val arh = Macros.handler[API_DTO]
}; import repository.BsonFormats._


trait ApiRepositoryI {
  def getAPIs(): Future[List[API_DTO]]
  def addAPI(api: API_DTO): Future[WriteResult]
  def deleteAPI(api: API_DTO): Future[WriteResult]
}


class ApiRepository @Inject() (mongoConfig: MongoConfiguration) extends ApiRepositoryI {
  lazy val docs               = mongoConfig.getMongoDataStore("collections.apis")
  lazy val c: BSONCollection  = docs.collection; import c._
  def getAPIs()               = find(BSONDocument()).cursor[API_DTO]().collect[List]()
  def addAPI(api: API_DTO)    = insert(api)
  def deleteAPI(api: API_DTO) = remove(api)
} 
开发者ID:Sharecare,项目名称:health-profile-phr-common-service-api,代码行数:34,代码来源:Repository.scala


示例20: StcEventMongoRepositorySpec

//设置package包名称以及导入依赖的类
package repositories.stc

import model.persisted.StcEvent
import org.joda.time.{ DateTime, DateTimeZone }
import reactivemongo.bson.BSONDocument
import reactivemongo.json.ImplicitBSONHandlers
import repositories.CollectionNames
import testkit.MongoRepositorySpec

import scala.concurrent.Future

class StcEventMongoRepositorySpec extends MongoRepositorySpec {
  import ImplicitBSONHandlers._

  override val collectionName = CollectionNames.EVENT

  lazy val repository = new StcEventMongoRepository()

  "Stop the Clock Event repository" should {
    "insert new event" in {
      val event = StcEvent("ExampleEvent", DateTime.now(DateTimeZone.UTC), Some("appId"), Some("userId"))
      repository.create(event).futureValue
      val result = getEvent(repository.collection.find(BSONDocument.empty).one[BSONDocument])

      result mustBe event
    }
  }

  private def getEvent(doc: Future[Option[BSONDocument]]): StcEvent =
    doc.map(_.map(StcEvent.eventHandler.read)).futureValue.get
} 
开发者ID:hmrc,项目名称:fset-faststream,代码行数:32,代码来源:StcEventMongoRepositorySpec.scala



注:本文中的reactivemongo.bson.BSONDocument类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala Answer类代码示例发布时间:2022-05-23
下一篇:
Scala JsArray类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap