首页 > 解决方案 > 如果没有,不要插入 mongo - scala

问题描述

我正在使用以下方法使用 Scala 驱动程序将数据插入 mongodb。

def updateUserTestProgress(userId: Long, providerId: String, provider: String, contentId: Long, 
                           contentType: String, chapterId: Long, subjectId: Long, courseId: Long, status: String,
                           startedAt: Long, endedAt: Option[Long], endedMethod: Option[String], marksOption: Option[Double]) = {
    
    val collection = database.getCollection("user_content_progress")
    val res = collection.updateOne(
      Filters.and(
        Filters.eq("user_id", userId),
        Filters.eq("content_id", contentId)),
      Updates.combine(
        Updates.setOnInsert("course_id", courseId),
        Updates.setOnInsert("subject_id", subjectId),
        Updates.setOnInsert("chapter_id", chapterId),
        Updates.setOnInsert("content_type", contentType),

        Updates.set("status", status),
        Updates.set("last_activity_date", System.currentTimeMillis()),
        Updates.set("test_content.provider", provider),
        Updates.set("test_content.provider_id", providerId),
        Updates.set("test_content.start_time_in_millis", startedAt),
        Updates.set("test_content.end_time_in_millis", endedAt),
        Updates.set("test_content.ended_method", endedMethod),
        Updates.set("test_content.marks", marksOption)),
      new UpdateOptions().upsert(true))
    res.foreach(u => u)
  }

目前,如果endAt、endMethod、marksOptionNone ,我将保留 null 值

如果endAt、endMethod、marksOptionNone我不想将它们持久化到集合中,而不是持久化 null 值。

任何人都可以帮助我吗?

标签: mongodbscala

解决方案


由于Updates.combine是可变参数(它需要任意多个Bsons):

def combine(updates: Bson*): Bson

这意味着您可以利用Seqto variadic arguments 技巧:

seq: _*

所以:

val collection = database.getCollection("user_content_progress")
val updates = Seq(
  Updates.setOnInsert("course_id", courseId),
  Updates.setOnInsert("subject_id", subjectId),
  Updates.setOnInsert("chapter_id", chapterId),
  Updates.setOnInsert("content_type", contentType),
  Updates.set("status", status),
  Updates.set("last_activity_date", System.currentTimeMillis),
  Updates.set("test_content.provider", provider),
  Updates.set("test_content.provider_id", providerId),
  Updates.set("test_content.start_time_in_millis", startedAt)
) ++ Seq(
  endedAt.map(Updates.set("test_content.end_time_in_millis", _)),
  endedMethod.map(Updates.set("test_content.ended_method", _)),
  marksOption.map(Updates.set("test_content.marks", _))
).flatten

val res = collection.updateOne(
  Filters.and(
    Filters.eq("user_id", userId),
    Filters.eq("content_id", contentId)),
  Updates.combine(
    updates: _*),
  new UpdateOptions().upsert(true))

定义更简洁是可能的updates,但希望这能传达这个想法。


推荐阅读