我有 3 个集合及其架构的简化表示
我正在尝试获取独特产品的列表及其描述和库存(单位 - 发货数量)。
我试过这个
db.products.aggregate([
{ $match: {} },
{
$lookup: {
from: "sales",
localField: "sku",
foreignField: "sku",
as: "sales",
},
},
{ $unwind: "$sales" },
{
$lookup: {
from: "batches",
localField: "sku",
foreignField: "sku",
as: "batches",
},
},
{ $unwind: "$batches" },
{
$project: {
sku: 1,
productId: "$products._id",
productDescription: "$products.description",
description: 1,
unitsLeft: {
$subtract: ["$batches.units", "$sales.quantityShipped"],
},
},
},
{
$group: {
_id: {
sku: "$_id",
productId: "$_id",
description: "$description",
},
_id: "$_id",
total: {
$sum: "$unitsLeft",
},
},
},
]);
我错过了什么?
输入示例:
- Product
{
description: "A black Shoe",
sku: "HT124"
}
- Batch
{ units: 130, sku:"HT124" }
- Sales
{ quantityShipped: 100, sku: "HT124"}
- SAMPLE OUTPUT
[ { _id: "productId1", description: "product description1", stock: 30}, { _id: "productId2", description: "product description2", stock: 40}]
以下是我在导入代码并在 Mongo Playground 中运行时发现的错误/错误:
$lookup
为空,从而导致 $unwind
$group
获取剩余库存之前,您应该先$subtract
获取已售出的总数量;在您当前的代码中,通过复制现有库存计数,您将得到不正确的计算结果db.products.aggregate([
{
$lookup: {
from: "sales",
localField: "sku",
foreignField: "sku",
as: "sales"
}
},
{
$unwind: "$sales"
},
{
$lookup: {
from: "batches",
localField: "sku",
foreignField: "sku",
as: "batches"
}
},
{
$unwind: "$batches"
},
{
$group: {
_id: {
productId: "$_id",
description: "$description"
},
totalSales: {
$sum: "$sales.quantityShipped"
},
units: {
$first: "$batches.units"
}
}
},
{
$project: {
_id: "$_id.productId",
description: "$_id.description",
stock: {
"$subtract": [
"$units",
"$totalSales"
]
}
}
}
])
这里有一个“修正”了以上几点的Mongo Playground,供大家参考。