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



我使用mongo scala驱动程序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":****
}                                                                                              
]
}

创建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.

最新更新