如何在mongo吗啡中的2个日期之间求和?

时间:2019-07-18 10:34:50

标签: java mongodb morphia

我有一个问题,我想用吗啡写这样的代码

  

从y中选择总和(金额),其中date> a和date

在Robo3T中,我已经成功创建了查询

db.TransactionLog.aggregate([
  { 
    $match: {
      transactionTimestamp: {
        $gte: ISODate("2018-06-05T07:10:22.725Z"),
        $lt: ISODate("2019-07-01T07:10:22.725Z")
      },
        senderAccount:"1234567890"
    }
  }, {
    $group: {
      _id: null,
      total: {
        $sum: "$amount"
      }
    }
  }
]);

结果

{
    "_id" : null,
    "total" : NumberDecimal("55987000.00")
}

但是如何用Java代码编写呢?我已经尝试过了

Query<TransactionLog> query = datastore.createQuery(TransactionLog.class);
    AggregationPipeline pipeline = datastore.createAggregation(TransactionLog.class)
            .match(
                    query
                            .filter("transactionTimestamp >=", new Date(2018, 6, 5, 0, 0, 0))
                            .filter("transactionTimestamp <=", new Date(2019, 7, 15, 0, 0, 0))
                            .filter("senderAccount", "0012101781")
            ).group(Group.grouping("count", new Accumulator("$sum", "amount")))
            ;
    AggregationOptions opts = AggregationOptions.builder().outputMode(OutputMode.CURSOR).build();
    pipeline.aggregate(TransactionLog.class, opts);
    Iterator<BigDecimal> result = pipeline.out(BigDecimal.class);

但是我得到这样的错误

  

命令失败,错误9:“'cursor'选项是必需的,除了   在服务器XXXXX:27017上使用“解释参数”进行汇总。的   完整的响应为{“ ok”:0.0,“ errmsg”:“” cursor“选项为   必需,但带有解释参数的聚合“,” code“:9,   “ codeName”:“ FailedToParse”}

谢谢

1 个答案:

答案 0 :(得分:0)

这是答案

首先制作pojo

public class Summary {

    private BigDecimal count;

    public BigDecimal getCount() {
        return count;
    }

    public void setCount(BigDecimal count) {
        this.count = count;
    }
}

第二个是代码

Query<TransactionLog> query = datastore.createQuery(TransactionLog.class);


            query.field("transactionTimestamp").greaterThanOrEq(oneYearAgo());
            query.field("transactionTimestamp").lessThanOrEq(new Date());
            query.field("senderAccount").equal("1234567890");


            Iterator<Summary> pipeline = datastore.createAggregation(TransactionLog.class)
                    .match(query)
                    .group(Group.grouping("count", new Accumulator("$sum", "amount")))
                    .aggregate(Summary.class, AggregationOptions.builder()
                            .outputMode(AggregationOptions.OutputMode.CURSOR)
                            .build());

            while (pipeline.hasNext()) {
                Summary x = pipeline.next();
                System.out.println(x.getCount());
            }

祝你有美好的一天!