1

I'm trying to convert this javascript code into java code to be used in Spring Data:

proj3={"$project": {
        "comms" : 1,
        "same" : { "$eq" : ["$comms.i" , "$max"]},
    "max" : 1,
    "_id" : 1
     }
};

I cannot seem to figure it out.

I have tried this:

    BasicDBObject o3 = new BasicDBObject();
    o3.append("$eq", "[\"$comms.i\",\"$max\"]");
    Aggregation aggCount2 = newAggregation(project("comms", "max", "_id").andExpression("same", o3));
    logger.info(aggCount2.toString());

This is what is logged:

{ "$project" : { "comms" : 1 , "max" : 1 , "_id" : 1}}

I also read this thread: Spring Data MongoDB - $eq within $project support but the poster seemed to have given up and used the executeCommand option instead which is not the route I would like to go.

How can I get this code to work in java Spring Data Mongodb?

Community
  • 1
  • 1
Simon
  • 19,658
  • 27
  • 149
  • 217

1 Answers1

0

This is how I solved it, it might not be the most efficient way but it seem to work without too much code rewrite.

First, I looked at the answer in this thread: Aggregation Project Group By extracted day, month and year with Spring Data

Blakes Seven proposed that I use a special custom aggregationOperation class so that the aggregation code will take BasicDBObjects:

public class CustomGroupOperation implements AggregationOperation {
    private DBObject operation;

    public CustomGroupOperation (DBObject operation) {
        this.operation = operation;
    }

    @Override
    public DBObject toDBObject(AggregationOperationContext context) {
        return context.getMappedObject(operation);
    }
}

Next, you just format the project code you want into the BasicDBObject:

BasicDBList basicDBList = new BasicDBList();
basicDBList.add("$comms.i");
basicDBList.add("$max");

Aggregation aggCount2 = newAggregation(
        match(),
        project(),
        group(),
        new CustomGroupOperation(new BasicDBObject("$project",
                new BasicDBObject("comms", 1)
                        .append("max", 1)
                        .append("_id", 1)
                        .append("same", new BasicDBObject("$eq", basicDBList)))),
        match(),
        project(),
        group(),
        sort());

Print it out in the logger and you will see that the format for the javascript code is now correct.

{ "$project" : { "comms" : 1 , "max" : 1 , "_id" : 1 , "same" : { "$eq" : [ "$comms.i" , "$max"]}}}
Community
  • 1
  • 1
Simon
  • 19,658
  • 27
  • 149
  • 217