无法将聚合查询从mongodb转换为Spring Data MongoDb

时间:2017-08-01 13:11:19

标签: java spring mongodb spring-boot spring-data

我一直在尝试使用Aggregation Object将mongodb中的查询转换为Spring Data MongoDb。我在mongo中有以下文档:

{
"_id" : ObjectId("596ce468798b61179c6442bb"),
"_class" : "com.test.model.User",
"name" : "Oi",
"surName" : "Alo",
"workLogs" : [
    {
        "_id" : ObjectId("596ce468798b61179c6442bc"),
        "day" : 1,
        "month" : 1,
        "year" : 2017,
        "timeEntrance" : "8:00",
        "lunchLeave" : "12:00",
        "lunchBack" : "13:00",
        "timeLeave" : "18:00"
    },
    {
        "_id" : ObjectId("596ce468798b61179c6442bd"),
        "day" : 2,
        "month" : 1,
        "year" : 2017,
        "timeEntrance" : "8:00",
        "lunchLeave" : "12:00",
        "lunchBack" : "13:00",
        "timeLeave" : "18:00"
    }
  ]
}

我想查询同一年和月份的所有workLogs,之后我想得到workLogs数组作为结果。我设法使用mongo使用此查询:

db.user.aggregate([
  {$unwind: '$workLogs'}, 
  {$match: {'workLogs.month':2, 'workLogs.year':2017}}, 
  {$group: {_id:'$_id', workLogs:{$push: '$workLogs'}}}, 
  {$project: {'_id':0, 'workLogs': 1}}
]).pretty()

但是我无法找到如何将此查询转换为Spring Data MongoDb,我想我几乎就在那里,如果有人可以帮助我,我会很感激。这是我在java中使用的代码。

Aggregation agg = Aggregation.newAggregation(
  unwind("workLogs"),
  match(Criteria
    .where("_id").is(userId)
    .and("workLogs.month").is(1)
    .and("workLogs.year").is(2017)
    ),
    group("_id"),
    group("horarios")
      .push(new BasicDBObject("workLogs", "workLogs")).as("workLogs"),
    project("workLogs")
);

AggregationResults<WorkLog> results = mongoTemplate.aggregate(agg, "workLogs", WorkLog.class);

提前谢谢大家!

1 个答案:

答案 0 :(得分:3)

不确定为什么你的java代码中有所有额外的字段。

shell查询的java等效代码是

 Aggregation agg = Aggregation.newAggregation(
   unwind("workLogs"),
   match(Criteria
      .where("workLogs.month").is(1)
      .and("workLogs.year").is(2017)
   ),
   group("_id").push("workLogs").as("workLogs"),
   project("workLogs").andExclude("_id")
 );

或者,您可以简化代码以使用$filter

import static org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.project;
import static org.springframework.data.mongodb.core.aggregation.ArrayOperators.Filter.filter;
import static org.springframework.data.mongodb.core.aggregation.BooleanOperators.And.and;
import static org.springframework.data.mongodb.core.aggregation.ComparisonOperators.Eq;

 Aggregation agg = newAggregation(project().
     and(
      filter("workLogs").
      as("workLog").
      by(
       and(
          Eq.valueOf("workLog.month").equalToValue(1), 
          Eq.valueOf("workLog.year").equalToValue(2017)
      )
     )
    ).as("workLogs").
    andExclude("_id")
 );