下面是使用最新 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();
详情请见: https://ashutosh-srivastav-mongodb.blogspot.in/2017/09/mongodb-bulkwrite-java-api.html