Search code examples
javaregexmongodbsubstr

How do I use the $substr expression in $project operator when using MongoDB 3.0 Java Driver aggregation framework


I am attempting to integrate a mongoDB process into Java but can't wrap my head around how to integrate the $expressions within the $project operator whilest using the aggregation framework. The perfectly working Mongo query is:

db.options.aggregate([{$project:{name:1,lastTradeDate:1,month:{$substr:["$lastTradeDate",4,2]}}},{$out:"Books"}])

Converting this to Java has got me to the following (non-functioning) point:

Document expression = new Document("$substr", new Document("lastTradeDate",new int[] {4,2}));
        AggregateIterable iterable = myDocs.aggregate(asList(
                new Document("$project", new Document("name", 1).append("lastTradeDate", 1).append("month", expression)),
                new Document("$group", new Document("_id", "$contSize").append("count", new Document("$sum", 1))));

So the question is: how do I ge the 'expression' to actually be recognized as an expression of the $substr type?


Solution

  • In case anyone runs into the same problem. I found that Jongo gave the flexibility I was after without the convoluted way of having to implement this directly.

    The resulting jongo query looks something like the following:

    Aggregate.ResultsIterator<JongoDoc> jongoProject = JongoColl.aggregate("{$project:{name:1, smonth:{$substr:['$lastTradeDate',4,2]}}}").and("{$out:'Books'}").as(JongoDoc.class);