Mongo聚合与Java的循环和性能对比

时间:2019-12-28 05:58:29

标签: mongodb aggregation-framework spring-mongodb

我存储了以下mongo文档

{
 "Field1": "ABC",
 "Field2": [
    { "Field3": "ABC1","Field4": [ {"id": "123" }, { "id" : "234" }, { "id":"345" }] }, 
    { "Field3": "ABC2","Field4": [ {"id": "123" }, { "id" : "234" }, { "id":"345" }] }, 
    { "Field3": "ABC3","Field4": [{ "id":"345" }] },  
    ]
}

从上面开始,我想获取ID为“ 123”的子文档

即。

{ 
    "Field3" : "ABC1",
    "Field4" : [ { "id": "123"} ]
} ,
{
    "Field3" : "ABC2",
    "Field4" : [ { "id": "123"} ]
}
1. Java way  
    A. use Mongo find method to get the ABC document from Mongo DB
    B. for Loop to Iterate the Field2 Json Array
    C. Again for Loop to Iterate over Field4 Json Array
    D. Inside the nested for loop I've if condition to Match id value to "123"
    E. Store the Matching subdocument into List 

2. Mongo Way
   A. Use Aggregation query to get the desired output from DB.No Loops and conditions in the Java side. 
   B. Aggregation Query below stages
    I)  $Match - match the ABC document
    II) $unwind - Field2
    III) $unwind - Field4
    IV) $match - Match the with id ( value is "123")
    V) $group - group the document  based on Field3 (based on "ABC1" or "ABC2") 
    VI) execute aggregation and return results

双方都工作良好,并返回了适当的结果。
问题是哪个更好,为什么?我在宁静的服务get方法中使用了聚合,因此并行执行聚合查询1000次或更多次会导致性能问题吗?

2 个答案:

答案 0 :(得分:1)

使用Aggregation,整个查询在MongoDB服务器上作为单个进程执行-应用程序将从服务器获取结果游标。

使用Java程序,您还可以从数据库服务器获取光标,作为对应用程序中处理的输入。来自服务器的响应游标将是更大的数据集,并且将使用更多的网络带宽。然后在应用程序中进行处理,这增加了更多步骤来完成查询。

我认为聚合选项是一个更好的选择-因为所有处理(初始匹配和过滤数组)都在数据库服务器上作为单个进程进行。

此外,请注意,您可以高效地完成已发布的聚合查询步骤。您可以分两个阶段进行这些操作,而不必进行多个阶段(2、3、4和5)-在外部数组上使用$project$map,然后{ {1}}在内部数组上,然后 $filter在外部数组上。

聚合:

$filter

答案 1 :(得分:0)

第二种方法可能更好,因为它从数据存储区返回的结果较小;在电线上切碎比特很昂贵。

相关问题