gpt4 book ai didi

java - MongoDB聚合Spring/Java(带有数组、分组和匹配的项目)

转载 作者:行者123 更新时间:2023-12-02 13:05:03 24 4
gpt4 key购买 nike

我在使用 springframework 在 Java 中编写该查询时遇到问题。

db.getCollection('fish').aggregate(
{$match : {"uploadDate" : { $gte : new ISODate("2017-05-22T00:00:00Z"), $lte : new ISODate("2017-05-25T00:00:00Z") }}},
{$group: {_id: {lake : "$lake", type : "$type"}, count: {$sum: 1}}} ,
{$project: {array : ["$_id.type" , "$count"], count : "$count"}},
{$group: {_id: {lake : "$_id.lake"}, count: {$sum: 1}, types : {$addToSet : "$array"}}})

我能够编写匹配和分组,但在添加包含 id.type 和 count 的数组的项目时遇到问题。到目前为止我能够写这个

Aggregation aggregation = newAggregation(match(Criteria.where("uploadDate").gte(created).lte(newCreatedDate)),
group("lake").count().as("values"));

我找不到任何解决方案如何编写它,我只看到您可以将字段/字符串添加到 project()

最佳答案

我会给你替代方案,因为确实没有办法按照你想要的方式创建表达式。

您必须使用AggregationOperation并使用BasicDBObject来创建project阶段。

类似于

AggregationOperation project = aggregationOperationContext -> new BasicDBObject("$project", new BasicDBObject("array", Arrays.asList("$_id.type" , "$count")).append("count", "$count"));

关于java - MongoDB聚合Spring/Java(带有数组、分组和匹配的项目),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44165812/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com