mongodb Java Driver - $group with multiple fields

六眼飞鱼酱① 提交于 2020-06-29 04:33:33

问题


My goal is to create a pipeline using the aggregation framework to group my data and then use this pipeline with the java driver. MongoDB v4.0.3

I created the following pipeline using MongoDB Compass (reduced to the important part):

[{
    $group: {
        _id: {
            year: '$year',
            month: '$month',
            day: '$day',
            prodName: '$prodName',
            actionName: '$actionName'
        },
        actionCount: {
            $sum: 1
        }
    }
  }
]

This resulted in the following (generated) Java code:

collectionName.aggregate(
  Arrays.asList(
    group(and(eq("year", "$year"),
              eq("month", "$month"),
              eq("day", "$day"),
              eq("prodName", "$prodName"),
              eq("actionName", "$actionName")),
         sum("actionCount", 1))
);

The data before the $group stage in the collection looks like this:

{
 year: 2020,
 month: 01,
 day: 01,
 prodName: "productXY",
 actionName: "actionXY"
}

The $group stage should return the following data structure:

{
  _id: {
    year: 2020,
    month: 01,
    day: 01,
    prodName: "productXY",
    actionName: "actionXY"
  },
  actionCount: 50
}

The Problem

Mongo Compass previews the result of the stage as expected, but the results of the stage using the java driver are very different. It only returns 1 Document (instead of 20 expected) and only returns the field actionCount.

The Question

How do I have to change the java code to create the desired pipeline stage?


回答1:


I found the solution. I needed to change the and operator to a Projections.fields operator. I still don't know why. Maybe someon else can elaborate about that.

So the working query looks like this:

collectionName.aggregate(
  Arrays.asList(
    group(fields(eq("year", "$year"),
                 eq("month", "$month"),
                 eq("day", "$day"),
                 eq("prodName", "$prodName"),
                 eq("actionName", "$actionName")),
         sum("actionCount", 1))
);


来源:https://stackoverflow.com/questions/62225054/mongodb-java-driver-group-with-multiple-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!