mongodb-获得按字段分组的总和的最大值

时间:2018-08-06 17:04:32

标签: mongodb aggregation-framework

我想我们有这个数据

{ "_id" : 1, "item" : "abc", "quantity" : 2, "category" : 1}

{ "_id" : 2, "item" : "jkl", "quantity" : 1, "category" : 1}

{ "_id" : 3, "item" : "xyz", "quantity" : 5, "category" : 2}

{ "_id" : 4, "item" : "abc", "quantity" : 10, "category" : 2}

{ "_id" : 5, "item" : "xyz", "quantity" : 10, "category" : 3}

{ "_id" : 6, "item" : "cds", "quantity" : 9, "category" : 3}

我想查询一个包含最大数量的类别的查询。 所以我必须:

1-按类别分组

2-汇总每个类别中项目的数量

3-得到这些总和中的最高值。

请帮助我进行此查询。 预先谢谢你

1 个答案:

答案 0 :(得分:0)

import org.apache.cxf.endpoint.Client; import org.apache.cxf.frontend.ClientProxy; import org.apache.cxf.jaxws.JaxWsProxyFactoryBean; import org.apache.cxf.transport.http.HTTPConduit; import org.apache.cxf.transports.http.configuration.HTTPClientPolicy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class WebServiceConsumerPort<P>{ protected P puerto; private static Logger log = LoggerFactory.getLogger(WebServiceConsumerPort.class); public void creaPuerto(String url, String timeoutS, Class<P> tipoClase) { try { Long timeout = Long.parseLong(timeoutS); JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); factory.setServiceClass(tipoClase); factory.setAddress(url); puerto = (P) factory.create(); Client client = ClientProxy.getClient(puerto); if (client != null) { HTTPConduit conduit = (HTTPConduit) client.getConduit(); HTTPClientPolicy policy = new HTTPClientPolicy(); policy.setAllowChunking(false); policy.setConnectionTimeout(timeout * 1000); policy.setReceiveTimeout(timeout * 1000); conduit.setClient(policy); } nIntento = 0; } catch (Exception e) { puerto = null; nIntento++; } } } $sort一起使用可得到最大总数:

$limit