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

Scala MongoDatabase类代码示例

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

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



在下文中一共展示了MongoDatabase类的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: DatabaseActor

//设置package包名称以及导入依赖的类
package com.edu.chat.database

import akka.actor.{Actor, ActorLogging}
import com.edu.chat.Settings
import com.mongodb.ServerAddress
import org.mongodb.scala.bson.collection.immutable.Document
import org.mongodb.scala.connection.ClusterSettings
import org.mongodb.scala.{MongoClient, MongoClientSettings, MongoCollection, MongoCredential, MongoDatabase}

import scala.collection.JavaConverters._

abstract class DatabaseActor extends Actor with ActorLogging {
  private val applicationSettings = Settings(context.system)

  protected val collectionName: String

  protected def loadCollection: MongoCollection[Document] = {
    val clusterSettings = ClusterSettings
      .builder()
      .hosts(List(new ServerAddress(applicationSettings.dbHost, applicationSettings.dbPort)).asJava)
      .build()

    val credentials = List(MongoCredential.createCredential(
      applicationSettings.dbUsername,
      applicationSettings.dbName,
      applicationSettings.dbPassword)).asJava

    val dbSettings = MongoClientSettings
      .builder()
      .clusterSettings(clusterSettings)
      .credentialList(credentials)
      .build()

    val mongoDbClient = MongoClient(dbSettings)

    val database: MongoDatabase = mongoDbClient.getDatabase(applicationSettings.dbName)
    database.getCollection(collectionName)
  }
} 
开发者ID:themirrortruth,项目名称:chat-akka,代码行数:40,代码来源:DatabaseActor.scala


示例2: Example3

//设置package包名称以及导入依赖的类
package com.stulsoft.pmongodb.example01

import com.stulsoft.pmongodb.example01.Helpers._
import com.typesafe.scalalogging.LazyLogging
import org.bson.codecs.configuration.CodecRegistries.{fromProviders, fromRegistries}
import org.mongodb.scala.bson.ObjectId
import org.mongodb.scala.bson.codecs.DEFAULT_CODEC_REGISTRY
import org.mongodb.scala.bson.codecs.Macros._
import org.mongodb.scala.model.Filters._
import org.mongodb.scala.{MongoClient, MongoCollection, MongoDatabase}


object Example3 extends App with LazyLogging {

  private lazy val codecRegistry = fromRegistries(fromProviders(classOf[Person]), DEFAULT_CODEC_REGISTRY)

  // To directly connect to the default server localhost on port 27017
  val client: MongoClient = MongoClient()
  val database: MongoDatabase = client.getDatabase("testDb").withCodecRegistry(codecRegistry)
  val collection: MongoCollection[Person] = database.getCollection("testCollection3")
  collection.drop().results()

  val person: Person = Person("Ada", "Lovelace")
  collection.insertOne(person).results()

  collection.find().first().printHeadResult()
  collection.find().printResults()
  collection.find(equal("firstName", "Ada")).first().printHeadResult()
  collection.find(equal("lastName", "Lovelace")).first().printHeadResult()

  case class Person(_id: ObjectId, firstName: String, lastName: String)

  object Person {
    def apply(firstName: String, lastName: String): Person =
      Person(new ObjectId(), firstName, lastName)
  }

} 
开发者ID:ysden123,项目名称:poc,代码行数:39,代码来源:Example3.scala


示例3: Cloud1

//设置package包名称以及导入依赖的类
package com.stulsoft.pmongodb.example01

import com.stulsoft.pmongodb.example01.Helpers._
import com.typesafe.scalalogging.LazyLogging
import org.bson.codecs.configuration.CodecRegistries.{fromProviders, fromRegistries}
import org.mongodb.scala.bson.ObjectId
import org.mongodb.scala.bson.codecs.DEFAULT_CODEC_REGISTRY
import org.mongodb.scala.bson.codecs.Macros._
import org.mongodb.scala.model.Filters._
import org.mongodb.scala.{MongoClient, MongoCollection, MongoDatabase}

