在spring mongodb数据中运行原始聚合json字符串

ryevplcw  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(235)

我想直接在JavaSpringMongoDB数据中,在mongodb的标准聚合结构中,为聚合发送原始json字符串。例如:

[
      { $match: { status: "A" } },
      { $group: { _id: "$cust_id", total: { $sum: "$amount" } } },
      { $sort: { total: -1 } }
]

有类似的吗 BasicQuery 对于聚合?
我希望使用原始字符串构建聚合,因为我希望允许客户端指定聚合查询。
先谢谢你

juzqafwq

juzqafwq1#

尝试使用spring数据mongodb MongoTemplateAggregation . 下面的示例演示了mongodb聚合框架的使用模式。
在您的情况下,可以这样编写聚合代码:

Aggregation aggregation = newAggregation(
    match(Criteria.where("status").is("A")),
    group("status")
        .first("cust_id").as("_id")
        .sum("amount").as("total"),
    sort(Direction.DESC, "total")
);

AggregationResults<AggregationResult> results = mongoTemplate.aggregate(
    aggregation, "your_collection_name", AggregationResult.class);
List<AggregationResult> aggregationResult = results.getMappedResults();

相关问题