3

I have a document in MongoDB that looks like this:

{"_id":"asdf", "data":[
    {"a":"1","b":"2"}, 
    {"a":"3","b":"4"}, 
    {"a":"5","b":"6"}, 
]}

I would like to query that object using Scala, and convert the entries in "data" into a list of case classes. After a few hours' work, I've yet to come up with something that even compiles. Can someone point me to a tutorial with this information? This tutorial hasn't been any help. I've tried every combination of nested maps, fors, foreaches, casts, and pattern matching that I can come up with.

Edit: My super-ugly but now seemingly working code is now this:

def getData(source_id:String) = {
    val source = collection.findOne(MongoDBObject("_id" -> source_id)).get
    val data = source.get("data").asInstanceOf[BasicDBList]

    var ret:List[Data] = List()

    val it = presses.iterator
    while(it.hasNext) {
        val item = it.next.asInstanceOf[BasicDBObject]

        ret = Data(
            item.get("a").asInstanceOf[String],
            item.get("b").asInstanceOf[String]
        ) :: ret
    }

    ret
}

Please, someone tell me there's a better way.

4

1 回答 1

1

无论如何您都在使用案例类,最简单的解决方案是只使用salat - 它会自动序列化/反序列化到 mongo 连接和从一个非常少的样板连接。

一个小问题,但在您的代码中,您应该能够简单地map跨越 DBObject 持有结构,而不是手动改变ret变量:

val ret = presses.map { item => Data(…) }

如果你真的想要一个 List,你可能需要调用 .toList (尽管你可能只需要 Seq 或 Iterable)

于 2012-06-12T02:46:02.757 回答