当前位置: 动力学知识库 > 问答 > 编程问答 >

regex - 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?

网友答案:

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);
网友答案:

For $substr in $project operator, you can form query the following way:

In mongodb, considering a document :

{
    "_id" : ObjectId("58a09b076560a311779be35f"),
    "name" : "Helen",
    "date" : "12-04-2015",
    "description" : "Committee head"
}

Consider you need only day to be projected from "date" field. The aggregate query using java query is as follows:

Document dayExpression = new Document("$substr", Arrays.asList("$date", 0, 2));

AggregateIterable<BasicDBObject> iterable = coll.aggregate(Arrays
                .asList(new Document("$project", new Document("name", 1)
                                .append("description", 1),
                                .append("dayOfDate", dayExpression))));
分享给朋友:
您可能感兴趣的文章:
随机阅读: