使用Scala将嵌入式文档插入MongoDB时出错

时间:2020-04-03 15:38:24

标签: mongodb scala

我使用mongo-scala-driver 2.9.0,这是一个将用户推荐列表保存到MongoDB的功能。参数 streamRecs 是(productId:Int,score:Double)的数组。现在,我要插入一个由 useId 及其相关推荐列表 recs 组成的文档。但是,val doc:Document = Document("userId" -> userId,"recs"->recs)行中有错误。有人知道出什么问题了吗?

  def saveRecsToMongoDB(userId: Int, streamRecs: Array[(Int, Double)])(implicit mongoConfig: MongoConfig): Unit ={
    val streamRecsCollection = ConnHelper.mongoClient.getDatabase(mongoConfig.db).getCollection(STREAM_RECS_COLLECTION)
    streamRecsCollection.findOneAndDelete(equal("userId",userId))
    val recs: Array[Document] = streamRecs.map(item=>Document("productId"->item._1,"score"->item._2))
    val doc:Document = Document("userId" -> userId,"recs"->recs)
    streamRecsCollection.insertOne(doc)
  }

我要插入到MongoDB中的文档是这样的(这意味着 用户及其推荐产品和分数):

{
  "_id":****,
  "userId":****,
  "recs":[
         {
          "productId":****,
          "score":****
         },
         {
          "productId":****,
          "score":****
         },
         {
          "productId":****,
          "score":****
         },
         {
          "productId":****,
          "score":****
         }                                                                                              
         ]

}

1 个答案:

答案 0 :(得分:0)

在创建BSON文档时,为键/值对中的每个值显式声明Bson类型,如下所示:

/* Compose Bson document */
val document = Document(
   "email" -> BsonString("email@domain.com"),
   "token" -> BsonString("some_random_string"),
   "created" -> BsonDateTime(org.joda.time.DateTime.now.toDate)
)

要查看示例,请检查https://code.linedrop.io/articles/Storing-Object-in-MongoDB