从MongoDb聚合查询创建Spring Data聚合

4

有人可以帮我将这个MongoDB聚合查询转换为Spring Data MongoDB吗?

我正在尝试获取每个邀请文档中未提醒参与者的电子邮件列表。

在Mongo shell中可以正常工作,但需要在Spring data mongo中执行。

我的shell查询:

db.invitation.aggregate(
[ 
    { $match : {_id : {$in : [id1,id2,...]}}},
    { $unwind : "$attendees" },
    { $match : { "attendees.reminded" : false}},
    { $project : {_id : 1,"attendees.contact.email" : 1}},
    { $group : {
            _id : "$_id",
            emails : { $push : "$attendees.contact.email"}
        }
    }
]

这就是我的想法,正如您所看到的,在管道的项目和组操作中,它的工作结果并非如预期。 生成的查询如下所示。

创建聚合对象

Aggregation aggregation = newAggregation(
        match(Criteria.where("_id").in(ids)),
        unwind("$attendees"),
        match(Criteria.where("attendees.reminded").is(false)),
        project("_id","attendees.contact.email"),
        group().push("_id").as("_id").push("attendees.contact.email").as("emails")
    );

它创建以下查询

通过聚合对象生成的查询

{ "aggregate" : "__collection__" , "pipeline" : [
{ "$match" : { "_id" : { "$in" : [id1,id2,...]}}},
{ "$unwind" : "$attendees"},
{ "$match" : { "attendees.reminded" : false}},
{ "$project" : { "_id" : 1 , "contact.email" : "$attendees.contact.email"}},
{ "$group" : { "_id" : { "$push" : "$_id"}, "emails" : { "$push" : "$attendees.contact.email"}}}]}

我不知道在Spring Data Mongo中正确使用聚合组的方法。

有人可以帮帮我,或者提供链接以使用类似于$push的聚合组吗?


我遇到了一个类似的问题 如何在Spring Data Mongo DB中聚合嵌套对象并避免PropertyException,但最终发现需要使用不同的解决方案。 - Sylhare
1个回答

14

正确的语法应该是:

Aggregation aggregation = newAggregation(
        match(Criteria.where("_id").in(ids)),
        unwind("$attendees"),
        match(Criteria.where("attendees.reminded").is(false)),
        project("_id","attendees.contact.email"),
        group("_id").push("attendees.contact.email").as("emails")
    );

参考资料:http://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongo.group

该链接介绍了Spring Data MongoDB中的group操作。通过使用group操作,可以将集合中的文档分组并对其进行聚合计算,例如求和、计数等。在group操作中,需要指定分组字段和聚合函数。此外,还可以使用条件过滤器来进一步限制分组的文档范围。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接