文档菜单
文档首页
/ / /
Kotlin 协程

单次操作插入或更新

本页内容

  • 概述
  • 指定 Upsert

在本指南中,您将学习如何使用 MongoDB Kotlin 驱动程序执行 upsert 操作。

应用程序使用插入和更新操作来存储和修改数据。有时,您需要根据文档是否存在来选择插入或更新。MongoDB 通过一个upsert 选项来简化我们的这个决策。

upsert

  • 更新与您的查询过滤器匹配的文档

  • 如果没有匹配到查询过滤器的文档,则插入一个文档

要使用 updateOne()updateMany() 方法指定 upsert,请将 true 传递给 UpdateOptions.upsert()

要使用 replaceOne() 方法指定 upsert,请将 true 传递给 ReplaceOptions.upsert()

以下示例中,一家油漆店销售八种不同颜色的油漆。该店举办了年度在线促销活动。他们的 paint_inventory 集合现在显示以下文档

{ "_id": { "$oid": "606b4cfbcd83be7518b958da" }, "color": "red", "qty": 5 }
{ "_id": { "$oid": "606b4cfbcd83be7518b958db" }, "color": "purple", "qty": 8 }
{ "_id": { "$oid": "606b4cfbcd83be7518b958dc" }, "color": "blue", "qty": 0 }
{ "_id": { "$oid": "606b4cfbcd83be7518b958dd" }, "color": "white", "qty": 0 }
{ "_id": { "$oid": "606b4cfbcd83be7518b958de" }, "color": "yellow", "qty": 6 }
{ "_id": { "$oid": "606b4cfbcd83be7518b958df" }, "color": "pink", "qty": 0 }
{ "_id": { "$oid": "606b4cfbcd83be7518b958e0" }, "color": "green", "qty": 0 }
{ "_id": { "$oid": "606b4cfbcd83be7518b958e1" }, "color": "black", "qty": 8 }

该数据使用以下 Kotlin 数据类建模

data class PaintOrder(
@BsonId val id: ObjectId = ObjectId(),
val qty: Int,
val color: String
)

商店收到了一批新货并需要更新库存。这批货的第一件是十罐橙色油漆。

为了更新库存,查询paint_inventory集合,其中color"orange",指定更新操作increment qty字段增加10,并指定trueUpdateOptions.upsert()

val filter = Filters.eq(PaintOrder::color.name, "orange")
val update = Updates.inc(PaintOrder::qty.name, 10)
val options = UpdateOptions().upsert(true)
val results = collection.updateOne(filter, update, options)
println(results)
AcknowledgedUpdateResult{ matchedCount=0, modifiedCount=0, upsertedId=BsonObjectId{ value=606b4cfc1601f9443b5d6978 }}

这个AcknowledgedUpdateResult告诉我们

  • 没有文档匹配我们的查询过滤器

  • 我们的集合中没有文档被修改

  • 一个_id606b4cfc1601f9443b5d6978的文档被upserted

以下显示了paint_inventory集合中的文档

{ "_id": { "$oid": "606b4cfbcd83be7518b958da" }, "color": "red", "qty": 5 }
{ "_id": { "$oid": "606b4cfbcd83be7518b958db" }, "color": "purple", "qty": 8 }
{ "_id": { "$oid": "606b4cfbcd83be7518b958dc" }, "color": "blue", "qty": 0 }
{ "_id": { "$oid": "606b4cfbcd83be7518b958dd" }, "color": "white", "qty": 0 }
{ "_id": { "$oid": "606b4cfbcd83be7518b958de" }, "color": "yellow", "qty": 6 }
{ "_id": { "$oid": "606b4cfbcd83be7518b958df" }, "color": "pink", "qty": 0 }
{ "_id": { "$oid": "606b4cfbcd83be7518b958e0" }, "color": "green", "qty": 0 }
{ "_id": { "$oid": "606b4cfbcd83be7518b958e1" }, "color": "black", "qty": 8 }
{ "_id": { "$oid": "606b4cfc1601f9443b5d6978" }, "color": "orange", "qty": 10 }]

注意

不包括UpdateOptions将导致集合无变化。

val filter = Filters.eq(PaintOrder::color.name, "orange")
val update = Updates.inc(PaintOrder::qty.name, 10)
val results = collection.updateOne(filter, update)
println(results)
AcknowledgedUpdateResult{ matchedCount=0, modifiedCount=0, upsertedId=null }

有关本节中提到的方法和类的更多信息,请参阅以下API文档

  • UpdateOptions.upsert()

  • ReplaceOptions.upsert()

下一页

MongoDB Kotlin Driver