在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 (如果需要,可以为很多人设置)并设置 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
发布评论