【问题标题】:Spring data mongodb group aggregation objectSpring数据MongoDB组聚合对象
【发布时间】:2017-07-14 10:54:03
【问题描述】:

我正在尝试根据使用 spring 数据和 mongodb 的查询对对象进行分组,这就是我现在所做的:

MongoDB 数据:

{
 "_id" : ObjectId("58af31feef34aa45476d2be9"),
 "_class" : "my.model.Image",
 "file" : "0006000.jpg",
 "number" : "123",
 "mkdius" : "Fiscalization 432",
 "status" : "UNCOMPLETED",
 "createdAt" : ISODate("2017-02-23T16:03:26.612-03:00")
},
{
 "_id" : ObjectId("58af31feef34aa45476d2bf3"),
 "_class" : "my.model.Image",
 "file" : "9781.jpg",
 "number" : "987",
 "mkdius" : "Fiscalization 432",
 "status" : "UNCOMPLETED",
 "createdAt" : ISODate("2017-02-23 16:03:26.866-03:00")
},
{
 "_id" : ObjectId("58af31feef34aa45476d2bea"),
 "_class" : "my.model.Image",
 "file" : "00016.jpg",
 "number" : "432",
 "mkdius" : "Fiscalization 4154",
 "status" : "UNCOMPLETED",
 "createdAt" : ISODate("2017-02-23T16:03:26.835-03:00")
}

我的聚合函数:

Aggregation aggregation = Aggregation.newAggregation(
    Aggregation.match(Criteria.where("status").is(Status.UNCOMPLETED)), // Match
    Aggregation.group("mkdius").last("mkdius").as("mkdius").addToSet("id").as("imgsId"), // Grouping
    Aggregation.project("imgsId").and("cd").previousOperation()); // Projecting

AggregationResults<InitApp.result> groupResults = this.mongoTemplate.aggregate(aggregation, Image.class, InitApp.result.class);

groupResults.getMappedResults().forEach(System.out::println);

我得到的结果:

InitApp.result(mkdius=Fiscalization 432, imgIds=[58af31feef34aa45476d2be9,58af31feef34aa45476d2bf3]

InitApp.result(mkdius=Fiscalization 4154, imgIds=[58af31feef34aa45476d2bea]

我的期望:

InitApp.result(mkdius=Fiscalization 432, imgs=[{
 "_id" : ObjectId("58af31feef34aa45476d2be9"),
 "_class" : "my.model.Image",
 "file" : "0006000.jpg",
 "number" : "123",
 "mkdius" : "Fiscalization 432",
 "status" : "UNCOMPLETED",
 "createdAt" : ISODate("2017-02-23T16:03:26.612-03:00")
},{
 "_id" : ObjectId("58af31feef34aa45476d2bf3"),
 "_class" : "my.model.Image",
 "file" : "9781.jpg",
 "number" : "987",
 "mkdius" : "Fiscalization 432",
 "status" : "UNCOMPLETED",
 "createdAt" : ISODate("2017-02-23 16:03:26.866-03:00")
}]

InitApp.result(cd=Fiscalization 4154, imgs=[{
 "_id" : ObjectId("58af31feef34aa45476d2bea"),
 "_class" : "my.model.Image",
 "file" : "00016.jpg",
 "number" : "432",
 "mkdius" : "Fiscalization 4154",
 "status" : "UNCOMPLETED",
 "createdAt" : ISODate("2017-02-23T16:03:26.835-03:00")
}]

我不知道是否可以这样做,聚合数据并将当前对象放入响应中。

谢谢。

【问题讨论】:

    标签: spring mongodb spring-boot spring-data


    【解决方案1】:

    将您的 $group 舞台替换为

    Aggregation.group("mkdius").last("mkdius").as("mkdius").push("$$ROOT").as("imgsId"),
    

    $$ROOT 将推送整个文档。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-21
      • 1970-01-01
      • 1970-01-01
      • 2021-11-03
      • 2020-07-27
      • 1970-01-01
      • 2020-08-20
      • 2020-07-02
      相关资源
      最近更新 更多