查找和展开mongodb后如何防止重复的总和

时间:2019-05-20 09:48:23

标签: mongodb sum mongodb-query aggregation-framework

我有托收订单(销售,客户,小计和发票集)和销售(集合销售信息,它有1个或多个联系人),然后我想查看每个客户在当前期间的总订单数,在我把$ unwind放在这里之前,这里是我的代码:

[{"_id":"CUSTOMER ABC","SALES":(Array) 2 Elements,"TOTAL":231986}]

,它将返回如下输出:

db.torder.aggregate([
        {$match:{$and:[{TANGGALPI:{$gte:'2019-01-01'}},{TANGGALPI:{$lte:'2019-12-31'}}]}},
        {$lookup:{
                from:"tsales",
                localField:"IDSALES",
                foreignField:"SALESCODE",
                as:"SALESINFO"
        }},
        {$unwind : "$SALESINFO"},
        {$group:{
                _id:"$CUSTNAME",SALES:{$first:"$SALESINFO.NAMASALES"},TOTAL : { $sum: {$multiply:["$QTY","$PRICE"]}}}},
        {$sort:{TOTAL:-1}}
])

然后我执行$ unwind,将数组元素更改为field元素:

[{"_id":"CUSTOMER ABC","SALES":"Peter","TOTAL":463972}] => total will become 2 times than before

其输出变为:

[{"_id":"CUSTOMER ABC","SALES":"Peter","TOTAL":231986}]

我检查我的tsales集合,Sales Peter有两行值,因此使重复项的总和值为零,如何使用$ unwind用单行tsales集合进行正确的计算总和

我想要这样的输出:

    if (method.equals("POST") )
            {
                url+= "api/now/table/incident";
            }
            else if (method.equals("GET")|| method.equals("PUT"))
            {
                url+= "api/now/table/incident/" + incident.getSys_id();
            }

            URL request_url = new URL(url);
            CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
            connection = (HttpsURLConnection) request_url.openConnection();
//            ((HttpsURLConnection) connection).setSSLSocketFactory(sslsocketfactory);
            if (method.equals("POST") || method.equals("PUT"))
            {
                connection.setRequestProperty("Content-Type", "application/json");
            }
            else
            {
                connection.setRequestProperty("Accept", "application/json");
            }

            connection.setRequestProperty("User-Agent", "Mozilla/5.0"); // this was suggested as solution, but doesn't work.

            connection.setRequestMethod(method);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setRequestProperty("Authorization", "Basic "+encoded);

            if (method.equals("POST") || method.equals("PUT"))
            {
                JSONObject json = new JSONObject();

                json.put("short_description",incident.getShort_description());
                json.put("description", incident.getDescription());
                json.put("assignment_group",incident.getAssignment_group());
                json.put("priority",incident.getPriority());
                json.put("impact",incident.getImpact());

                OutputStream os = connection.getOutputStream();
                os.write(json.toJSONString().getBytes(StandardCharsets.UTF_8));
                os.close();
            }

            // read the respond
            httpsCode = connection.getResponseCode();
            if (httpsCode == HttpsURLConnection.HTTP_OK || httpsCode == 201)
            {
                //Read
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
                String lines = null;
                StringBuilder stringBuilder = new StringBuilder();
                while ((lines = bufferedReader.readLine()) != null)
                {
                    stringBuilder.append(lines);
                }
                bufferedReader.close();
                result = stringBuilder.toString();
                JSONParser parser = new JSONParser();
                JSONObject json = (JSONObject) parser.parse(result);
                String incident_number = json.get("incident_number").toString();
                String sys_id = json.get("sys_id").toString();
                incident.setIncident_number(incident_number);
                incident.setSys_id(sys_id);

                return  null;
            }

1 个答案:

答案 0 :(得分:0)

您只需要交换$group$lookup阶段。

db.torder.aggregate([
  { "$match": {
    "TANGGALPI": { "$gte": "2019-01-01", "$lte": "2019-12-31" }
  }},
  { "$group": {
    "_id": "$CUSTNAME",
    "IDSALES": { "$first": "$IDSALES" },
    "TOTAL": { "$sum": { "$multiply": ["$QTY", "$PRICE"] } },
    "duplicateNames": { "$push": "$name" }
  }},
  { "$lookup": {
    "from": "tsales",
    "localField": "IDSALES",
    "foreignField": "SALESCODE",
    "as": "SALES"
  }},
  { "$addFields": {
    "SALES": { "$arrayElemAt": ["$SALES.NAMASALES", 0] }
  }},
  { "$sort": { "TOTAL": -1 } }
])