使用MongoDB Java 3.0驱动程序批量Upsert [英] Bulk Upsert with MongoDB Java 3.0 Driver
问题描述
在MongoDB Java驱动程序的早期版本中,要运行查询并对结果执行无序批量upsert,我们所做的就是:
In the earlier versions of MongoDB Java drivers , to run a query and do unordered bulk upsert on the result all we had do was :
BulkWriteOperation bulk = dbCollection.initializeUnorderedBulkOperation();
bulk.find(searchQuery).upsert().update(new BasicDBObject("$set", getDbObjectModel()));
但是在版本3中,随着Bson Document支持和MongoCollection.bulkWrite()方法的引入怎么能这样做了吗?
But in version 3, with the introduction of Bson Document support and MongoCollection.bulkWrite() method how can this be done?
我试过这个:
List<WriteModel<Document>> documentList = new ArrayList<>();
collection.bulkWrite(documentList, new BulkWriteOptions().ordered(false));
但是,我需要upsert功能。
but, I need the upsert functionality.
谢谢。
推荐答案
您仍然可以使用所有功能,只是BulkWrites现在有不同的语法:
You can still use all of the functionality, it's just that BulkWrites now have a different syntax:
MongoCollection<Document> collection = db.getCollection("sample");
List<WriteModel<Document>> updates = Arrays.<WriteModel<Document>>asList(
new UpdateOneModel<Document>(
new Document(), // find part
new Document("$set",1), // update part
new UpdateOptions().upsert(true) // options like upsert
)
);
BulkWriteResult bulkWriteResult = collection.bulkWrite(updates);
所以你使用 UpdateOneModel
(如果需要,可以为很多人设置)并设置< a href =http://api.mongodb.org/java/current/com/mongodb/client/model/UpdateOptions.html =noreferrer> UpdateOptions
作为构造函数的第三个参数。
So you use the UpdateOneModel
( or for many if you want ) and set the UpdateOptions
as the third argument to the constructor.
需要习惯,但它基本上只是构建列表,其语法与其他地方相同。我猜这是改变的主要原因。
Takes some getting used to, but it's basically just building "Lists" with all the same syntax as elsewhere. I guess that's the main reason for the change.
这篇关于使用MongoDB Java 3.0驱动程序批量Upsert的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!