我的目标是使用聚合框架创建一个管道来对我的数据进行分组,然后将此管道与 java 驱动程序一起使用.MongoDB v4.0.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
我使用 MongoDB Compass 创建了以下管道(简化为重要部分):
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 } } } ]这导致了以下(生成的)Java 代码:
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)) );集合中$group阶段之前的数据如下所示:
The data before the $group stage in the collection looks like this:
{ year: 2020, month: 01, day: 01, prodName: "productXY", actionName: "actionXY" }$group 阶段应该返回以下数据结构:
The $group stage should return the following data structure:
{ _id: { year: 2020, month: 01, day: 01, prodName: "productXY", actionName: "actionXY" }, actionCount: 50 }问题
Mongo Compass 预览阶段的结果符合预期,但是使用java驱动的阶段的结果有很大的不同.它只返回 1 个文档(而不是预期的 20 个)并且只返回字段 actionCount.
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.
问题
如何更改 java 代码以创建所需的管道阶段?
How do I have to change the java code to create the desired pipeline stage?
推荐答案我找到了解决方案.我需要将 and 运算符更改为 Projections.fields 运算符.我仍然不知道为什么.也许其他人可以详细说明这一点.
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)) );更多推荐
mongodb Java 驱动程序
发布评论