3

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
  • The Compass generated Java code for aggregation's group stage looks correct - there is no problem with it. Commented Jun 6, 2020 at 5:30

1 Answer 1

3

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))
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.