Spring / Java Mongo查询:如何在分组/投影时将多个文档中的字段值作为数组添加

时间:2019-03-25 14:39:50

标签: mongodb mongodb-query aggregation-framework spring-data-mongodb

我的记录如下:

 {
    domain: 'ABC',
    technology: 'Java',
    appName: 'app1',
    environment: 'Dev',
    version : '1_1',

    domain: 'ABC',
    technology: 'Java',
    appName: 'app1',
    environment: 'SQA',
    version : '1_1',

    domain: 'ABC',
    technology: 'Java',
    appName: 'app2',
    environment: 'Dev',
    version : '1_1',

    domain: 'DEF',
    technology: '.NET',
    appName: 'app3',
    environment: 'SQA',
    version: '1_3'

    }

最终结果是获取按域和技术分组的应用程序环境和版本列表(这两者之间是1到1的映射)。将输入环境/域/技术。如果该环境不存在,那么我仍然想显示结果,版本为N / A。

[
      {
      "domain": "ABC",
      "technology": "Java",
      "apps": [      
      {
         "appName": "app1",
         "environment": ["Dev","SQA"],
         "version": ["1_1", "1_1"],
         "hasVersionDiff": false
      }, 
      {
         "appName": "app2",
         "environment": ["Dev","SQA"],
         "version": ["1_1", "N/A"],
         "hasVersionDiff": true }]
      },
      {
      "domain": "DEF",
      "technology": ".NET",
      "apps": [      {
         "appName": "app3",
         "environment": ["Dev","SQA"],
         "version": ["N/A", "1_1"],
         "hasVersionDiff": true
      }
      ]
   }]

到目前为止,我已经尝试过以下方法:

Aggregation agg = Aggregation.newAggregation(
                    Aggregation.match(cr),

Aggregation.group("domain").first("technology").as("technology")
                    .addToSet(new BasicDBObject() {
                                  {
                                      put("technology", "$technology");
                                      put("domain", "$domain");
                                      put("environment","$environment");
                                      put("version", "$version");
                                      put("appName", "$appName");
                                  }
                              }
                    ).as("apps"));

但这给了我如下结果,对于每个应用程序,它向我显示了每个环境的两个差异记录,我也不知道如何为它们应用hasVersionDiff值:

[

      {
      "domain": "ABC",
      "technology": "Java",
      "apps": [      {
         "appName": "app1",
         "environment": ["DEV"],
         "version": ["1_1"],
         "hasVersionDiff": false 
      },  {
         "appName": "app1",
         "environment": ["SQA"],
         "version": ["1_1"],
         "hasVersionDiff": false 
      } 
]
   }

等等。

我的模型课如下: CompareResult具有域,技术和ArrayList应用程序 应用具有appName,环境列表,版本列表和hasVersionDiff布尔值。

0 个答案:

没有答案