如果 None - scala 不要插入 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)
}

当前,如果endedAt、endedMethod、marksOptionNone,我将保留空值

如果endedAt、endedMethod、marksOptionNone,则不保留null值,我根本不想将它们保留到集合中。

有人能帮我吗?

由于Updates.combine是可变的(它需要任意多个Bson(:

def combine(updates: Bson*): Bson

这意味着您可以利用Seq变参数技巧:

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可能会更加简洁,但希望这能让人理解这个想法。

最新更新