【问题标题】:How to convert MongoDBList to BasicDBList?如何将 MongoDBList 转换为 BasicDBList?
【发布时间】:2013-03-03 16:39:18
【问题描述】:

我使用 Casbah 2.5.0。教程中有例子:

scala> val builder = MongoDBList.newBuilder
scala> builder += "foo"
scala> builder += "bar"
scala> builder += "x"
scala> builder += "y"
builder.type = com.mongodb.casbah.commons.MongoDBListBuilder@...

scala> val newLst = builder.result
newLst: com.mongodb.BasicDBList = [ "foo" , "bar" , "x" , "y"]

所以这里的 newLst 是 BasicDBList。

但是当我自己尝试时,它的效果就不同了。

scala> val builder = MongoDBList.newBuilder
scala> builder += "foo"
scala> builder += "bar"
scala> val newLst = builder.result
newLst: com.mongodb.casbah.commons.MongoDBList = [ "foo" , "bar"]

这里的newLst 是MongoDBList 类型。

为什么会这样?如何将 MongoDBList 转换为 BasicDBList?

【问题讨论】:

    标签: scala casbah


    【解决方案1】:

    在 casbah 中存在从 com.mongodb.casbah.commons.MongoDBListcom.mongodb.BasicDBList 的隐式转换(检查 com.mongodb.casbah.commons.Implicits):

    implicit def unwrapDBList(in: MongoDBList): BasicDBList = in.underlying
    

    只需将 MongoDBList 传递到期望 BasicDBList 的位置:

    scala>  val l: BasicDBList = newLst
    l: com.mongodb.casbah.Imports.BasicDBList = [ "foo" , "bar"]
    

    如果你想从List创建MongoDBList

    scala>  val list = List("foo", "bar")
    list: List[java.lang.String] = List(foo, bar)
    
    scala>  val dbList = MongoDBList(list:_*)
    dbList: com.mongodb.casbah.commons.MongoDBList = [ "foo" , "bar"]
    

    【讨论】:

    • 谢谢。还有一个问题。有没有一种简单的方法可以将 List 转换为 MongoDBList(或 BasicDBList)?
    • @SergeyPassichenko 你也可以回答stackoverflow.com/questions/15188605/…吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-17
    • 2010-09-08
    相关资源
    最近更新 更多