简体   繁体   English

阅读Casbah MongoDB查询的结果

[英]Reading the results of a Casbah MongoDB query

I have a document in MongoDB that looks like this: 我在MongoDB中有一个文档如下所示:

{"_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. 我想使用Scala查询该对象,并将“data”中的条目转换为case类列表。 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. 我已经尝试了嵌套地图,fors,foreaches,casts和模式匹配的每种组合,我可以想出来。

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. 请有人告诉我有更好的方法。

As you are using case classes anyway, the easiest solution is to just use salat – it will automatically serialize/deserialize to and from a mongo connection with very little boilerplate. 无论如何,当您使用案例类时,最简单的解决方案是使用salat - 它将自动序列化/反序列化为mongo连接和非常少的样板。

A minor point, but in your code you should be able to simply map across the DBObject holding structure rather than manually mutate the ret variable: 一个小问题,但在您的代码中,您应该能够简单地map DBObject保持结构,而不是手动改变ret变量:

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

you may need to call .toList if you really want a List (though you may only need Seq or Iterable) 如果你真的想要一个List,你可能需要调用.toList(尽管你可能只需要Seq或Iterable)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM