4

Can any one help me convert this mongoDB aggregation to spring data mongo?

I am trying to get list of un-reminded attendee's email in each invitation document.

Got it working in mongo shell, but need to do it in Spring data mongo.

My shell query

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"}
        }
    }
]

)

This is what I came up with, as you can see, it's working not as expected at a project and group operation of the pipeline. Generated query is given below.

Aggregation Object creation

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

It creates the following query

Query generated by Aggregation object

{ "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"}}}]}

I don't know the correct way to use Aggregation Group in spring data mongo.

Could someone help me please or provide link to group aggregation with $push etc?

Shabin Muhammed
  • 1,092
  • 2
  • 18
  • 29
  • I had an issue similar [how-to-aggregate-in-spring-data-mongo-db-a-nested-object-and-avoid-a-propertyException](https://stackoverflow.com/questions/57910383/how-to-aggregate-in-spring-data-mongo-db-a-nested-object-and-avoid-a-propertyref/57913900#57913900). but it turned out to be a different solution – Sylhare Sep 12 '19 at 20:18

1 Answers1

14

Correct Syntax would be:

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

Reference: http://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongo.group

Prakash Bhagat
  • 1,406
  • 16
  • 30