簡體   English   中英

使用Java從MongoDB返回多個文檔

[英]Return multiple documents from MongoDB using Java

我已經在萬維網上搜索了幾個小時,但找不到解決我問題的可行方法:

很簡單:我想從MongoDB中搜索一組項目,然后返回所有文檔。

從RESTFul API角度來看: GET / items- 返回集合中的所有項目。 未排序

// NOT WORKING - STILL TRYING  
    public static String getItems() {

        StringBuilder items = new StringBuilder();
    MongoCursor<Document> cursor = itemCollection.find().iterator();
    try {

        while (cursor.hasNext()) {
            items.append(cursor.next().toJson());

        }

    } finally {
        cursor.close();
    }

    return items.toString();
    }

如您所見,我返回一個StringBuilder,因為我想將每個文檔連接成一個大塊。 但這返回為TEXT而不是JSON 見下文:

這是當讀取類型設置為JSON時
將JSON設置為讀取類型時

下面是當讀取類型設置為TEXT時,它創建了我需要的輸出,但它不是正確的格式。

將TEXT設置為讀取類型時

我不能將其作為文檔返回,然后使用方法: toJson() ,因為它只會返回最后一個條目。 我已經嘗試過使用列表,但是無法將其轉換為JSON文檔。 以上是我所需要的最接近的。

我希望這里的某個人和我一樣遇到同樣的問題,並且可以給我快速提示以解決我遇到的問題:-)。

您可以將JSON字符串收集在List ,並將該列表格式化為JSON數組字符串:

public static String getItems() {
    List<String> items = new ArrayList<>();
    MongoCursor<Document> cursor = itemCollection.find().iterator();
    try {
        while (cursor.hasNext()) {
            items.add(cursor.next().toJson());
        }
    } finally {
        cursor.close();
    }

    return "[" + String.join(", ", items) + "]";
}

您必須修改代碼以正確形成JSON對象的集合

    while (cursor.hasNext()) {
        items.append(cursor.next().toJson());

    }

正在為您構建下一個輸出:

{json object1}{json object2}...{json objectN}

當你需要

[{json object1},{json object2}, ... {json objectN}]

串聯JSON時,您錯過了[ ,]

根據Aleh Maksimovich的回答,我可以告訴您,通過更正每個文檔之間的逗號並將其包裝在文檔數組中,可以解決此問題。

這是解決方案的代碼:

/**
 * This method is used to retrieve all the items in the item collection
 * @return - A String which contains all the documents. 
 */
public static String getItems() {

    StringBuilder items = new StringBuilder();
    MongoCursor<Document> cursor = itemCollection.find().iterator();
    try {

        items.append("[");
        while (cursor.hasNext()) {

            items.append(cursor.next().toJson());
            if(cursor.hasNext()) {
                items.append(",");
            }
        }
        items.append("]");
    } finally {
        cursor.close();
    }

    return items.toString();
}

謝謝您的貢獻,祝您度過一個愉快的夜晚。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM