How to apply group by on multiple nested document in MongoDB using MongoTemplate

自古美人都是妖i 提交于 2021-02-11 08:49:31

问题


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

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

Sample document:

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

回答1:


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

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

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


来源:https://stackoverflow.com/questions/59639379/how-to-apply-group-by-on-multiple-nested-document-in-mongodb-using-mongotemplate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!