本文整理汇总了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)
}
}
示例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)
}
}
示例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)
}
}
示例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()
}
}
示例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
示例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(_ => ())
}
示例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()
}
}
示例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()
}
}
示例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
)
}
}
示例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))
}
}
示例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) }
}
示例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()
}
}
示例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)
}
}