How can I recursively append to a DBObject
in Casbah, and then return a single MongoDBObject
with each list element appended?
Note that the below does not compile or work, but it intends to show my desired code
def foo( pairs: List[(String, Int)]): List[MongoDBObject] = {
def go( ps: List[(String, Int)], acc: List[MongoDBObject]): List[MongoDBObject] =
ps match {
case x :: xs if(x._1 == "BAD") => go(xs, acc)
case x :: xs => go(xs, MongoDBObject(x._1 -> x._2) :+ acc) /* error line */
case Nil => acc
}
}
val pairsList: List[MongoDBObject] = foo( getPairs() ) // assume getPairs() is defined
val builder = // do something to convert pairsList -> MongoDBObject (maybe a fold?)
val results = collection.find(builder)
When I tried something like the above, I saw the following compile-time error at my second case statement.
[myApp] $ compile
[info] Compiling 1 Scala source to ...
[error] c:\development\myApp\Test.scala:85: overloaded method value apply with alternatives:
[error] [A(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply) <
: String, B(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)](e
lems: List[(A(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply),
B(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply))])com.mongo
db.casbah.commons.Imports.DBObject <and>
[error] [A(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply) <
: String, B(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)](e
lems: (A(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply), B(in
method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply)(in method apply))*)com.mongodb.ca
sbah.commons.Imports.DBObject
[error] cannot be applied to (com.mongodb.casbah.query.Imports.DBObject with com.mongodb.casbah.query.dsl.QueryExpressionObject)
[error] go(xs, acc :+ MongoDBObject(elemMatch))
[error] ^
[error] one error found
If you want to append the new object to the list this should do it:
MongoDBObject(x._1 -> x._2) :: acc