【问题标题】:Nested fields in mongodb Documents with scala带有scala的mongodb文档中的嵌套字段
【发布时间】:2018-05-22 16:08:59
【问题描述】:

在将 mongodb 连接从 Scala 应用程序从 Mongodb+Casbah 升级到 mongo-scala-driver 2.3.0 (scala 2.11.8) 时,我们在创建要插入数据库的文档时遇到了一些问题。基本上,我遇到了 Map[String,Any] 或 Map[Int,Int] 类型的嵌套字段的问题。

如果我的字段是 Map["String", Int] 类型就没有问题,代码编译也没有问题:

val usersPerPage = Map("home" -> 23, "contact" -> 12) //Map[String,Int]
Document("page_id" -> pageId, "users_per_page" -> Document(usersPerPage))  
//Compiles 

val usersPerTime = Map(180 -> 23, 68 -> 34) //Map[Int,Int]
Document("page_id" -> pageId, "users_per_time" -> Document(usersPerTime)) 
//Doesn't compile

val usersConf = Map("age" -> 32, "country" -> "Spain") //Map[String,Any]
Document("user_id" -> userId, "user_conf" -> Document(usersConf)) 
//Doesn't compile

我尝试了许多解决方法,但我无法创建一个完整的文档来插入 Map[Int,Int] 和 Map[String,Any] 类型的字段,我想通过升级到更新版本Mongo会让事情变得更容易..我错过了什么?

【问题讨论】:

    标签: mongodb scala


    【解决方案1】:

    请记住,Map[Int,Int] 类型不是有效的文档映射,因为Documents
    k,v -> String, BsonValue 格式。

    这将因此编译:

    val usersPerTime = Map("180" -> 23, "68" -> 34) //Map[String,Int]
    Document("page_id" -> pageId, "users_per_time" -> Document(usersPerTime)) 
    

    对于这两种情况,直接使用 Document 类而不是 Map:

    val usersConf = Document("age" -> 32, "country" -> "Spain") 
    Document("user_id" -> userId, "user_conf" -> usersConf) 
    

    这适用于"org.mongodb.scala" %% "mongo-scala-driver" % "2.1.0"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-26
      • 1970-01-01
      • 2019-09-24
      • 2021-11-12
      • 1970-01-01
      • 2017-01-27
      • 1970-01-01
      • 2020-10-06
      相关资源
      最近更新 更多