简体   繁体   English

使用MongoDB Java 3.0驱动程序批量Upsert

[英]Bulk Upsert with MongoDB Java 3.0 Driver

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 : 在早期版本的MongoDB Java驱动程序中,要运行查询并对结果执行无序批量upsert,我们所做的就是:

BulkWriteOperation bulk = dbCollection.initializeUnorderedBulkOperation();
    bulk.find(searchQuery).upsert().update(new BasicDBObject("$set", getDbObjectModel()));

But in version 3, with the introduction of Bson Document support and MongoCollection.bulkWrite() method how can this be done? 但是在版本3中,随着Bson Document支持和MongoCollection.bulkWrite()方法的引入,如何才能做到这一点?

I tried this : 我试过这个:

List<WriteModel<Document>> documentList = new ArrayList<>();

collection.bulkWrite(documentList, new BulkWriteOptions().ordered(false));

but, I need the upsert functionality. 但是,我需要upsert功能。

Thanks. 谢谢。

You can still use all of the functionality, it's just that BulkWrites now have a different syntax: 您仍然可以使用所有功能,只是BulkWrites现在有不同的语法:

    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);

So you use the UpdateOneModel ( or for many if you want ) and set the UpdateOptions as the third argument to the constructor. 因此,您可以使用UpdateOneModel (如果需要,可以使用UpdateOneModel ),并将UpdateOptions设置为构造函数的第三个参数。

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. 我猜这是改变的主要原因。

Here is the example using latest APIs.. 以下是使用最新API的示例..

for (Long entityId : entityIDs) {

    //Finder doc
    Document filterDocument = new Document();
    filterDocument.append("_id", entityId);

    //Update doc
    Document updateDocument = new Document();
    Document setDocument = new Document();
    setDocument.append("name", "xyz");
    setDocument.append("role", "abc");

    updateDocument.append("$set", setDocument);

    //Update option
    UpdateOptions updateOptions = new UpdateOptions();
    updateOptions.upsert(true); //if true, will create a new doc in case of unmatched find
    updateOptions.bypassDocumentValidation(true); //set true/false

    //Prepare list of Updates
    updateDocuments.add(
            new UpdateOneModel<Document>(
                    filterDocument,
                    updateDocument,
                    updateOptions));

}

//Bulk write options
BulkWriteOptions bulkWriteOptions = new BulkWriteOptions();
bulkWriteOptions.ordered(false);
bulkWriteOptions.bypassDocumentValidation(true);

MongoCollection<Document> mongoCollection = mongoDB.getCollection("myCollection");

BulkWriteResult bulkWriteResult = null;
try {
    //Perform bulk update
    bulkWriteResult = mongoCollection.bulkWrite(updateDocuments,
            bulkWriteOptions);
} catch (BulkWriteException e) {
    //Handle bulkwrite exception
    List<BulkWriteError> bulkWriteErrors = e.getWriteErrors();
    for (BulkWriteError bulkWriteError : bulkWriteErrors) {
        int failedIndex = bulkWriteError.getIndex();
        Long failedEntityId = entityIDs.get(failedIndex);
        System.out.println("Failed record: " + failedEntityId);
        //handle rollback
    }
}

int rowsUpdated = bulkWriteResult.getModifiedCount();

Details at: http://ashutosh-srivastav-mongodb.blogspot.in/2017/09/mongodb-bulkwrite-java-api.html 详细信息: http//ashutosh-srivastav-mongodb.blogspot.in/2017/09/mongodb-bulkwrite-java-api.html

If you want something findAndModifyElseCreate(); 如果你想要一些findAndModifyElseCreate(); That means if the document exist then update it else create it and insert the data then PLEASE FOLLOW THIS. 这意味着如果文档存在然后更新它,则创建它并插入数据然后请关注此事。

BasicDBObject insertInCaseDocumentNotFound = new BasicDBObject();


insertInCaseDocumentNotFound.put("field1", "value1");
insertInCaseDocumentNotFound.put("date", new Date());


MongoCollection<BasicDBObject> table = db.getCollection("collectionName",BasicDBObject.class);

BasicDBObject updateObject = new BasicDBObject();

updateObject.append("$setOnInsert", new BasicDBObject());
updateObject.append("$set", new BasicDBObject("date",new Date());

List<WriteModel<BasicDBObject>> updates = Arrays.<WriteModel<BasicDBObject>> asList(
                new UpdateOneModel<BasicDBObject>(new BasicDBObject("search_name", alert.getString("search_name")), // query for which we need to apply

                        updateObject, // update the document in case it is found
                        new UpdateOptions().upsert(true) // upsert to insert new data in case document is not found
        ));
table.bulkWrite(updates);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM