繁体   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