单操作插入或更新
本页面内容
概述
在本指南中,您可以学习如何使用 MongoDB Java 驱动程序执行 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 }
店铺收到了一批新货,需要更新库存。这批货物的第一项是十罐橙色油漆。
要更新库存,查询 paint_inventory
集合中颜色为 "orange"
的文档,指定更新 increment
qty
字段增加 10
,并指定 true
给 UpdateOptions.upsert()
// Creates a filter and update document to increment the matching document's "qty" value Bson filter = Filters.eq("color", "orange"); Bson update = Updates.inc("qty", 10); // Updates the matching document or inserts a document if none match the query filter UpdateOptions options = new UpdateOptions().upsert(true); System.out.println(collection.updateOne(filter, update, options));
该方法返回
AcknowledgedUpdateResult{ matchedCount=0, modifiedCount=0, upsertedId=BsonObjectId{ value=606b4cfc1601f9443b5d6978 }}
此 AcknowledgedUpdateResult
告诉我们
没有文档匹配我们的查询过滤器
我们集合中的文档没有修改
一个具有
_id
为606b4cfc1601f9443b5d6978
的文档被 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 } { "_id": { "$oid": "606b4cfc1601f9443b5d6978" }, "color": "orange", "qty": 10 }]
注意
不包括 UpdateOptions
会导致集合没有任何变化。
Bson filter = Filters.eq("color", "orange"); Bson update = Updates.inc("qty", 10); System.out.println(collection.updateOne(filter, update));
该方法返回
AcknowledgedUpdateResult{ matchedCount=0, modifiedCount=0, upsertedId=null }
有关本节中提到的方法和类的更多信息,请参阅以下API文档