Mongo汇总(按和分组)

时间:2020-04-11 09:58:43

标签: jquery node.js database mongodb mongoose

订单收集数据,例如:

      "products": [
        {
          "productId": "5e83bbaa6e9c50132c05d8af",
          "quantity": 5
        },
        {
          "productId": "5e7f5facddae7c00744e77de",
          "quantity": 3
        }
      ],
      "_id": "5e8f9b62afc293002393d09f",
      "restaurantId": "5e7c60264540d00023b1fb16",
      "clientId": "5e864c89ece8ad002322f1e2",
      "orderStatus": "order-preparing",
      "orderCancleReason": "null",
      "driverId": "null",
      "destinationLong": "73.03565745472619",
      "destinationLat": "33.57202153787093",
      "orderPrice": "560",
      "deliveryCharges": "15",
      "totalOrderPrice": 575,
      "totalOrderPriceInSeting": "575",
      "orderTime": "2020-04-09T22:02:10.454Z",
      "__v": 0
    },
    {
      "products": [
        {
          "productId": "5e83bbaa6e9c50132c05d8af",
          "quantity": 4
        }
      ],
      "_id": "5e8fa06bafc293002393d0a0",
      "restaurantId": "5e7c60264540d00023b1fb16",
      "clientId": "5e864c89ece8ad002322f1e2",
      "orderStatus": "order-preparing",
      "orderCancleReason": "null",
      "driverId": "null",
      "destinationLong": "73.03491740731033",
      "destinationLat": "33.57570871502576",
      "orderPrice": "400",
      "deliveryCharges": "15",
      "totalOrderPrice": 415,
      "totalOrderPriceInSeting": "415",
      "orderTime": "2020-04-09T22:23:39.485Z",
      "__v": 0
    },

我要分组并计算productId,而不要重复ID 我尝试:

      $group: {
        _id: "$products.productId",
        count: { $sum: 1 },
      },
    },

我的代码获取具有单个产品的订单的数据工作正常,但是当订单具有多个产品时,它将创建一个新字段,然后对这些产品进行计数

0 个答案:

没有答案