import com.mongodb.MongoCredential
import org.mongodb.scala.bson.collection.mutable.Document
import org.mongodb.scala.{Completed, FindObservable, MongoClient, MongoClientSettings, MongoCollection, MongoDatabase, Observable,Observer, ReadPreference, ServerAddress}
import org.mongodb.scala.connection.ClusterSettings
import com.mongodb.MongoCredential._
import java.util.logging.{Level, Logger}
import org.mongodb.scala.connection.{NettyStreamFactoryFactory,SslSettings}
import scala.collection.JavaConverters._



object Cloud1 extends App with LazyLogging {

  private lazy val codecRegistry = fromRegistries(fromProviders(classOf[Person]), DEFAULT_CODEC_REGISTRY)


  val clusterSettings: ClusterSettings = ClusterSettings.builder().hosts(List(new ServerAddress("cluster0-shard-00-00-k8h55.mongodb.net:27017"),
    new ServerAddress("cluster0-shard-00-01-k8h55.mongodb.net:27017"),
    new ServerAddress("cluster0-shard-00-02-k8h55.mongodb.net:27017")
  ).asJava).build()
  val user: String = "<USER NAME>>"
  val databasename: String = "testDb"
  val password: Array[Char] = "<PASSWORD>".toCharArray
  val credential: MongoCredential = createCredential(user, databasename, password)
  val settings: MongoClientSettings = MongoClientSettings.builder()
    .clusterSettings(clusterSettings).credentialList(List(credential,credential).asJava).sslSettings(SslSettings.builder().enabled(true).build())
    .streamFactoryFactory(NettyStreamFactoryFactory()).build()
  val client: MongoClient = MongoClient(settings)

  val database: MongoDatabase = client.getDatabase("testDb").withCodecRegistry(codecRegistry)
  val collection: MongoCollection[Person] = database.getCollection("testCollection3")
  collection.drop().results()

  val person: Person = Person("Ada", "Lovelace")
  collection.insertOne(person).results()

  collection.find().first().printHeadResult()
  collection.find().printResults()
  collection.find(equal("firstName", "Ada")).first().printHeadResult()
  collection.find(equal("lastName", "Lovelace")).first().printHeadResult()

  case class Person(_id: ObjectId, firstName: String, lastName: String)

  object Person {
    def apply(firstName: String, lastName: String): Person =
      Person(new ObjectId(), firstName, lastName)
  }

} 
开发者ID:ysden123,项目名称:poc,代码行数:61,代码来源:Cloud1.scala


示例4: MongoService

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

import java.util.concurrent.TimeUnit.SECONDS

import org.bson.json.JsonMode
import org.bson.json.JsonWriterSettings
import org.mongodb.scala.MongoClient
import org.mongodb.scala.MongoCollection
import org.mongodb.scala.MongoDatabase
import org.mongodb.scala.bson.collection.immutable.Document

import scala.concurrent.Await
import scala.concurrent.Future
import scala.concurrent.duration.Duration
import scala.language.postfixOps
import scala.util.Failure
import scala.util.Success
import scala.util.Try

class MongoService(mongoQueryParser: MongoQueryParser) {

  // You will only need one instance of class MongoClient even with multiple concurrently executing asynchronous operations.
  val mongoClient: MongoClient = MongoClient("mongodb://localhost")
  val database: MongoDatabase = mongoClient.getDatabase("vm")
  val collection: MongoCollection[Document] = database.getCollection("letters")

  def executeQuery(query: String): Seq[String] = Try {
    val result: Future[Document] = collection.find(mongoQueryParser.parse(query)).first().head()
    List(Await.result(result, Duration(30, SECONDS)).toJson(new JsonWriterSettings(JsonMode.STRICT, true)))
  } match {
    case Success(value) => value
    case Failure(f) => List()
  }
} 
开发者ID:dougsleite,项目名称:oak,代码行数:35,代码来源:MongoService.scala


示例5: UserAuthToken

//设置package包名称以及导入依赖的类
package com.github.cupenya.auth.service.persistence

import org.bson.BsonString
import org.mongodb.scala.MongoDatabase
import org.mongodb.scala.bson._
import org.mongodb.scala.bson.collection.immutable.Document

