何使用MongoTemplate在MongoDB中的嵌套文档上应

何使用MongoTemplate在MongoDB中的嵌套文档上应

本文介绍了如何使用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中的嵌套文档上应用分组依据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 22:00