我有一个问题,我想在吗啡中编写这样的代码
select sum(amount) from y where date > a and date < b
在 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);
但我收到这样的错误
Command failed with error 9: 'The 'cursor' option is required, except for aggregate with the explain argument' on server XXXXX:27017. The full response is { "ok" : 0.0, "errmsg" : "The 'cursor' option is required, except for aggregate with the explain argument", "code" : 9, "codeName" : "FailedToParse" }
谢谢
最佳答案
答案在这里
首先制作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());
}
祝你有美好的一天!
关于java - 如何在 mongo morphia 中对 2 个日期求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57092565/