2015-07-17 16 views
6

Trong các phiên bản trước của trình điều khiển MongoDB Java, để chạy một truy vấn và làm upsert số lượng lớn có thứ tự vào kết quả tất cả chúng tôi đã làm là:Upsert Bulk với MongoDB Java 3.0 driver

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

Nhưng trong phiên bản 3, với sự giới thiệu của Bson Document support và phương thức MongoCollection.bulkWrite() làm thế nào điều này có thể được thực hiện?

Tôi cố gắng này:

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

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

nhưng, tôi cần các chức năng upsert.

Cảm ơn.

Trả lời

16

Bạn vẫn có thể sử dụng tất cả các chức năng, nó chỉ là BulkWrites bây giờ có một cú pháp khác nhau:

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

Vì vậy, bạn sử dụng UpdateOneModel (hoặc đối với nhiều người nếu bạn muốn) và thiết lập UpdateOptions như thứ ba đối số cho hàm tạo.

Làm cho một số việc quen thuộc, nhưng về cơ bản chỉ cần xây dựng "Danh sách" với tất cả cú pháp giống như ở nơi khác. Tôi đoán đó là lý do chính cho sự thay đổi.

+0

Có bất kỳ tài liệu chính thức cho những thay đổi trong trình điều khiển? – void

+0

@AswinJoseRoy Ví dụ? Không may là tất cả các ví dụ về tài liệu (ít nhất là chính thức) dường như tuân theo các lớp học cũ hơn. Đây là cùng một câu chuyện cho hầu hết các trình điều khiển ngôn ngữ. Đối với tôi, tôi tìm thấy thêm thông tin bằng cách tìm kiếm "GitHub" cho "kiểm tra" và như vậy trong kho lưu trữ. Nhưng một lần nữa, một số "kiểm tra" sử dụng các lớp cũ "vẫn". Vì vậy, một số là thử và sai. Sẽ trở nên tốt hơn và các câu hỏi như của bạn thực sự hữu ích. –

+0

Khi chèn dữ liệu ở lần đầu tiên, cả hai được chènCount và ModifiedCount của bulkWriteResult đều bằng không, đó có phải là lỗi không? – inza9hi

0

Nếu bạn muốn một cái gì đó findAndModifyElseCreate(); Điều đó có nghĩa là nếu tài liệu tồn tại sau đó cập nhật nó khác tạo và chèn dữ liệu rồi XIN VUI LÒNG THEO D THI NÀY.

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

Dưới đây là ví dụ sử dụng API mới nhất ..

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

chi tiết tại địa chỉ: http://ashutosh-srivastav-mongodb.blogspot.in/2017/09/mongodb-bulkwrite-java-api.html

+0

Tính năng này hoạt động đối với phiên bản trình điều khiển mong muốn Java mới nhất: 3.6.0-rc0 trên repo trung tâm. –

Các vấn đề liên quan