[英]Get the total amount of aggregated data in Mongoose
我有 2 个文件: Locations
和Orders
假设我有 4 个位置,有些位置包含订单。
我已经能够获取我的位置列表以及每个位置的相应订单。
我不能做的是包括每个位置的订单数量和总面积。 (每个单独的订单已包含此信息)
这是带有我当前代码的 Mongo Playground。 请注意,我想填充“金额”和“总计”。
https://mongoplayground.net/p/FO_nYDOD1kn
这是我用来聚合我的数据的内容:
db.Locations.aggregate([{
$lookup: {
from: "Orders",
let: {
loc_id: "$_id"
},
pipeline: [{
$match: {
$expr: {
$eq: ["$$loc_id", "$location"]
}
}
}, {
$project: {
_id: 0,
products: 1
}
}],
as: "orders"
}
}, {
$project: {
_id: 1,
name: 1,
orders: {
total: "insert total orders expanses in this order",
amount: "insert amount of orders for this location",
orders: "$orders"
}
}
}])
以及单个订单的结构:
{
"_id": "5e17ab585eb7f11a971bce5c",
"location": "5e17a001f1e0220def7a2b5d",
"total": "1000"
}
好吧,我做了一些工作! 好极了!
这是找到这个的人的解决方案。
Location
.aggregate([
{
$lookup: {
from: "orders",
let: { loc_id: "$_id" },
pipeline: [{ $match: { $expr: { $eq: ["$$loc_id", "$location"] } } }],
as: "order"
}
}
,
{
$project: {
_id: 1,
name: 1,
address: 1,
orders: {
total: { $sum: "$order.total" },
amount: { $size: "$order" },
items: "$order"
}
}
}
])
.then(locations => {
res.status(200).json({
success: true,
locations
})
})
.catch(error => {
res.status(500).json({
success: false,
error
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.