如何使用 MongoTemplate 在 MongoDB 中的嵌套文档上应用分组? [英] How to apply group by on nested document in MongoDB using MongoTemplate?

查看:20
本文介绍了如何使用 MongoTemplate 在 MongoDB 中的嵌套文档上应用分组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

db.students.aggregate([
  { $unwind: "$details" },
  {
    $group: {
      _id: {
        sid: "$details.student._id",
        statuscode: "$details.studentStatus.statusCode"
      },
      total: { $sum: 1 }
    }
  }
]);

查询工作正常,需要转换成mongo模板.

The query is working fine and need to convert into mongo template.

示例文档:

{
        "_id" : 59,
        "details" : [
                {
                        "student" : {
                                "_id" : "5d3145a8523a2e602e5e0200"
                        },
                        "studentStatus" : {
                                "statusCode" : 1
                        }
                }
        ]
}

推荐答案

给定聚合的 Spring Data MongoTemplate 代码如下.

The Spring Data MongoTemplate code for the given aggregation is as follows.

请注意,我在 group 之前添加了一个 project 阶段.这个项目是必需的;如果在 group 阶段直接使用嵌套字段(details.student._id"和details.studentStatus.statusCode"),则会出现错误FieldPath 字段名称可能不包含'.'." 并且无法解析(仅当您在分组中使用多个字段时才会发生这种情况).

Note that I have added a project stage before the group. This project is required; if the nested fields ("details.student._id" and "details.studentStatus.statusCode") are used directly within the group stage there are errors "FieldPath field names may not contain '.'." and could not be resolved (and this only happens when you use more than one field in the grouping).

结果与您提供的聚合结果相同.我在 Java 8 中使用了最新的 Spring 和 MongoDB 驱动程序.

The result is same as that of the aggregation you have provided. I have used the latest of Spring and MongoDB drivers with Java 8.

MongoOperations mongoOps = new MongoTemplate(MongoClients.create(), "spr_test");

Aggregation agg = newAggregation(
                                unwind("details"),    
                                project("_id")
                                    .and("details.student._id").as("sid")
                                    .and("details.studentStatus.statusCode").as("statuscode"),
                                group("sid", "statuscode")
                                    .count().as("total")
);

AggregationResults<Document> aggResults = mongoOps.aggregate(agg, "students", Document.class);
aggResults.forEach(System.out::println);

这篇关于如何使用 MongoTemplate 在 MongoDB 中的嵌套文档上应用分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