简体   繁体   中英

mongodb Java Driver - $group with multiple fields

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?

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))
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM