Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring Mongo聚合请求_Spring_Mongodb - Fatal编程技术网

Spring Mongo聚合请求

Spring Mongo聚合请求,spring,mongodb,Spring,Mongodb,我是mongo/spring启动环境的新手,我需要一些帮助来回答一个简短的问题: 我收集的销售包括: { {"client": "MICKAEL", "article": "article1"}, {"client": "MICKAEL", "article": "article1"}, {"client

我是mongo/spring启动环境的新手,我需要一些帮助来回答一个简短的问题: 我收集的销售包括:

{
    {"client": "MICKAEL", "article": "article1"},
    {"client": "MICKAEL", "article": "article1"},
    {"client": "MICKAEL", "article": "article2"},
    {"client": "JOHN", "article": "article1"},
    {"client": "JACK", "article": "article1"},
    {"client": "JACK", "article": "article2"},
}
所以,根据Mongo的要求

db.getCollection("sales").aggregate(
    [
      {"$group" : {_id: {client:"$client",article:"$article"}}},
      {"$group" : {_id: {client:"$_id.client"}, count:{$sum:1}}
    ]
)
我得到以下结果:

{"_id" : {"client" : "JACK"}, "count" : 2},
{"_id" : {"client" : "JOHN"}, "count" : 1},
{"_id" : {"client" : "MICKAEL"}, "count" : 2}
那么每个客户有多少不同的商品。那很好

不,我花了更多的时间用Spring boot(使用存储库或mongoOperations/aggregate请求)来翻译,但没有结果

你能帮我吗?
非常感谢

希望您的查询工作正常。您可以使用
MongoTemplate
将其隐藏。因此,您需要自动连接它

@Autowired
MongoTemplate mongoTemplate;
聚合函数可帮助您转换此值

public List<Object> test(){
    Aggregation aggregation = Aggregation.newAggregation(
        group(
            Fields.from(
                    Fields.field("client", "$client"),
                    Fields.field("article", "$article")
            )
        ),
        group(
            Fields.from(
                    Fields.field("client", "$_id.client")
            )
        ).count().as("count")

    ).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());

    return mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(YOUR_COLLECTION.class), Object.class).getMappedResults();
}
公共列表测试(){
Aggregation=Aggregation.newAggregation(
团体(
字段(
字段。字段(“客户机”,“$client”),
Fields.field(“article”、“$article”)
)
),
团体(
字段(
Fields.field(“客户机”,“美元id.client”)
)
).count().as(“count”)
).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE.build());
返回mongoTemplate.aggregate(聚合,mongoTemplate.getCollectionName(您的_COLLECTION.class),Object.class).getMappedResults();
}

我还没有测试过它,但如果您的查询是正确的,它应该可以工作。

非常感谢您。我测试你的解决方案。