mongodb Java 驱动程序

编程入门 行业动态 更新时间:2024-10-22 10:56:08
本文介绍了mongodb Java 驱动程序 - 具有多个字段的 $group的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的目标是使用聚合框架创建一个管道来对我的数据进行分组,然后将此管道与 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 驱动程序

本文发布于:2023-11-22 19:29:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618719.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:驱动程序   mongodb   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!