import scala.concurrent.{ExecutionContext, Future}
import org.mongodb.scala.model.Filters._
import spray.json.DefaultJsonProtocol


case class UserAuthToken(
  id: String,
  userId: String,
  createdAt: Long    ,
  forceTeamId: Option[String] = None
) extends UserAuthTokenModel

sealed trait UserAuthTokenModel

object UserAuthTokenModel extends DefaultJsonProtocol {
  implicit val UserAuthTokenFormat = jsonFormat4(UserAuthToken)
}

trait UserAuthTokenDao extends MongoDao {
  override def collectionName: String = "UserAuthToken"

  def removeByUserId(userId: String)(implicit ec: ExecutionContext, db: MongoDatabase): Future[Long] = {
    removeByQuery(equal("userId", userId))
  }

  def insert(userAuthToken: UserAuthToken)(implicit ec: ExecutionContext, db: MongoDatabase): Future[Boolean] = {
    insert[UserAuthToken](userAuthToken)
  }

  def findByAuthKey(authKey: String)(implicit ec: ExecutionContext, db: MongoDatabase): Future[Option[UserAuthToken]] =
    findById[UserAuthToken](authKey)
}

object UserAuthTokenDao extends UserAuthTokenDao 
开发者ID:cupenya,项目名称:auth-service,代码行数:42,代码来源:UserAuthTokenDao.scala


示例6: DatabaseContext

//设置package包名称以及导入依赖的类
package ai.snips.bsonmacros

import javax.inject._

import org.mongodb.scala.{MongoClient, MongoDatabase}
import play.api._
import play.api.inject.ApplicationLifecycle

import scala.concurrent._

@Singleton
class DatabaseContext @Inject()(val conf: Configuration,
                                applicationLifecycle: ApplicationLifecycle)
                               (implicit val ec: ExecutionContext) {

  lazy val mongoConf: String = conf.getOptional[String]("mongodb.uri").getOrElse("mongodb://localhost")
  lazy val client = MongoClient(mongoConf)
  lazy val codecRegistry = new DynamicCodecRegistry

  applicationLifecycle.addStopHook { () =>
    Future.successful(client.close())
  }

  def database(name: String): MongoDatabase =
    client.getDatabase(name).withCodecRegistry(codecRegistry)

  def ping(): Future[Unit] =
    client.listDatabaseNames().toFuture.map(_ => ())
} 
开发者ID:snipsco,项目名称:play-mongo-bson,代码行数:30,代码来源:DatabaseContext.scala


示例7: PlatformRepository

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

import com.buysomegames.model.Platform
import com.google.inject.Inject
import org.mongodb.scala.MongoDatabase

import scala.concurrent.Future

class PlatformRepository @Inject()(
                                    db: MongoDatabase
                                  ) {
  def findAllPlatforms: Future[Iterable[Platform]] = {
    val collection = db.getCollection("platforms")
    val documents = collection.find()
    documents.map(doc =>
      new Platform(
        name = doc.get("name").get.asString().getValue,
        id = doc.get("_id").get.asString().getValue
      )
    ).toFuture()
  }
} 
开发者ID:kaliy,项目名称:buysomegames,代码行数:23,代码来源:PlatformRepository.scala


示例8: GameRepository

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

import com.buysomegames.model.Game
import com.google.inject.Inject
import org.mongodb.scala.MongoDatabase

import scala.concurrent.Future

class GameRepository @Inject()(
                                db: MongoDatabase
                              ) {
  def findAllGames: Future[Iterable[Game]] = {
    val collection = db.getCollection("games")
    collection.find().map(doc =>
      new Game(
        name = doc.get("name").get.asString().getValue,
        description = doc.get("description").get.asString().getValue
      )
    ).toFuture()
  }
} 
开发者ID:kaliy,项目名称:buysomegames,代码行数:22,代码来源:GameRepository.scala


示例9: GameEditionRepository

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

import java.time.ZoneId

