我有一个问题,我想在莫菲亚写这样的代码
从y where date中选择sum(金额)
在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:“游标”选项是必需的,除了服务器XXXXX: 27017上的带有解释参数的聚合。完整响应是{"ok":0.0,"errmsg":"`cursor'选项是必需的,除了带有解释参数的聚合","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());
}
祝你有美好的一天!