如何在此查询中使用分组

时间:2017-08-10 11:14:23

标签: java mongodb morphia

我正在使用mongo morphia。如何在下面的函数中添加group by子句。

public ArrayList<DeliveryServiceVisitorUserTraceEntity> listExpectedDeliveries(String associationId) {

        // HashMap<String, String> filterExpressions = new HashMap<String, String>();

        Query<DeliveryServiceVisitorUserTraceEntity> query = DBManager.getInstance().createQuery(
                DeliveryServiceVisitorUserTraceEntity.class);

        List<Integer> values = new ArrayList<Integer>();
        values.add(1);
        values.add(2);

        query.and(query.criteria("associationId").equal(associationId),
                query.criteria("deliveryServicestatus").in(values),
                query.criteria("allowTimeIn").greaterThan(getStartOfDay(new Date()) + ""), query
                        .criteria("allowTimeIn").lessThan(getEndOfDay(new Date()) + "")
                        );
        List<DeliveryServiceVisitorUserTraceEntity> residents = query.asList();
        return new ArrayList<DeliveryServiceVisitorUserTraceEntity>(residents);
    }

1 个答案:

答案 0 :(得分:0)

您必须使用聚合框架来实现分组。 我使用morphia 1.1.0并进行聚合我会做这样的事情

AggregationPipeline pipeline = DAO.getDatastore()
      .createAggregation(DeliveryServiceVisitorUserTraceEntity.class)
      .match(query) //Your createQuery object
      .group("groupByField"); //group by field
        
 Iterator<GroupObj> iterator = pipeline.aggregate(GroupObj.class);

这里GroupObj是您需要创建的新类,它与聚合结果的模式匹配