单次操作插入或更新
概述
在本指南中,您将学习如何使用 MongoDB Kotlin 驱动程序执行 upsert 操作。
应用程序使用插入和更新操作来存储和修改数据。有时,您需要根据文档是否存在来选择插入或更新。MongoDB 通过一个upsert
选项来简化我们的这个决策。
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( val id: ObjectId = ObjectId(), val qty: Int, val color: String )
商店收到了一批新货并需要更新库存。这批货的第一件是十罐橙色油漆。
为了更新库存,查询paint_inventory
集合,其中color
为"orange"
,指定更新操作increment
qty
字段增加10
,并指定true
到UpdateOptions.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
告诉我们
没有文档匹配我们的查询过滤器
我们的集合中没有文档被修改
一个
_id
为606b4cfc1601f9443b5d6978
的文档被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文档