【发布时间】:2021-05-24 19:20:37
【问题描述】:
我是 mongodb 聚合的新手,我有一个集合
{
"_id":60ab3312623b0108338a9601,
"items":[{"type":"Tshirt","price":300,"quantity":2}],
"orderId":"ORD189",
"from":"abc",
"to":"xyz",
"createdAt":2021-05-24T05:01:06.960Z,
"__v":0,
"tracking":null
}
我想查找每天的订单数量和类似物品的总价格
{_id: {date:24, month:05, year:2021}, count: 1, totalPrice: 600}
我使用了像下面这样的聚合
db.getCollection("orders").aggregate(
[
{
"$group" : {
"_id" : {
"date" : {
"$dayOfMonth" : "$createdAt"
},
"month" : {
"$month" : "$createdAt"
},
"year" : {
"$year" : "$createdAt"
}
},
"count" : { $sum : 1},
"totalPrice" : {
$sum: {
$map: {
"input" :"$items",
"as":"item",
"in":{
$multiply: ["$item.price", "$item.quantity"]
}
}
}
}
}
}
]
);
它给了我以下结果
{
"_id" : {
"date" : NumberInt(24),
"month" : NumberInt(5),
"year" : NumberInt(2021)
},
"count" : 1.0,
"totalPrice" : NumberInt(0)
}
如果我使用 unwind 无法获得正确的计数。
【问题讨论】:
标签: mongodb aggregation-framework