quiros quiros - 1 year ago 122
Java Question

MongoDB $aggregate $push in Java Spring Data

I have a mongo aggregate group query:

$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(

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?

Answer Source

Note: MongoDB versiĆ³n 2.6 - 3.0 (compatible Java driver)

I've extended org.springframework.data.mongodb.core.aggregation.AggregationOperation class to implement custom toDBObject method:

public class GenericAggregationOperation implements AggregationOperation {

    private String operator;
    private DBObject query;

     * Default constructor.
     * @param operator MongoDB operator ($group, $sort, $project, etc..)
     * @param query MongoDB aggregation query step string
    public GenericAggregationOperation(String operator, String query) {
        this(operator, (DBObject) JSON.parse(query));

     * Default constructor.
     * @param operator MongoDB operator ($group, $sort, $project, etc..)
     * @param query MongoDB aggregation query step DBObject
    public GenericAggregationOperation(String operator, DBObject query) {
        this.operator = operator;
        this.query    = query;

    public DBObject toDBObject(AggregationOperationContext context) {

        return new BasicDBObject(operator, query);


In your case, it would be:

List<AggregationOperation> list = new ArrayList<AggregationOperation>();
lista.add(new GenericAggregationOperation("$group", "{ \"_id\": \"$title\", \"versions\": { \"$push\": { \"version\":\"$version\", \"author\":\"$author\", \"dateAdded\":\"$dateAdded\"}} }"));

TypedAggregation<EpisodeIndexDto> agg = Aggregation.newAggregation(
    YourClassTitleVersion.class, list);
mongoOperations.aggregate(agg, YourClassTitleVersion.class,

Hope this helps you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download