import com.buysomegames.model.{GameEdition, GameEditionGame, Platform}
import com.google.inject.Inject
import org.mongodb.scala.MongoDatabase
import org.mongodb.scala.bson.BsonDocument
import org.mongodb.scala.bson.collection.Document

import scala.concurrent.Future

class GameEditionRepository @Inject()(
                                       db: MongoDatabase
                                     ) {
  def findAllGameEditions: Future[Iterable[GameEdition]] = {
    val collection = db.getCollection("game_editions")
    collection.find().map(mapGameEdition).toFuture()
  }

  private def mapGameEdition(doc: Document): GameEdition = {
    val gameDocument = doc.get[BsonDocument]("game").get
    val game = new GameEditionGame(
      id = gameDocument.getObjectId("_id").getValue,
      name = gameDocument.getString("name").getValue
    )
    new GameEdition(
      id = doc.getObjectId("_id"),
      name = doc.get("name").get.asString().getValue,
      region = doc.get("region").get.asString.getValue,
      platform = new Platform(id = "PS3", name = "changeit"),
      game = game,
      releaseDate = doc.getDate("release_date").toInstant.atZone(ZoneId.of("UTC")).toLocalDate
    )
  }
} 
开发者ID:kaliy,项目名称:buysomegames,代码行数:37,代码来源:GameEditionRepository.scala


示例10: beforeEach

//设置package包名称以及导入依赖的类
package com.buysomegames.test

import java.util.concurrent.TimeUnit

import org.mongodb.scala.MongoDatabase
import org.mongodb.scala.bson.collection.immutable.Document

import scala.concurrent.Await
import scala.concurrent.duration.Duration
import scala.io.Source

trait FreshDatabase extends com.twitter.inject.IntegrationTest {
  override protected def beforeEach(): Unit = {
    insertDataFromResourceIntoCollection("/data/games.dump", "games")
    insertDataFromResourceIntoCollection("/data/platforms.dump", "platforms")
    insertDataFromResourceIntoCollection("/data/game_editions.dump", "game_editions")
  }

  private def insertDataFromResourceIntoCollection(json: String, collection: String): Unit = {
    val mongoCollection = injector.instance[MongoDatabase].getCollection(collection)
    val lines = Source.fromInputStream(getClass.getResourceAsStream(json)).getLines
    Await.result(mongoCollection.drop().head(), Duration(10, TimeUnit.SECONDS))
    Await.result(mongoCollection.insertMany(lines.map(json => Document(json)).toSeq).toFuture(), Duration(10, TimeUnit.SECONDS))
  }
} 
开发者ID:kaliy,项目名称:buysomegames,代码行数:26,代码来源:FreshDatabase.scala


示例11: getAvailableCollections

//设置package包名称以及导入依赖的类
package org.sunnyshahmca.connect.mongodb

package object databaseReader {
  import org.mongodb.scala.{MongoClient,MongoDatabase,MongoCollection,Document,FindObservable}
  import scala.concurrent.{ExecutionContext, Future}
  import scala.concurrent.ExecutionContext.Implicits.global
  import common._
  import common.OpRetrierImplicits._

  def getAvailableCollections(mongoClient:MongoClient, database:MongoDatabase)
    (implicit maxRetriesAllowed:MaxRetriesAllowed, delayBetweenRetries:DelayBetweenRetries)
    :Future[Seq[String]] = {
    val collectionNames = OpRetrier(() => database.listCollectionNames().toFuture)(maxRetriesAllowed,delayBetweenRetries)
    collectionNames.map{ _.filter { ! _.startsWith("system.") } }
  }

  def availableDatabases(mongoClient:MongoClient)
  (implicit maxRetriesAllowed:MaxRetriesAllowed, delayBetweenRetries:DelayBetweenRetries):Future[Seq[String]]
   = { OpRetrier(() => mongoClient.listDatabaseNames().toFuture)(maxRetriesAllowed,delayBetweenRetries) }
   
} 
开发者ID:ShahSunny,项目名称:Mongodb-kafka-connector,代码行数:22,代码来源:DatabaseReader.scala


示例12: ReminderRepository

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

