javaspringmongodbspring-data-mongodbspring-mongo

MongoDB $aggregate $push multiple fields in Java Spring Data


I have a mongo aggregate group query:

db.wizard.aggregate(
{
$group: {
    _id: "$title",
    versions: { $push: {version:"$version", author:"$author", dateAdded:"$dateAdded"}}
    }
})

I need this query in Java Spring-Data-MongoDB, my current solution looks like this:

    Aggregation agg = Aggregation.newAggregation(
            Aggregation.group("title").
                    push("version").as("versions")
    );

Problem is that i don't know how to add more fields to push method (version, author, dateAdded). Is it possible with Spring-Data-MongoDB?


Solution

  • You can directly pass the BasicDbObject to any of the aggregation pipeline stage.

    Aggregation agg = newAggregation(
                group("title").
                push(new BasicDBObject
                       ("version", "$version").append
                       ("author", "$author").append
                       ("dateAdded", "$dateAdded")).as("versions"));