2016-05-10 77 views
0

我是MongoDB的新手。因爲async API支持對數據庫的回調和非阻塞調用,所以有人建議使用MongoDB Async Java Driver API而不是Spring-Data/Mongo DB Driver API。雖然我正在瀏覽下面的鏈接,但我注意到了一些差異。使用MongoDB異步驅動程序獲取文檔列表到Java列表

異步驅動程序API:http://mongodb.github.io/mongo-java-driver/3.0/driver-async/reference/crud/ 同步驅動程序API:http://mongodb.github.io/mongo-java-driver/3.0/driver/reference/crud/

我關注的主要區別是,我們怎樣才能得到結果集文檔轉換成使用異步驅動程序API一個ArrayList/LinkedList的。異步API頁面給出了下面的代碼塊來遍歷結果,但不能給它們分配到我們選擇的名單:

// find documents 
collection.find().into(new ArrayList<Document>(), 
    new SingleResultCallback<List<Document>>() { 
     @Override 
     public void onResult(final List<Document> result, final Throwable t) { 
      System.out.println("Found Documents: #" + result.size()); 
     } 
    }); 

這將複製文件到新的ArrayList(進入方法的第一個參數),但是沒有辦法讓它恢復。

雖然sync api支持如下操作,它將所有結果文檔複製到一個數組列表中。

// find documents 
List<BasicDBObject> foundDocument = collection.find().into(new ArrayList<BasicDBObject>()); 

Async API是否仍在演變或我錯過了什麼?是否有任何可用的專用於異步驅動程序api的實用程序非常感謝。

最好的問候, 錢德拉。

回答

0

我終於實現了它:

public CompletableFuture<List<Document>> getMongoDocuments() throws InterruptedException, ExecutionException { 
    CompletableFuture<List<Document>> future = new CompletableFuture<>(); 
    List<Document> list = new ArrayList<>(); 

    collection.find().forEach((document) -> { 
     try { 
     list.add(document); 
     } catch (Exception e) { 
     LOGGER.error("Error while parsing document::" + document.toString(), e); 
     } 

    }, (final Void result, final Throwable t) -> { 
     future.complete(list); 
    }); 

    List<Document> resultList = future.get(); //Just for testing if everything is as planned 
    LOGGER.info("getHighResDocumentsByDriveSessionVinAndLogDate:: Count::" + resultList.size()); 
    return future; 
    } 

最好的問候, 錢德拉。

1

您可以通過在呼叫之外聲明列表來返回結果。

例如:

List<Document> docs = new ArrayList<>(); 
    collection.find().into(docs, 
    new SingleResultCallback<List<Document>>() { 
     @Override 
     public void onResult(final List<Document> result, final Throwable t) { 
      System.out.println("Found Documents: #" + result.size()); 
     } 
    }); 

由於這些操作都是異步的,你需要讓你的方法來等待,直到它被完成。

我更喜歡你去通過使用Java 8的CompletableFuture像下面這個鏈接

Getting list of Documents into Java List using Mongo DB Async Driver

+0

我試過這樣做,但我從來沒有得到結果,因爲它在檢索塊之外。最後能夠使用CompletableFutures做到這一點...請看我的答案。 – Mouli

相關問題