我有一个名为库存的集合,其中包含以下文档:
{
"_id" : 1,
"type" : "In",
"qty" : 30,
"tranDate" : ISODate("2019-02-12T11:04:25.659+07:00"),
"unitCost" : 10,
"totalCost" : 300,
},
{
"_id" : 2,
"type" : "In",
"qty" : 40,
"tranDate" : ISODate("2019-02-11T11:04:25.659+07:00"),
"unitCost" : 5,
"totalCost" : 200,
},
{
"_id" : 3,
"type" : "Out",
"qty" : -2,
"tranDate" : ISODate("2019-02-10T11:04:25.659+07:00"),
"unitCost" : 0,
"totalCost" : 0,
},
我只能使用以下javascript代码来获得所需的结果。如何仅使用mongodb聚合来计算unitCost和totalCost所有记录类型,而不是以下JavaScript代码?
let data = db.inventories.find()
.sort({ order: 1 })
.limit(10)
.toArray()
let res = []
_.forEach(data, (doc) => {
if(doc.type==='Out'){
let summary = _.reduce(
data,
(result, o)=> {
if(moment(doc.tranDate).isAfter(o.tranDate))
{
result.totalQty+=o.qty
result.amount+=o.totalCost
}
return result
},
{ totalQty: 0, amount: 0 }
)
doc.unitCost=summary.amount/summary.totalQty
doc.totalCost=doc.qty*doc.unitCost
}
res.push(doc)
})