mongodb - 如果没有,不要插入 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、marksOption为None ,我将保留 null 值
如果endAt、endMethod、marksOption是None我不想将它们持久化到集合中,而不是持久化 null 值。
任何人都可以帮助我吗?
解决方案
由于Updates.combine
是可变参数(它需要任意多个Bson
s):
def combine(updates: Bson*): Bson
这意味着您可以利用Seq
to 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
,但希望这能传达这个想法。
推荐阅读
- javascript - 始终检查语句更新
- javascript - JavaScript 匿名函数作用域变量
- windows - android studio的窗口在windows 8.1 pro上闪烁
- python - 假正数布隆过滤器
- r - 是否可以在 R 包之间共享 C++ 类?
- html - 如何使用渐变 CSS 使图像变暗一半?
- javascript - Summer-note 在引导模式中不起作用(从视图中加载模式内容)
- python - 如何为 OCR 制作 REST API
- python - Python/Pandas 新手:重新分配给新变量时,对数据框进行了不必要的更改
- php - 如果发布时文件中的匹配,PHP删除数组元素