簡體   English   中英

MongoDB Java驅動程序性能降低

[英]Mongodb java driver slow performance

我正在開發一個項目,該項目實現為front:VUE.JS和back:Java servlet(tomcat)。 我的servlet在具有數千種產品的mongoDB數據庫上執行請求。 我是mongodb查詢的新手 )。

對我來說,問題是我的servlet需要很多時間來響應數據數組。

我需要一些建議來加快查詢速度,並加快servlet進程以將數據發送到前端。

  1. 首先,我想知道在mongodb中使用這樣的查詢是否有效(這是具有很多查詢的查詢示例,因為我必須從許多集合中獲取數據):

     db.getCollection('collection_name').aggregate([ { "$match":{ "_id": ObjectId("xxxxxxxxxxxxxxxxx") } }, { "$lookup":{ "from":"collection_name", "localField":"id", "foreignField":"id", "as":"trans" } }, { "$unwind":"$trans" }, { "$lookup":{ "from":"collection_name", "localField":"trans.id", "foreignField":"trans_id", "as":"orders" } }, { "$unwind":"$orders" }, { "$match":{ "$and":[ { "orders.status":"status_state" } ] } }, { "$unwind":"$orders.products" }, { "$lookup":{ "from":"collection_name", "localField":"orders.products.id", "foreignField":"id", "as":"detailsProducts" } }, { "$unwind":"$detailsProducts" }, { "$unwind":"$detailsProducts.products" }, { "$project":{ "_id":1, "orders":1, "detailsProducts": 1 } } ]) 
  2. 正如我所說的,在第二秒中,我的java servlet需要花費很多時間來執行數據處理,在定義了聚合之后,我執行了循環操作以將數據推入json數組中,如下所示:

     // Define json array JSONArray array = new JSONArray(); // Get collection AggregateIterable<Document> myCollection = MongoDB.getCollection("coll_name").aggregate(...); // Going through all documents (thousands of document) for (Document orderDocument : orderCollection) { // Get all products and they references arrays.put(new JSONObject(orderDocument.toJson())); } // AFTER THE END OF LOOP, MY SERVLET SEND THE ARRAY TO THE FRONT 

注意:我使用mongodb java driver 3.5(我同時嘗試:核心驅動程序和異步驅動器)

我想得到一些建議,以加快治療速度並優化我的要求。

構建具有數千個元素的JSONArray不能很好地擴展。 最好將JSON直接流回客戶端。 因此,假設這在合理的時間內返回:

// Get collection
AggregateIterable<Document> myCollection =
    MongoDB.getCollection("coll_name").aggregate(...);

那么類似以下的內容應該會大大改善:

import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.bson.Document;
import org.bson.codecs.DocumentCodec;
import org.bson.codecs.Encoder;
import org.bson.codecs.EncoderContext;
import org.bson.json.JsonWriter;
...
public void writeAsJsonTo(AggregateIterable<Document> orderCollection,
        HttpServletResponse httpServletResponse) throws IOException {
    final Encoder<Document> encoder = new DocumentCodec();
    final JsonWriter jsonWriter =
        new JsonWriter(httpServletResponse.getWriter());
    final EncoderContext encoderContext = EncoderContext.builder()
        .isEncodingCollectibleDocument(true).build();

    jsonWriter.writeStartDocument();
    jsonWriter.writeStartArray("orders");
    // Going through all documents (thousands of document)
    for (Document orderDocument : orderCollection) {
        encoder.encode(jsonWriter, orderDocument, encoderContext);
    }
    jsonWriter.writeEndArray();
    jsonWriter.writeEndDocument();
}

暫無
暫無

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

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