获取猫鼬的汇总数据总量 [英] Get the total amount of aggregated data in Mongoose
问题描述
我有2个文档:Locations
和Orders
假设我有4个地点,有些地点包含订单.
Let's say I have 4 locations, and some locations contain orders.
我已经能够获取位置列表以及每个位置的相应订单.
I'm already able to get a list of my locations with the corresponding orders for each location.
我不能够做的是包括每个位置的订单量以及总费用. (每个单独的订单已包含此信息)
What I'm not able to do, is to include the amount of orders for each location, and the total expanses. (Each individual order already contain this information)
这是我当前代码的Mongo Playground. 请注意,我要填充数量"和总计".
Here's Mongo Playground with my current code. Notice that I want to populate "amount" and "total".
https://mongoplayground.net/p/FO_nYDOD1kn
这是我用来汇总数据的方式:
This is what I use to aggregate my data:
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"
}
推荐答案
好的,我做了一些工作!是的!
Alright, I made something work! Yay!
这是找到它的人的解决方案.
Here's the solution for whoever finds this.
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
})
})
这篇关于获取猫鼬的汇总数据总量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!