我正在尝试在Mongodb中执行查询。我想要执行的查询是根据日期(过去7天)查找集合中的所有订单,然后将每个订单的嵌套对象的价格相加。到目前为止,我有以下代码:
类别/数据
{
"_id" : "g32fYpydfSFDbFkoi",
"orderNumber" : 1234,
"createdAt" : ISODate("2016-01-12T13:50:17.559Z"),
"productsInOrder" : [
{
"category" : "ambient",
"item" : 23982,
"desc" : "Ergonomic Cotton Sausages",
"quantity" : "456",
"price" : "0.54",
"lineprice" : "246.24",
"_id" : "BdD4QnM7sYTwBpLds"
},
{
"category" : "ambient",
"item" : 15336,
"desc" : "Rustic Wooden Chicken",
"quantity" : "2",
"price" : "1.87",
"lineprice" : "3.74",
"_id" : "PvtSxi2MfYrZNTD6f"
},
{
"category" : "chilled",
"item" : 57584,
"desc" : "Unbranded Soft Chicken",
"quantity" : "3",
"price" : "4.69",
"lineprice" : "14.07",
"_id" : "ppkECqmhPvg7pQcgB"
},
{
"category" : "ambient",
"item" : 71168,
"desc" : "Rustic Rubber Computer",
"quantity" : "5",
"price" : "3.04",
"lineprice" : "15.20",
"_id" : "bZtr5dkvsG92YtLoe"
},
{
"category" : "frozen",
"item" : 87431,
"desc" : "Unbranded Granite Sausages",
"quantity" : "5678",
"price" : "1.98",
"lineprice" : "11242.44",
"_id" : "ZKur3rHhtCLsWiENr"
},
{
"category" : "frozen",
"item" : 75007,
"desc" : "Practical Frozen Towels",
"quantity" : "678",
"price" : "1.19",
"lineprice" : "806.82",
"_id" : "g78zvzoE8wJkciD9C"
},
{
"category" : "frozen",
"item" : 84721,
"desc" : "Fantastic Metal Hat",
"quantity" : "34",
"price" : "1.83",
"lineprice" : "62.22",
"_id" : "4aqxBWhXy5cabbbiM"
},
{
"category" : "frozen",
"item" : 72240,
"desc" : "Fantastic Granite Towels",
"quantity" : "1",
"price" : "2.94",
"lineprice" : "2.94",
"_id" : "MQD2LNv36mE3BWvZJ"
},
{
"category" : "chilled",
"item" : 89448,
"desc" : "Intelligent Concrete Towels",
"quantity" : "6678",
"price" : "0.42",
"lineprice" : "2804.76",
"_id" : "AjRrxFT4mfpxuciC4"
},
{
"category" : "chilled",
"item" : 57584,
"desc" : "Unbranded Soft Chicken",
"quantity" : "1111",
"price" : "4.69",
"lineprice" : "5210.59",
"_id" : "4yBspve6mBNNzqDnZ"
}
]
}
查询
Orders.aggregate([
{ $match: { 'createdAt': { $gt: pastDate }}},
{ $unwind: '$productsInOrder' },
{
$group: {
_id: null,
price: {
$sum: '$productsInOrder.price'
}
}
}
]);
我最终想要的是输出过去7天每天的总价。谁能帮助我指出正确的方向?非常感谢提前。
答案 0 :(得分:1)
首先, $sum
运算符将忽略非数字值,productsInOrder.price
子文档字段为String类型,因此最好将其转换为数字字段。
完成此操作后,要输出过去7天内每天的总价格,请按键更改组,以使用 $dayOfMonth
运算符,该运算符将您的文档每天分组。日期范围,如下所示
Orders.aggregate([
{ "$match": { "createdAt": { "$gt": pastDate } } },
{ "$unwind": "$productsInOrder" },
{
"$group": {
"_id": {
"day": { "$dayOfMonth": "$createdAt" }
},
"price": { "$sum": "$productsInOrder.price" }
}
}
]);