Mongodb聚合:如何多次使用unwind-> group->项目

时间:2016-02-16 21:04:43

标签: mongodb mongodb-query aggregation-framework

我有一个订单集合,我需要从多个子数组数组计算一些总和,但我无法弄清楚如何松开双展开创建的相乘项目。

db.Orders.aggregate(
  {$unwind: "$items"},
  {$unwind: "$shipping"},           
  {$group: {
    _id: {
      year: { '$year': '$createdAt' },
      month: { '$month': '$createdAt' },
      day: { '$dayOfMonth': '$createdAt' }
    },
    mainItems: { $addToSet: '$items' },
    totalSales: {$sum: {
      $multiply: ["$items.quantity",   "$items.variants.price"]
    }},
    averageSales: {$avg: {$multiply: ["$items.quantity", "$items.variants.price"]}},
    /* this will not sum the individial orders because the unwind 
     * created multiple document per order*/
    ordersPlaced: {$sum: 1}, 
    itemsPurchased: {$sum: "$items.quantity"},
    totalRefundAmount: {$sum: 0},
    chargedForShipping: {$sum: "$shipping.shipmentMethod.rate"}
  }}
)

如果我从展开和小组中取出发货,则查询将返回正确的值,但chargedForShipping(0,因为它是unwinded)和ordersPlaces仍将是超出预期(但我还需要运送信息以及我为了更容易理解而采取的更多其他信息)。

示例数据:

[{
    "_id" : "xK29ZHxGcYvgWgx5p",
    "sessionId" : "yw7e9G7uBzYTy9Grq",
    "userId" : "fZREMm2DmsnMosMKj",
    "shopId" : "oiqQDnuBwabj44q2o",

    "billing" : [ 
        {
            "shopId" : "oiqQDnuBwabj44q2o",

            "_id" : "9TMJj9w65MmAkgg27",
            "paymentMethod" : {
                "amount" : 22.45,
                "status" : "settled",
                "mode" : "capture",
                "transactionId" : "AP",
                "createdAt" : ISODate("2016-02-15T13:44:35.116Z"),
                "transactions" : [ 
                   { type:"refund", amount:5}
                ]
            }
        }, 
        {

            "shopId" : "9YfkXWyCci8fN43Pj",
            "_id" : "RwW8xMnFzQqdTpqtg",
            "paymentMethod" : {
                "createdAt" : ISODate("2016-02-15T13:44:35.116Z")
            }
        }, 
        {

            "shopId" : "SgXWPKGJkxBw6qsbT",
            "_id" : "ASizt6BtkxpCxgEJn",
            "paymentMethod" : {
                "createdAt" : ISODate("2016-02-15T13:44:35.116Z")
            }
        }
    ],
    "shipping" : [ 
        {
            "_id" : "yXb5T5zLuxPYmgoT5",
            "shipmentMethod" : {
                "name" : "Continental US",
                "_id" : "womiJX2QZBFQQWFur",
                "rate" : 9.949999999999999,
                "shopId" : "9YfkXWyCci8fN43Pj",

            },
            "items" : [ 
                {
                    "_id" : "48s9bmDfrRMqnkije",
                    "productId" : "KXtF5xqERWJsXk2yP",
                    "shopId" : "SgXWPKGJkxBw6qsbT",
                    "variantId" : "YQDHuyPHbhx4wruZx",
                    "quantity" : 1
                }
            ],
            "packed" : false,
            "shipped" : false,
        }
    ],
    "items" : [ 
        {
            "_id" : "hhuiGFTBkLACLpPjQ",
            "shopId" : "9YfkXWyCci8fN43Pj",
            "productId" : "sDYNXMrnRJiyQ8gex",
            "quantity" : 1,
            "variants" : {
                "_id" : "muJi6Bqnq2CD8B7AR",
                "price" : 2.5,
               "title" : "egy",
                "weight" : 23,

            },
            "type" : "simple",

        }, 
        {
            "_id" : "48s9bmDfrRMqnkije",
            "shopId" : "SgXWPKGJkxBw6qsbT",
            "productId" : "KXtF5xqERWJsXk2yP",
            "quantity" : 1,
            "variants" : {
                "_id" : "YQDHuyPHbhx4wruZx",
                "title" : "Bogi varinat title",
                "price" : 10,
                "type" : "variant",
                "compareAtPrice" : 100000,
                "weight" : 100,

            },
            "type" : "simple",

        }
    ],

    "email" : "test@user.com",
    "createdAt" : ISODate("2016-02-15T13:44:35.091Z"),
    "updatedAt" : ISODate("2016-02-15T14:24:55.174Z")
}]

我需要的是每月orderTotal,每月shippingTotal,每月totalRefunded,每月平均销售额。问题是我需要从items子数组,另一个来自shipping子数组,第三个来自billing子数组,这就是我解开问题的原因。

0 个答案:

没有答案