查看MongoDB文档,您可以确保在应用程序运行时使用如下所示的命令为集合创建索引:
db.myCollection.ensureIndex({'my-col': 1}, {unique: true})
Run Code Online (Sandbox Code Playgroud)
我在反应性mongo apis中找不到这样的东西.这样的事情存在吗?
我使用ReactiveMongo 0.10.0,我有以下用户案例类和性别Enumeration对象:
case class User(
_id: Option[BSONObjectID] = None,
name: String,
gender: Option[Gender.Gender] = None)
object Gender extends Enumeration {
type Gender = Value
val MALE = Value("male")
val FEMALE = Value("female")
val BOTH = Value("both")
}
Run Code Online (Sandbox Code Playgroud)
我声明了两个隐式宏处理程序:
implicit val genderHandler = Macros.handler[Gender.Gender]
implicit val userHandler = Macros.handler[User]
Run Code Online (Sandbox Code Playgroud)
但是,当我运行应用程序时,我收到以下错误:
Error:(123, 48) No apply function found for reactive.userservice.Gender.Gender
implicit val genderHandler = Macros.handler[Gender.Gender]
^
Error:(125, 46) Implicit reactive.userservice.Gender.Gender for 'value gender' not found
implicit val userHandler = Macros.handler[User]
^
Run Code Online (Sandbox Code Playgroud)
有人知道如何将宏处理程序写入Enumeration对象吗?
提前致谢!
我有使用MongoDBvia的Play 2.1应用程序Reactivemongo 0.8 plugin.在我的应用程序中,我使用此处描述的aproach 而不使用模型
我有从mongodb返回所有文件的方法,其中"type"等于函数getTypeAll中的getType参数,例如{"type": "computer"}工作正常.
def getTypeAll(getType: String) = Action {
val validatedType = getType.replaceAll("-"," ")
val q = QueryBuilder().query(toType.writes(validatedType))
Async {
val f = collection.find[JsValue](q)
f.toList.map{
jsonp =>
Ok( Json.toJson(jsonp) )
}
}
}
Run Code Online (Sandbox Code Playgroud)
toType写为,val toType = OWrites[String]{ s => Json.obj("type" -> s) }而val集合定义为lazy val collection = db("mycollection")
问题是我无法编写方法来获取"type"等于相同参数的文档的计数.
def countTypeAll(getType: String) = Action {
}
Run Code Online (Sandbox Code Playgroud)
并将其作为json返回{{typecount":45}
我正在寻找我找到的每一个例子但没有成功.我认为我想要的是类似的东西val c = collection.find[JsValue](q).count()
但它说错误 value size is …
下面是使用Mongo更新文档的代码FindAndModify:
val selector = BSONDocument("id" -> "1234")
val modifier = BSONDocument("$set" -> BSONDocument("email" -> "new@domain.com"))
ReactiveMongoPlugin.db.command(FindAndModify(
collection.name,
selector,
Update(modifier, false),
false,
None
)).transform(
success => success.map { s =>
// doesn't work...
Json.fromJson[Seq[JsValue]](toJson(s)).map(for (item <- _) yield item).get
}.getOrElse(List[JsValue]()),
failure => failure match {
case e: LastError => DaoServiceException(e.message, Some(DATABASE_ERROR))
}
)
Run Code Online (Sandbox Code Playgroud)
在success块我试图将返回的BSONDocument集合转换为JsValue集合...但它不起作用,结果JsValue集合总是空的(我已经验证BSONDocument了命令返回的集合,我确认它是非空的).我错过了什么吗?
我有一个非常简单的案例类,它是更大案例类的一部分.
case class PublisherStatus(status: String)
case class Publisher(id: Option[BSONObjectID], name: String, status: PublisherStatus, keywords: List[String], updatedAt: Option[DateTime], outputChannelIP: String, outputChannelName: String)
Run Code Online (Sandbox Code Playgroud)
我已经为它定义了BSON Reader和Writer,如下所示.
implicit object StatusBSONReader extends BSONDocumentReader[PublisherStatus] {
def read(doc: BSONDocument): PublisherStatus =
PublisherStatus(
doc.getAs[String]("status").get
)
}
implicit object StatusBSONWriter extends BSONDocumentWriter[PublisherStatus] {
def write(status: PublisherStatus): BSONDocument =
BSONDocument(
"status" -> status.status)
}
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试执行以下操作时,我收到编译错误.
def updateState(id: String, s: String) {
import models.PublisherBSONWriter._
implicit val statusWrites = Json.writes[PublisherStatus]
val objectId = new BSONObjectID(id)
val status = PublisherStatus(s)
val modifier = …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用ScalaTest + embedmongo + reactivemongo 进行一些测试但是我失败了.我的第一个问题是,在测试mongod进程没有关闭后,我在控制台中有这条消息:
INFO: stopOrDestroyProcess: process has not exited
Run Code Online (Sandbox Code Playgroud)
并且暂停测试直到我手动终止该过程.即使我的测试体是空的,也会发生这种情况.我正在运行Windows 8.1.
另一个问题是,当我尝试使用反应式mongo连接到db里面并向db插入任何内容时,我得到以下异常:
reactivemongo.core.errors.ConnectionNotInitialized: MongoError['Connection is missing metadata (like protocol version, etc.) The connection pool is probably being initialized.']
Run Code Online (Sandbox Code Playgroud)
我真的不知道如何设置它.这是我的测试代码:
package model
import com.github.simplyscala.MongoEmbedDatabase
import org.scalatest.{OptionValues, Matchers, BeforeAndAfter, FlatSpec}
import reactivemongo.api.MongoDriver
import reactivemongo.api.collections.bson.BSONCollection
import scala.concurrent.duration._
import reactivemongo.bson.BSONDocument
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Await
class MongoBookingRepositoryTest extends FlatSpec
with Matchers
with OptionValues
with MongoEmbedDatabase
with BeforeAndAfter {
"A MongoBookingRepository" should "..." in withEmbedMongoFixture(port = 12345) { mongoProps =>
val driver = …Run Code Online (Sandbox Code Playgroud) 我有一个用Play和ReactiveMongo编写的应用程序,我想要:
landingPage文档插入MongoDB的操作.我有这个工作代码:
// Insert the landing page and wait for it to be inserted, so we can then get the new count of landing pages.
val futures = for {
wr <- landingPagesCollection.insert(landingPage)
count <- landingPagesCollection.count()
} yield count
futures.map { (count: Int) =>
Created(Json.obj(
"created" -> true,
"landingPage" -> landingPage.toJson,
"count" -> count
))
}
Run Code Online (Sandbox Code Playgroud)
这段代码工作正常.但是,出于好奇,我想知道如何访问wr(WriteResult)值.当我将代码更改为:
val futures = for {
wr <- landingPagesCollection.insert(landingPage)
count <- landingPagesCollection.count()
} yield (wr, count)
futures.map …Run Code Online (Sandbox Code Playgroud) 我需要offset从查询中跳过一些文档(),并且只返回limit后续文档的数量.我知道以下天真的方法:
collection.find(BSONDocument())
.cursor[T].collect[List](offset+limit).map(_.drop(offset))
Run Code Online (Sandbox Code Playgroud)
但它并不是真正需要的,因为它会offset+limit在JVM内存中加载大量文档,而我想在"数据库"端过滤它们.
我目前升级到0.12.RC3,希望能解决我遇到的以下问题.升级后,我收到了该collect方法的弃用警告.
所以我离开了:
def find(query: JsObject = Json.obj())(implicit reader: Reads[T]): Future[List[T]] = {
collection.flatMap(_.find(query).cursor[T](ReadPreference.nearest).collect[List]())
}
Run Code Online (Sandbox Code Playgroud)
至:
def find(query: JsObject = Json.obj())(implicit reader: Reads[T]): Future[List[T]] = {
collection.flatMap(_.find(query).cursor[T](ReadPreference.nearest).collect[List](Int.MaxValue, Cursor.FailOnError()))
}
Run Code Online (Sandbox Code Playgroud)
但是,遗憾的是我收到以下错误:
类型不匹配,预期:(JSONCollection)=> Future [NotInferedS],actual:(JSONCollection)=> Any
假设我想要执行以下操作(在mongo shell中):
var bulk = db.vectors.initializeOrderedBulkOp()
bulk.find({"_id" : ObjectId("53f265da13d3f885ed8bf75d")}).updateOne({"$pop": {"v": 1}})
bulk.find({"_id" : ObjectId("53f265da13d3f885ed8bf75d")}).updateOne({"$push": {"v": 5}})
bulk.execute()
Run Code Online (Sandbox Code Playgroud) reactivemongo ×10
scala ×8
mongodb ×5
future ×1
implicit ×1
json ×1
scala-2.10 ×1
scalatest ×1