import com.typesafe.config.{Config, ConfigFactory}
import de.neuland.models.ReminderRecord
import org.bson.codecs.configuration.CodecRegistries.{fromProviders, fromRegistries}
import org.bson.codecs.configuration.CodecRegistry
import org.mongodb.scala.bson.codecs.DEFAULT_CODEC_REGISTRY
import org.mongodb.scala.bson.codecs.Macros._
import org.mongodb.scala.model.Filters._
import org.mongodb.scala.{Completed, MongoClient, MongoCollection, MongoDatabase}
import play.api.Logger

import scala.concurrent.Future

class ReminderRepository {
  val conf: Config = ConfigFactory.load

  val codecRegistry: CodecRegistry = fromRegistries(fromProviders(classOf[ReminderRecord]), DEFAULT_CODEC_REGISTRY )
  val mongoClient: MongoClient = MongoClient(conf.getString("db.mongo"))
  val database: MongoDatabase = mongoClient.getDatabase(conf.getString("db.database")).withCodecRegistry(codecRegistry)
  val collection: MongoCollection[ReminderRecord] = database.getCollection("reminders")

  def save(reminderRecord: ReminderRecord): Future[Completed] = {
    Logger.debug("Save " + reminderRecord)
    collection.insertOne(reminderRecord).head()
  }

  def all(): Future[Seq[ReminderRecord]] =  {
    collection.find().toFuture()
  }

  def find(author: String): Future[Seq[ReminderRecord]] = {
    collection.find(equal("author", author)).toFuture()
  }

} 
开发者ID:neuland,项目名称:matterminder,代码行数:37,代码来源:ReminderRepository.scala


示例13: MongoDBTrialsTest

//设置package包名称以及导入依赖的类
package operation.trivia.db

import com.mongodb.client.model.Filters
import operation.trivia.entities.Question
import org.mongodb.scala.bson.{BsonArray, BsonString}
import org.mongodb.scala.model.Updates
import org.mongodb.scala.{Completed, Document, MongoClient, MongoDatabase}
import org.scalatest.{BeforeAndAfter, FunSuite, Matchers}


class MongoDBTrialsTest extends FunSuite with Matchers with BeforeAndAfter {

  val mongoClient: MongoDatabase =
    MongoClient().getDatabase("operation_trivia")

  test("Test reading collections from Mongo DB") {
    mongoClient.listCollectionNames().subscribe((s: String) => println(s))
    Thread.sleep(4000)
  }


  test("Test reading collections from Mongo DB get limit of the first one") {

    def createQuestion(doc: Document): Option[Question] = {
      import collection.JavaConverters._
      for (
        item         <- doc.get("question").map(_.asString.getValue);
        actualAnswer <- doc.get("actualAnswer").map(_.asNumber().intValue());
        items        <- doc.get("answers").map(bson => bson.asArray()
                        .getValues.asScala.map(i => i.asString().getValue))
                        .map(_.toList)
      ) yield Question(item, items, actualAnswer)
    }

    mongoClient.getCollection("questions")
      .findOneAndUpdate(Filters.eq("taken", false), Updates.set("taken", true)).map(createQuestion)
      .subscribe((q: Option[Question]) => println(q))

    println("Done")
    Thread.sleep(4000)
  }

  test("Test create a Question") {
    def createDocument(question:Question): Document = {
      Document("question" -> question.item,
        "actualAnswer" -> question.actualAnswer,
        "answers" -> BsonArray(question.possibleAnswers.map(s => BsonString(s))))
    }

    mongoClient.getCollection("questions").insertOne(createDocument(Question("What is the capitol of Wyoming?",
                                                                    List("Cheyenne","Casper","Jackson","Sheridan"), 0)))
                                           .subscribe((c:Completed) => println(c))

    println("Done")
    Thread.sleep(4000)
  }
} 
开发者ID:dhinojosa,项目名称:operation-trivia,代码行数:58,代码来源:MongoDBTrialsTest.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala CircuitBreaker类代码示例发布时间:2022-05-23
下一篇:
Scala path类代码示例发布时间: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